@luvio/environments 0.138.0 → 0.138.2

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 (43) hide show
  1. package/dist/es/es2018/environments.js +858 -852
  2. package/dist/es/es2018/{DurableStore.d.ts → types/DurableStore.d.ts} +134 -134
  3. package/dist/{umd/es5 → es/es2018/types}/DurableTTLStore.d.ts +25 -25
  4. package/dist/{umd/es5 → es/es2018/types}/events.d.ts +18 -18
  5. package/dist/{umd/es5 → es/es2018/types}/main.d.ts +5 -5
  6. package/dist/es/es2018/{makeDurable → types/makeDurable}/error.d.ts +11 -11
  7. package/dist/es/es2018/{makeDurable → types/makeDurable}/flush.d.ts +4 -4
  8. package/dist/{umd/es5 → es/es2018/types}/makeDurable/revive.d.ts +38 -38
  9. package/dist/es/es2018/{makeDurable → types/makeDurable}/stagingStore.d.ts +6 -6
  10. package/dist/es/es2018/{makeDurable → types/makeDurable}/ttl.d.ts +3 -3
  11. package/dist/es/es2018/{makeDurable → types/makeDurable}/utils.d.ts +2 -2
  12. package/dist/es/es2018/{makeDurable.d.ts → types/makeDurable.d.ts} +44 -44
  13. package/dist/es/es2018/{utils → types/utils}/deep-freeze.d.ts +1 -1
  14. package/dist/es/es2018/{utils → types/utils}/language.d.ts +19 -19
  15. package/dist/umd/es2018/environments.js +858 -852
  16. package/dist/umd/es2018/{DurableStore.d.ts → types/DurableStore.d.ts} +134 -134
  17. package/dist/{es/es2018 → umd/es2018/types}/DurableTTLStore.d.ts +25 -25
  18. package/dist/{es/es2018 → umd/es2018/types}/events.d.ts +18 -18
  19. package/dist/umd/es2018/{main.d.ts → types/main.d.ts} +5 -5
  20. package/dist/umd/{es5 → es2018/types}/makeDurable/error.d.ts +11 -11
  21. package/dist/umd/es2018/{makeDurable → types/makeDurable}/flush.d.ts +4 -4
  22. package/dist/{es/es2018 → umd/es2018/types}/makeDurable/revive.d.ts +38 -38
  23. package/dist/umd/{es5 → es2018/types}/makeDurable/stagingStore.d.ts +6 -6
  24. package/dist/umd/es2018/{makeDurable → types/makeDurable}/ttl.d.ts +3 -3
  25. package/dist/umd/es2018/{makeDurable → types/makeDurable}/utils.d.ts +2 -2
  26. package/dist/umd/{es5 → es2018/types}/makeDurable.d.ts +44 -44
  27. package/dist/umd/es2018/{utils → types/utils}/deep-freeze.d.ts +1 -1
  28. package/dist/umd/es2018/{utils → types/utils}/language.d.ts +19 -19
  29. package/dist/umd/es5/environments.js +942 -936
  30. package/dist/umd/es5/{DurableStore.d.ts → types/DurableStore.d.ts} +134 -134
  31. package/dist/umd/{es2018 → es5/types}/DurableTTLStore.d.ts +25 -25
  32. package/dist/umd/{es2018 → es5/types}/events.d.ts +18 -18
  33. package/dist/{es/es2018 → umd/es5/types}/main.d.ts +5 -5
  34. package/dist/umd/{es2018 → es5/types}/makeDurable/error.d.ts +11 -11
  35. package/dist/umd/es5/{makeDurable → types/makeDurable}/flush.d.ts +4 -4
  36. package/dist/umd/{es2018 → es5/types}/makeDurable/revive.d.ts +38 -38
  37. package/dist/umd/{es2018 → es5/types}/makeDurable/stagingStore.d.ts +6 -6
  38. package/dist/umd/es5/{makeDurable → types/makeDurable}/ttl.d.ts +3 -3
  39. package/dist/umd/es5/{makeDurable → types/makeDurable}/utils.d.ts +2 -2
  40. package/dist/umd/{es2018 → es5/types}/makeDurable.d.ts +44 -44
  41. package/dist/umd/es5/{utils → types/utils}/deep-freeze.d.ts +1 -1
  42. package/dist/umd/es5/{utils → types/utils}/language.d.ts +19 -19
  43. package/package.json +4 -4
@@ -4,880 +4,886 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.luvioEnvironments = {}, global.luvioEngine));
5
5
  })(this, (function (exports, engine) { 'use strict';
6
6
 
7
- // the last version the metadata shape was altered
8
- const DURABLE_METADATA_VERSION = '0.111.0';
9
- function isDeprecatedDurableStoreEntry(durableRecord) {
10
- if (durableRecord.expiration !== undefined) {
11
- return true;
12
- }
13
- const metadata = durableRecord.metadata;
14
- if (metadata !== undefined) {
15
- const { metadataVersion } = metadata;
16
- // eventually we will want to assert that metadataVersion is defined
17
- if (metadataVersion !== undefined && metadataVersion !== DURABLE_METADATA_VERSION) {
18
- return true;
19
- }
20
- }
21
- // Add more deprecated shape checks here
22
- return false;
23
- }
7
+ // the last version the metadata shape was altered
8
+ const DURABLE_METADATA_VERSION = '0.111.0';
9
+ function isDeprecatedDurableStoreEntry(durableRecord) {
10
+ if (durableRecord.expiration !== undefined) {
11
+ return true;
12
+ }
13
+ const metadata = durableRecord.metadata;
14
+ if (metadata !== undefined) {
15
+ const { metadataVersion } = metadata;
16
+ // eventually we will want to assert that metadataVersion is defined
17
+ if (metadataVersion !== undefined && metadataVersion !== DURABLE_METADATA_VERSION) {
18
+ return true;
19
+ }
20
+ }
21
+ // Add more deprecated shape checks here
22
+ return false;
23
+ }
24
24
  const DefaultDurableSegment = 'DEFAULT';
25
25
 
26
- const { keys, create, assign, freeze } = Object;
26
+ const { keys, create, assign, freeze } = Object;
27
27
  const { isArray } = Array;
28
28
 
29
- //Durable store error instrumentation key
30
- const DURABLE_STORE_ERROR = 'durable-store-error';
31
- /**
32
- * Returns a function that processes errors from durable store promise rejections.
33
- * If running in a non-production environment, the error is rethrown.
34
- * When running in production the error is sent to instrumentation.
35
- * @param instrument Instrumentation function implementation
36
- */
37
- function handleDurableStoreRejection(instrument) {
38
- return (error) => {
39
- if (process.env.NODE_ENV !== 'production') {
40
- throw error;
41
- }
42
- if (instrument !== undefined) {
43
- instrument(() => {
44
- return {
45
- [DURABLE_STORE_ERROR]: true,
46
- error: error,
47
- };
48
- });
49
- }
50
- };
29
+ //Durable store error instrumentation key
30
+ const DURABLE_STORE_ERROR = 'durable-store-error';
31
+ /**
32
+ * Returns a function that processes errors from durable store promise rejections.
33
+ * If running in a non-production environment, the error is rethrown.
34
+ * When running in production the error is sent to instrumentation.
35
+ * @param instrument Instrumentation function implementation
36
+ */
37
+ function handleDurableStoreRejection(instrument) {
38
+ return (error) => {
39
+ if (process.env.NODE_ENV !== 'production') {
40
+ throw error;
41
+ }
42
+ if (instrument !== undefined) {
43
+ instrument(() => {
44
+ return {
45
+ [DURABLE_STORE_ERROR]: true,
46
+ error: error,
47
+ };
48
+ });
49
+ }
50
+ };
51
51
  }
52
52
 
53
- function deepFreeze(value) {
54
- // No need to freeze primitives
55
- if (typeof value !== 'object' || value === null) {
56
- return;
57
- }
58
- if (isArray(value)) {
59
- for (let i = 0, len = value.length; i < len; i += 1) {
60
- deepFreeze(value[i]);
61
- }
62
- }
63
- else {
64
- const keys$1 = keys(value);
65
- for (let i = 0, len = keys$1.length; i < len; i += 1) {
66
- deepFreeze(value[keys$1[i]]);
67
- }
68
- }
69
- freeze(value);
53
+ function deepFreeze(value) {
54
+ // No need to freeze primitives
55
+ if (typeof value !== 'object' || value === null) {
56
+ return;
57
+ }
58
+ if (isArray(value)) {
59
+ for (let i = 0, len = value.length; i < len; i += 1) {
60
+ deepFreeze(value[i]);
61
+ }
62
+ }
63
+ else {
64
+ const keys$1 = keys(value);
65
+ for (let i = 0, len = keys$1.length; i < len; i += 1) {
66
+ deepFreeze(value[keys$1[i]]);
67
+ }
68
+ }
69
+ freeze(value);
70
70
  }
71
71
 
72
- function isStoreEntryError(storeRecord) {
73
- return storeRecord.__type === 'error';
72
+ function isStoreEntryError(storeRecord) {
73
+ return storeRecord.__type === 'error';
74
74
  }
75
75
 
76
- /**
77
- * Takes a set of entries from DurableStore and publishes them via the passed in funcs.
78
- * This respects expiration and checks for valid DurableStore data shapes. This should
79
- * be used over manually parsing DurableStoreEntries
80
- *
81
- * @param durableRecords The DurableStoreEntries to parse
82
- * @param publish A function to call with the data of each DurableStoreEntry
83
- * @param publishMetadata A function to call with the metadata of each DurableStoreEntry
84
- * @param pendingWriter the PendingWriter (this is going away soon)
85
- * @returns
86
- */
87
- function publishDurableStoreEntries(durableRecords, publish, publishMetadata) {
88
- const revivedKeys = new engine.StoreKeySet();
89
- let hadUnexpectedShape = false;
90
- if (durableRecords === undefined) {
91
- return { revivedKeys, hadUnexpectedShape };
92
- }
93
- const durableKeys = keys(durableRecords);
94
- if (durableKeys.length === 0) {
95
- // no records to revive
96
- return { revivedKeys, hadUnexpectedShape };
97
- }
98
- for (let i = 0, len = durableKeys.length; i < len; i += 1) {
99
- const key = durableKeys[i];
100
- const durableRecord = durableRecords[key];
101
- if (isDeprecatedDurableStoreEntry(durableRecord)) {
102
- // had the old shape, skip reviving this entry.
103
- hadUnexpectedShape = true;
104
- continue;
105
- }
106
- const { metadata, data } = durableRecord;
107
- if (data === undefined) {
108
- // if unexpected data skip reviving
109
- hadUnexpectedShape = true;
110
- continue;
111
- }
112
- if (metadata !== undefined) {
113
- const { expirationTimestamp } = metadata;
114
- if (expirationTimestamp === undefined) {
115
- // if unexpected expiration data skip reviving
116
- hadUnexpectedShape = true;
117
- continue;
118
- }
119
- publishMetadata(key, metadata);
120
- }
121
- if (isStoreEntryError(data)) {
122
- // freeze errors on way into L1
123
- deepFreeze(data.error);
124
- }
125
- publish(key, data);
126
- revivedKeys.add(key);
127
- }
128
- return { revivedKeys, hadUnexpectedShape };
129
- }
130
- /**
131
- * This method returns a Promise to a snapshot that is revived from L2 cache. If
132
- * L2 does not have the entries necessary to fulfill the snapshot then this method
133
- * will refresh the snapshot from network, and then run the results from network
134
- * through L2 ingestion, returning the subsequent revived snapshot.
135
- */
136
- function reviveSnapshot(baseEnvironment, durableStore,
137
- // TODO [W-10165787]: We should only allow Unfulfilled snapshot be passed in
138
- unavailableSnapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics = { l2Trips: [] }) {
139
- const { recordId, select, seenRecords, state } = unavailableSnapshot;
140
- // L2 can only revive Unfulfilled snapshots that have a selector since they have the
141
- // info needed to revive (like missingLinks) and rebuild. Otherwise return L1 snapshot.
142
- if (state !== 'Unfulfilled' || select === undefined) {
143
- return Promise.resolve({
144
- snapshot: unavailableSnapshot,
145
- metrics: reviveMetrics,
146
- });
147
- }
148
- // in case L1 store changes/deallocs a record while we are doing the async read
149
- // we attempt to read all keys from L2 - so combine recordId with any seenRecords
150
- const keysToReviveSet = new engine.StoreKeySet().add(recordId);
151
- keysToReviveSet.merge(seenRecords);
152
- const keysToRevive = keysToReviveSet.keysAsArray();
153
- const canonicalKeys = keysToRevive.map((x) => engine.serializeStructuredKey(baseEnvironment.storeGetCanonicalKey(x)));
154
- const start = Date.now();
155
- const { l2Trips } = reviveMetrics;
156
- return durableStore.getEntries(canonicalKeys, DefaultDurableSegment).then((durableRecords) => {
157
- l2Trips.push({
158
- duration: Date.now() - start,
159
- keysRequestedCount: canonicalKeys.length,
160
- });
161
- const { revivedKeys, hadUnexpectedShape } = publishDurableStoreEntries(durableRecords,
162
- // TODO [W-10072584]: instead of implicitly using L1 we should take in
163
- // publish and publishMetadata funcs, so callers can decide where to
164
- // revive to (like they pass in how to do the buildL1Snapshot)
165
- baseEnvironment.storePublish.bind(baseEnvironment), baseEnvironment.publishStoreMetadata.bind(baseEnvironment));
166
- // if the data coming back from DS had an unexpected shape then just
167
- // return the L1 snapshot
168
- if (hadUnexpectedShape === true) {
169
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
170
- }
171
- if (revivedKeys.size() === 0) {
172
- // durable store doesn't have what we asked for so return L1 snapshot
173
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
174
- }
175
- // try building the snapshot from L1 now that we have revived the missingLinks
176
- const snapshot = buildL1Snapshot();
177
- // if snapshot is pending then some other in-flight refresh will broadcast
178
- // later
179
- if (snapshot.state === 'Pending') {
180
- return { snapshot, metrics: reviveMetrics };
181
- }
182
- if (snapshot.state === 'Unfulfilled') {
183
- // have to check if the new snapshot has any additional seenRecords
184
- // and revive again if so
185
- const { seenRecords: newSnapshotSeenRecords, recordId: newSnapshotRecordId } = snapshot;
186
- const newKeysToReviveSet = new engine.StoreKeySet();
187
- newKeysToReviveSet.add(newSnapshotRecordId);
188
- newKeysToReviveSet.merge(newSnapshotSeenRecords);
189
- const newKeys = newKeysToReviveSet.keysAsArray();
190
- // in case DS returned additional entries we combine the requested
191
- // and returned keys
192
- const alreadyRequestedOrRevivedSet = keysToReviveSet;
193
- alreadyRequestedOrRevivedSet.merge(revivedKeys);
194
- // if there's any seen keys in the newly rebuilt snapshot that
195
- // haven't already been requested or returned then revive again
196
- for (let i = 0, len = newKeys.length; i < len; i++) {
197
- const newSnapshotSeenKey = newKeys[i];
198
- if (!alreadyRequestedOrRevivedSet.has(newSnapshotSeenKey)) {
199
- return reviveSnapshot(baseEnvironment, durableStore, snapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics);
200
- }
201
- }
202
- }
203
- return { snapshot, metrics: reviveMetrics };
204
- }, (error) => {
205
- durableStoreErrorHandler(error);
206
- // getEntries failed, return the L1 snapshot
207
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
208
- });
76
+ /**
77
+ * Takes a set of entries from DurableStore and publishes them via the passed in funcs.
78
+ * This respects expiration and checks for valid DurableStore data shapes. This should
79
+ * be used over manually parsing DurableStoreEntries
80
+ *
81
+ * @param durableRecords The DurableStoreEntries to parse
82
+ * @param publish A function to call with the data of each DurableStoreEntry
83
+ * @param publishMetadata A function to call with the metadata of each DurableStoreEntry
84
+ * @param pendingWriter the PendingWriter (this is going away soon)
85
+ * @returns
86
+ */
87
+ function publishDurableStoreEntries(durableRecords, publish, publishMetadata) {
88
+ const revivedKeys = new engine.StoreKeySet();
89
+ let hadUnexpectedShape = false;
90
+ if (durableRecords === undefined) {
91
+ return { revivedKeys, hadUnexpectedShape };
92
+ }
93
+ const durableKeys = keys(durableRecords);
94
+ if (durableKeys.length === 0) {
95
+ // no records to revive
96
+ return { revivedKeys, hadUnexpectedShape };
97
+ }
98
+ for (let i = 0, len = durableKeys.length; i < len; i += 1) {
99
+ const key = durableKeys[i];
100
+ const durableRecord = durableRecords[key];
101
+ if (isDeprecatedDurableStoreEntry(durableRecord)) {
102
+ // had the old shape, skip reviving this entry.
103
+ hadUnexpectedShape = true;
104
+ continue;
105
+ }
106
+ const { metadata, data } = durableRecord;
107
+ if (data === undefined) {
108
+ // if unexpected data skip reviving
109
+ hadUnexpectedShape = true;
110
+ continue;
111
+ }
112
+ if (metadata !== undefined) {
113
+ const { expirationTimestamp } = metadata;
114
+ if (expirationTimestamp === undefined) {
115
+ // if unexpected expiration data skip reviving
116
+ hadUnexpectedShape = true;
117
+ continue;
118
+ }
119
+ publishMetadata(key, metadata);
120
+ }
121
+ if (isStoreEntryError(data)) {
122
+ // freeze errors on way into L1
123
+ deepFreeze(data.error);
124
+ }
125
+ publish(key, data);
126
+ revivedKeys.add(key);
127
+ }
128
+ return { revivedKeys, hadUnexpectedShape };
129
+ }
130
+ /**
131
+ * This method returns a Promise to a snapshot that is revived from L2 cache. If
132
+ * L2 does not have the entries necessary to fulfill the snapshot then this method
133
+ * will refresh the snapshot from network, and then run the results from network
134
+ * through L2 ingestion, returning the subsequent revived snapshot.
135
+ */
136
+ function reviveSnapshot(baseEnvironment, durableStore,
137
+ // TODO [W-10165787]: We should only allow Unfulfilled snapshot be passed in
138
+ unavailableSnapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics = { l2Trips: [] }) {
139
+ const { recordId, select, seenRecords, state } = unavailableSnapshot;
140
+ // L2 can only revive Unfulfilled snapshots that have a selector since they have the
141
+ // info needed to revive (like missingLinks) and rebuild. Otherwise return L1 snapshot.
142
+ if (state !== 'Unfulfilled' || select === undefined) {
143
+ return Promise.resolve({
144
+ snapshot: unavailableSnapshot,
145
+ metrics: reviveMetrics,
146
+ });
147
+ }
148
+ // in case L1 store changes/deallocs a record while we are doing the async read
149
+ // we attempt to read all keys from L2 - so combine recordId with any seenRecords
150
+ const keysToReviveSet = new engine.StoreKeySet().add(recordId);
151
+ keysToReviveSet.merge(seenRecords);
152
+ const keysToRevive = keysToReviveSet.keysAsArray();
153
+ const canonicalKeys = keysToRevive.map((x) => engine.serializeStructuredKey(baseEnvironment.storeGetCanonicalKey(x)));
154
+ const start = Date.now();
155
+ const { l2Trips } = reviveMetrics;
156
+ return durableStore.getEntries(canonicalKeys, DefaultDurableSegment).then((durableRecords) => {
157
+ l2Trips.push({
158
+ duration: Date.now() - start,
159
+ keysRequestedCount: canonicalKeys.length,
160
+ });
161
+ const { revivedKeys, hadUnexpectedShape } = publishDurableStoreEntries(durableRecords,
162
+ // TODO [W-10072584]: instead of implicitly using L1 we should take in
163
+ // publish and publishMetadata funcs, so callers can decide where to
164
+ // revive to (like they pass in how to do the buildL1Snapshot)
165
+ baseEnvironment.storePublish.bind(baseEnvironment), baseEnvironment.publishStoreMetadata.bind(baseEnvironment));
166
+ // if the data coming back from DS had an unexpected shape then just
167
+ // return the L1 snapshot
168
+ if (hadUnexpectedShape === true) {
169
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
170
+ }
171
+ if (revivedKeys.size() === 0) {
172
+ // durable store doesn't have what we asked for so return L1 snapshot
173
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
174
+ }
175
+ // try building the snapshot from L1 now that we have revived the missingLinks
176
+ const snapshot = buildL1Snapshot();
177
+ // if snapshot is pending then some other in-flight refresh will broadcast
178
+ // later
179
+ if (snapshot.state === 'Pending') {
180
+ return { snapshot, metrics: reviveMetrics };
181
+ }
182
+ if (snapshot.state === 'Unfulfilled') {
183
+ // have to check if the new snapshot has any additional seenRecords
184
+ // and revive again if so
185
+ const { seenRecords: newSnapshotSeenRecords, recordId: newSnapshotRecordId } = snapshot;
186
+ const newKeysToReviveSet = new engine.StoreKeySet();
187
+ newKeysToReviveSet.add(newSnapshotRecordId);
188
+ newKeysToReviveSet.merge(newSnapshotSeenRecords);
189
+ const newKeys = newKeysToReviveSet.keysAsArray();
190
+ // in case DS returned additional entries we combine the requested
191
+ // and returned keys
192
+ const alreadyRequestedOrRevivedSet = keysToReviveSet;
193
+ alreadyRequestedOrRevivedSet.merge(revivedKeys);
194
+ // if there's any seen keys in the newly rebuilt snapshot that
195
+ // haven't already been requested or returned then revive again
196
+ for (let i = 0, len = newKeys.length; i < len; i++) {
197
+ const newSnapshotSeenKey = newKeys[i];
198
+ if (!alreadyRequestedOrRevivedSet.has(newSnapshotSeenKey)) {
199
+ return reviveSnapshot(baseEnvironment, durableStore, snapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics);
200
+ }
201
+ }
202
+ }
203
+ return { snapshot, metrics: reviveMetrics };
204
+ }, (error) => {
205
+ durableStoreErrorHandler(error);
206
+ // getEntries failed, return the L1 snapshot
207
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
208
+ });
209
209
  }
210
210
 
211
- const TTL_DURABLE_SEGMENT = 'TTL_DURABLE_SEGMENT';
212
- const TTL_DEFAULT_KEY = 'TTL_DEFAULT_KEY';
213
- function buildDurableTTLOverrideStoreKey(namespace, representationName) {
214
- return `${namespace}::${representationName}`;
215
- }
216
- function isEntryDurableTTLOverride(entry) {
217
- if (typeof entry === 'object' && entry !== undefined && entry !== null) {
218
- const data = entry.data;
219
- if (data !== undefined) {
220
- return (data.namespace !== undefined &&
221
- data.representationName !== undefined &&
222
- data.ttl !== undefined);
223
- }
224
- }
225
- return false;
226
- }
227
- function isDefaultDurableTTLOverride(override) {
228
- return (override.namespace === TTL_DEFAULT_KEY && override.representationName === TTL_DEFAULT_KEY);
229
- }
230
- /**
231
- * Class to set and get the TTL override values in the Durable Store
232
- */
233
- class DurableTTLStore {
234
- constructor(durableStore) {
235
- this.durableStore = durableStore;
236
- }
237
- setDefaultDurableTTLOverrides(ttl) {
238
- return this.durableStore.setEntries({
239
- [buildDurableTTLOverrideStoreKey(TTL_DEFAULT_KEY, TTL_DEFAULT_KEY)]: {
240
- data: {
241
- namespace: TTL_DEFAULT_KEY,
242
- representationName: TTL_DEFAULT_KEY,
243
- ttl,
244
- },
245
- },
246
- }, TTL_DURABLE_SEGMENT);
247
- }
248
- setDurableTTLOverride(namespace, representationName, ttl) {
249
- return this.durableStore.setEntries({
250
- [buildDurableTTLOverrideStoreKey(namespace, representationName)]: {
251
- data: { namespace, representationName, ttl },
252
- },
253
- }, TTL_DURABLE_SEGMENT);
254
- }
255
- getDurableTTLOverrides() {
256
- return this.durableStore
257
- .getAllEntries(TTL_DURABLE_SEGMENT)
258
- .then((entries) => {
259
- const overrides = [];
260
- let defaultTTL = undefined;
261
- if (entries === undefined) {
262
- return {
263
- defaultTTL,
264
- overrides,
265
- };
266
- }
267
- const keys$1 = keys(entries);
268
- for (let i = 0, len = keys$1.length; i < len; i++) {
269
- const key = keys$1[i];
270
- const entry = entries[key];
271
- if (entry !== undefined && isEntryDurableTTLOverride(entry)) {
272
- if (isDefaultDurableTTLOverride(entry.data)) {
273
- defaultTTL = entry.data;
274
- }
275
- else {
276
- overrides.push(entry.data);
277
- }
278
- }
279
- }
280
- return {
281
- defaultTTL,
282
- overrides,
283
- };
284
- });
285
- }
211
+ const TTL_DURABLE_SEGMENT = 'TTL_DURABLE_SEGMENT';
212
+ const TTL_DEFAULT_KEY = 'TTL_DEFAULT_KEY';
213
+ function buildDurableTTLOverrideStoreKey(namespace, representationName) {
214
+ return `${namespace}::${representationName}`;
215
+ }
216
+ function isEntryDurableTTLOverride(entry) {
217
+ if (typeof entry === 'object' && entry !== undefined && entry !== null) {
218
+ const data = entry.data;
219
+ if (data !== undefined) {
220
+ return (data.namespace !== undefined &&
221
+ data.representationName !== undefined &&
222
+ data.ttl !== undefined);
223
+ }
224
+ }
225
+ return false;
226
+ }
227
+ function isDefaultDurableTTLOverride(override) {
228
+ return (override.namespace === TTL_DEFAULT_KEY && override.representationName === TTL_DEFAULT_KEY);
229
+ }
230
+ /**
231
+ * Class to set and get the TTL override values in the Durable Store
232
+ */
233
+ class DurableTTLStore {
234
+ constructor(durableStore) {
235
+ this.durableStore = durableStore;
236
+ }
237
+ setDefaultDurableTTLOverrides(ttl) {
238
+ return this.durableStore.setEntries({
239
+ [buildDurableTTLOverrideStoreKey(TTL_DEFAULT_KEY, TTL_DEFAULT_KEY)]: {
240
+ data: {
241
+ namespace: TTL_DEFAULT_KEY,
242
+ representationName: TTL_DEFAULT_KEY,
243
+ ttl,
244
+ },
245
+ },
246
+ }, TTL_DURABLE_SEGMENT);
247
+ }
248
+ setDurableTTLOverride(namespace, representationName, ttl) {
249
+ return this.durableStore.setEntries({
250
+ [buildDurableTTLOverrideStoreKey(namespace, representationName)]: {
251
+ data: { namespace, representationName, ttl },
252
+ },
253
+ }, TTL_DURABLE_SEGMENT);
254
+ }
255
+ getDurableTTLOverrides() {
256
+ return this.durableStore
257
+ .getAllEntries(TTL_DURABLE_SEGMENT)
258
+ .then((entries) => {
259
+ const overrides = [];
260
+ let defaultTTL = undefined;
261
+ if (entries === undefined) {
262
+ return {
263
+ defaultTTL,
264
+ overrides,
265
+ };
266
+ }
267
+ const keys$1 = keys(entries);
268
+ for (let i = 0, len = keys$1.length; i < len; i++) {
269
+ const key = keys$1[i];
270
+ const entry = entries[key];
271
+ if (entry !== undefined && isEntryDurableTTLOverride(entry)) {
272
+ if (isDefaultDurableTTLOverride(entry.data)) {
273
+ defaultTTL = entry.data;
274
+ }
275
+ else {
276
+ overrides.push(entry.data);
277
+ }
278
+ }
279
+ }
280
+ return {
281
+ defaultTTL,
282
+ overrides,
283
+ };
284
+ });
285
+ }
286
286
  }
287
287
 
288
- function copy(source) {
289
- if (typeof source !== 'object' || source === null) {
290
- return source;
291
- }
292
- if (isArray(source)) {
293
- // TS doesn't trust that this new array is an array unless we cast it
294
- return [...source];
295
- }
296
- return { ...source };
297
- }
298
- function flushInMemoryStoreValuesToDurableStore(store, durableStore, durableStoreErrorHandler) {
299
- const durableRecords = create(null);
300
- const evictedRecords = create(null);
301
- const { records, metadata: storeMetadata, visitedIds, refreshedIds, } = store.fallbackStringKeyInMemoryStore;
302
- // TODO: W-8909393 Once metadata is stored in its own segment we need to
303
- // call setEntries for the visitedIds on default segment and call setEntries
304
- // on the metadata segment for the refreshedIds
305
- const keys$1 = keys({ ...visitedIds, ...refreshedIds });
306
- for (let i = 0, len = keys$1.length; i < len; i += 1) {
307
- const key = keys$1[i];
308
- const record = records[key];
309
- // this record has been evicted, evict from DS
310
- if (record === undefined) {
311
- evictedRecords[key] = true;
312
- continue;
313
- }
314
- const metadata = storeMetadata[key];
315
- durableRecords[key] = {
316
- // copy the data in case the store is mutated during the
317
- // async setEntries call
318
- data: copy(record),
319
- };
320
- if (metadata !== undefined) {
321
- durableRecords[key].metadata = {
322
- ...metadata,
323
- metadataVersion: DURABLE_METADATA_VERSION,
324
- };
325
- }
326
- }
327
- const durableStoreOperations = [];
328
- // publishes
329
- const recordKeys = keys(durableRecords);
330
- if (recordKeys.length > 0) {
331
- durableStoreOperations.push({
332
- type: 'setEntries',
333
- entries: durableRecords,
334
- segment: DefaultDurableSegment,
335
- });
336
- }
337
- // evicts
338
- const evictedKeys = keys(evictedRecords);
339
- if (evictedKeys.length > 0) {
340
- durableStoreOperations.push({
341
- type: 'evictEntries',
342
- ids: evictedKeys,
343
- segment: DefaultDurableSegment,
344
- });
345
- }
346
- if (durableStoreOperations.length > 0) {
347
- return durableStore.batchOperations(durableStoreOperations).catch(durableStoreErrorHandler);
348
- }
349
- return Promise.resolve();
288
+ function copy(source) {
289
+ if (typeof source !== 'object' || source === null) {
290
+ return source;
291
+ }
292
+ if (isArray(source)) {
293
+ // TS doesn't trust that this new array is an array unless we cast it
294
+ return [...source];
295
+ }
296
+ return { ...source };
297
+ }
298
+ function flushInMemoryStoreValuesToDurableStore(store, durableStore, durableStoreErrorHandler) {
299
+ const durableRecords = create(null);
300
+ const evictedRecords = create(null);
301
+ const { records, metadata: storeMetadata, visitedIds, refreshedIds, } = store.fallbackStringKeyInMemoryStore;
302
+ // TODO: W-8909393 Once metadata is stored in its own segment we need to
303
+ // call setEntries for the visitedIds on default segment and call setEntries
304
+ // on the metadata segment for the refreshedIds
305
+ const keys$1 = keys({ ...visitedIds, ...refreshedIds });
306
+ for (let i = 0, len = keys$1.length; i < len; i += 1) {
307
+ const key = keys$1[i];
308
+ const record = records[key];
309
+ // this record has been evicted, evict from DS
310
+ if (record === undefined) {
311
+ evictedRecords[key] = true;
312
+ continue;
313
+ }
314
+ const metadata = storeMetadata[key];
315
+ durableRecords[key] = {
316
+ // copy the data in case the store is mutated during the
317
+ // async setEntries call
318
+ data: copy(record),
319
+ };
320
+ if (metadata !== undefined) {
321
+ durableRecords[key].metadata = {
322
+ ...metadata,
323
+ metadataVersion: DURABLE_METADATA_VERSION,
324
+ };
325
+ }
326
+ }
327
+ const durableStoreOperations = [];
328
+ // publishes
329
+ const recordKeys = keys(durableRecords);
330
+ if (recordKeys.length > 0) {
331
+ durableStoreOperations.push({
332
+ type: 'setEntries',
333
+ entries: durableRecords,
334
+ segment: DefaultDurableSegment,
335
+ });
336
+ }
337
+ // evicts
338
+ const evictedKeys = keys(evictedRecords);
339
+ if (evictedKeys.length > 0) {
340
+ durableStoreOperations.push({
341
+ type: 'evictEntries',
342
+ ids: evictedKeys,
343
+ segment: DefaultDurableSegment,
344
+ });
345
+ }
346
+ if (durableStoreOperations.length > 0) {
347
+ return durableStore.batchOperations(durableStoreOperations).catch(durableStoreErrorHandler);
348
+ }
349
+ return Promise.resolve();
350
350
  }
351
351
 
352
- const DurableEnvironmentEventDiscriminator = 'durable';
353
- function isDurableEnvironmentEvent(event) {
354
- return (event.type === 'environment' && event.environment === DurableEnvironmentEventDiscriminator);
355
- }
356
- function emitDurableEnvironmentAdapterEvent(eventData, observers) {
357
- engine.emitAdapterEvent({
358
- type: 'environment',
359
- timestamp: Date.now(),
360
- environment: DurableEnvironmentEventDiscriminator,
361
- data: eventData,
362
- }, observers);
352
+ const DurableEnvironmentEventDiscriminator = 'durable';
353
+ function isDurableEnvironmentEvent(event) {
354
+ return (event.type === 'environment' && event.environment === DurableEnvironmentEventDiscriminator);
355
+ }
356
+ function emitDurableEnvironmentAdapterEvent(eventData, observers) {
357
+ engine.emitAdapterEvent({
358
+ type: 'environment',
359
+ timestamp: Date.now(),
360
+ environment: DurableEnvironmentEventDiscriminator,
361
+ data: eventData,
362
+ }, observers);
363
363
  }
364
364
 
365
- async function reviveTTLOverrides(ttlStore, environment) {
366
- const map = await ttlStore.getDurableTTLOverrides();
367
- const { defaultTTL, overrides } = map;
368
- if (defaultTTL !== undefined) {
369
- environment.storeSetDefaultTTLOverride(defaultTTL.ttl);
370
- }
371
- for (let i = 0, len = overrides.length; i < len; i++) {
372
- const { namespace, representationName, ttl } = overrides[i];
373
- environment.storeSetTTLOverride(namespace, representationName, ttl);
374
- }
365
+ async function reviveTTLOverrides(ttlStore, environment) {
366
+ const map = await ttlStore.getDurableTTLOverrides();
367
+ const { defaultTTL, overrides } = map;
368
+ if (defaultTTL !== undefined) {
369
+ environment.storeSetDefaultTTLOverride(defaultTTL.ttl);
370
+ }
371
+ for (let i = 0, len = overrides.length; i < len; i++) {
372
+ const { namespace, representationName, ttl } = overrides[i];
373
+ environment.storeSetTTLOverride(namespace, representationName, ttl);
374
+ }
375
375
  }
376
376
 
377
- /**
378
- * Returns an empty InMemoryStore that can be used for ingestion. Copies over
379
- * the TTLOverrides from the given Environment's Store.
380
- */
381
- function buildIngestStagingStore(environment) {
382
- return environment.storeBuildIngestionStagingStore();
377
+ /**
378
+ * Returns an empty InMemoryStore that can be used for ingestion. Copies over
379
+ * the TTLOverrides from the given Environment's Store.
380
+ */
381
+ function buildIngestStagingStore(environment) {
382
+ return environment.storeBuildIngestionStagingStore();
383
383
  }
384
384
 
385
- const AdapterContextSegment = 'ADAPTER-CONTEXT';
386
- const ADAPTER_CONTEXT_ID_SUFFIX = '__NAMED_CONTEXT';
387
- async function reviveOrCreateContext(adapterId, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded) {
388
- // initialize empty context store
389
- contextStores[adapterId] = create(null);
390
- const context = {
391
- set(key, value) {
392
- contextStores[adapterId][key] = value;
393
- durableStore.setEntries({
394
- [adapterId]: { data: contextStores[adapterId] },
395
- }, AdapterContextSegment);
396
- pendingContextStoreKeys.add(adapterId);
397
- },
398
- get(key) {
399
- return contextStores[adapterId][key];
400
- },
401
- };
402
- const contextReturn = () => {
403
- if (onContextLoaded !== undefined) {
404
- return onContextLoaded(context).then(() => {
405
- return context;
406
- });
407
- }
408
- return context;
409
- };
410
- try {
411
- const entries = await durableStore.getEntries([adapterId], AdapterContextSegment);
412
- if (entries !== undefined && entries[adapterId] !== undefined) {
413
- // if durable store has a saved context then load it in the store
414
- contextStores[adapterId] = entries[adapterId].data;
415
- }
416
- }
417
- catch (error) {
418
- durableStoreErrorHandler(error);
419
- }
420
- return contextReturn();
421
- }
422
- function isUnfulfilledSnapshot(cachedSnapshotResult) {
423
- if (cachedSnapshotResult === undefined) {
424
- return false;
425
- }
426
- if ('then' in cachedSnapshotResult) {
427
- return false;
428
- }
429
- return cachedSnapshotResult.state === 'Unfulfilled';
430
- }
431
- /**
432
- * Configures the environment to persist data into a durable store and attempt to resolve
433
- * data from the persistent store before hitting the network.
434
- *
435
- * @param environment The base environment
436
- * @param durableStore A DurableStore implementation
437
- * @param instrumentation An instrumentation function implementation
438
- */
439
- function makeDurable(environment, { durableStore, instrumentation }) {
440
- let ingestStagingStore = null;
441
- const durableTTLStore = new DurableTTLStore(durableStore);
442
- const mergeKeysPromiseMap = new engine.StoreKeyMap();
443
- // When a context store is mutated we write it to L2, which causes DS on change
444
- // event. If this instance of makeDurable caused that L2 write we can ignore that
445
- // on change event. This Set helps us do that.
446
- const pendingContextStoreKeys = new Set();
447
- const contextStores = create(null);
448
- let initializationPromise = new Promise((resolve) => {
449
- const finish = () => {
450
- resolve();
451
- initializationPromise = undefined;
452
- };
453
- reviveTTLOverrides(durableTTLStore, environment).then(finish);
454
- });
455
- //instrumentation for durable store errors
456
- const durableStoreErrorHandler = handleDurableStoreRejection(instrumentation);
457
- let disposed = false;
458
- const validateNotDisposed = () => {
459
- if (disposed === true) {
460
- throw new Error('This makeDurable instance has been disposed');
461
- }
462
- };
463
- const unsubscribe = durableStore.registerOnChangedListener(async (changes) => {
464
- const defaultSegmentKeys = [];
465
- const adapterContextSegmentKeys = [];
466
- for (let i = 0, len = changes.length; i < len; i++) {
467
- const change = changes[i];
468
- // we only care about changes to the data which is stored in the default
469
- // segment or the adapter context
470
- if (change.segment === DefaultDurableSegment) {
471
- defaultSegmentKeys.push(...change.ids);
472
- }
473
- else if (change.segment === AdapterContextSegment) {
474
- adapterContextSegmentKeys.push(...change.ids);
475
- }
476
- }
477
- // process adapter context changes
478
- const adapterContextKeysFromDifferentInstance = [];
479
- for (const key of adapterContextSegmentKeys) {
480
- if (pendingContextStoreKeys.has(key)) {
481
- // if this instance caused the L2 write then remove from the
482
- // "pending" Set and move on
483
- pendingContextStoreKeys.delete(key);
484
- }
485
- else {
486
- // else it came from another luvio instance and we need to
487
- // read from L2
488
- adapterContextKeysFromDifferentInstance.push(key);
489
- }
490
- }
491
- if (adapterContextKeysFromDifferentInstance.length > 0) {
492
- try {
493
- const entries = await durableStore.getEntries(adapterContextKeysFromDifferentInstance, AdapterContextSegment);
494
- if (entries !== undefined) {
495
- const entryKeys = keys(entries);
496
- for (let i = 0, len = entryKeys.length; i < len; i++) {
497
- const entryKey = entryKeys[i];
498
- const entry = entries[entryKey];
499
- contextStores[entryKey] = entry.data;
500
- }
501
- }
502
- }
503
- catch (error) {
504
- durableStoreErrorHandler(error);
505
- }
506
- }
507
- // process default segment changes
508
- const defaultSegmentKeysLength = defaultSegmentKeys.length;
509
- if (defaultSegmentKeysLength > 0) {
510
- for (let i = 0; i < defaultSegmentKeysLength; i++) {
511
- const key = defaultSegmentKeys[i];
512
- const canonical = environment.storeGetCanonicalKey(key);
513
- if (canonical !== key) {
514
- continue;
515
- }
516
- // TODO: W-8909393 If expiration is the only thing that changed we should not evict the data... so
517
- // if we stored expiration and data at different keys (or same keys in different segments)
518
- // then we could know if only the expiration has changed and we wouldn't need to evict
519
- // and go through an entire broadcast/revive cycle for unchanged data
520
- // call base environment storeEvict so this evict is not tracked for durable deletion
521
- environment.storeEvict(key);
522
- }
523
- await environment.storeBroadcast(rebuildSnapshot, environment.snapshotAvailable);
524
- }
525
- });
526
- const dispose = function () {
527
- validateNotDisposed();
528
- disposed = true;
529
- return unsubscribe();
530
- };
531
- const storePublish = function (key, data) {
532
- validateNotDisposed();
533
- if (ingestStagingStore === null) {
534
- ingestStagingStore = buildIngestStagingStore(environment);
535
- }
536
- ingestStagingStore.publish(key, data);
537
- // remove record from main luvio L1 cache while we are on the synchronous path
538
- // because we do not want some other code attempting to use the
539
- // in-memory values before the durable store onChanged handler
540
- // calls back and revives the values to in-memory
541
- environment.storeEvict(key);
542
- };
543
- const publishStoreMetadata = function (recordId, storeMetadata) {
544
- validateNotDisposed();
545
- if (ingestStagingStore === null) {
546
- ingestStagingStore = buildIngestStagingStore(environment);
547
- }
548
- ingestStagingStore.publishMetadata(recordId, storeMetadata);
549
- };
550
- const storeIngest = function (key, ingest, response, luvio) {
551
- validateNotDisposed();
552
- // we don't ingest to the luvio L1 store from network directly, we ingest to
553
- // L2 and let DurableStore on change event revive keys into luvio L1 store
554
- if (ingestStagingStore === null) {
555
- ingestStagingStore = buildIngestStagingStore(environment);
556
- }
557
- environment.storeIngest(key, ingest, response, luvio, ingestStagingStore);
558
- };
559
- const storeIngestError = function (key, errorSnapshot, storeMetadataParams, _storeOverride) {
560
- validateNotDisposed();
561
- if (ingestStagingStore === null) {
562
- ingestStagingStore = buildIngestStagingStore(environment);
563
- }
564
- environment.storeIngestError(key, errorSnapshot, storeMetadataParams, ingestStagingStore);
565
- };
566
- const storeBroadcast = function (_rebuildSnapshot, _snapshotDataAvailable) {
567
- validateNotDisposed();
568
- // publishing to L2 is essentially "broadcasting" because the onChanged
569
- // handler will fire which will revive records to the main L1 store and
570
- // call the base storeBroadcast
571
- return publishChangesToDurableStore();
572
- };
573
- const publishChangesToDurableStore = function () {
574
- validateNotDisposed();
575
- if (ingestStagingStore === null) {
576
- return Promise.resolve();
577
- }
578
- const promise = flushInMemoryStoreValuesToDurableStore(ingestStagingStore, durableStore, durableStoreErrorHandler);
579
- ingestStagingStore = null;
580
- return promise;
581
- };
582
- const storeLookup = function (sel, createSnapshot, refresh, ttlStrategy) {
583
- validateNotDisposed();
584
- // if this lookup is right after an ingest there will be a staging store
585
- if (ingestStagingStore !== null) {
586
- const reader = new engine.Reader(ingestStagingStore, sel.variables, refresh, undefined, ttlStrategy);
587
- return reader.read(sel);
588
- }
589
- // otherwise this is from buildCachedSnapshot and we should use the luvio
590
- // L1 store
591
- return environment.storeLookup(sel, createSnapshot, refresh, ttlStrategy);
592
- };
593
- const storeEvict = function (key) {
594
- validateNotDisposed();
595
- if (ingestStagingStore === null) {
596
- ingestStagingStore = buildIngestStagingStore(environment);
597
- }
598
- ingestStagingStore.evict(key);
599
- };
600
- const getNode = function (key) {
601
- validateNotDisposed();
602
- if (ingestStagingStore === null) {
603
- ingestStagingStore = buildIngestStagingStore(environment);
604
- }
605
- return environment.getNode(key, ingestStagingStore);
606
- };
607
- const wrapNormalizedGraphNode = function (normalized) {
608
- validateNotDisposed();
609
- if (ingestStagingStore === null) {
610
- ingestStagingStore = buildIngestStagingStore(environment);
611
- }
612
- return environment.wrapNormalizedGraphNode(normalized, ingestStagingStore);
613
- };
614
- const rebuildSnapshot = function (snapshot, onRebuild) {
615
- validateNotDisposed();
616
- // try rebuilding from memory
617
- environment.rebuildSnapshot(snapshot, (rebuilt) => {
618
- // only try reviving from durable store if snapshot is unfulfilled
619
- if (rebuilt.state !== 'Unfulfilled') {
620
- onRebuild(rebuilt);
621
- return;
622
- }
623
- // Do an L2 revive and emit to subscriber using the callback.
624
- reviveSnapshot(environment, durableStore, rebuilt, durableStoreErrorHandler, () => {
625
- // reviveSnapshot will revive into L1, and since "records" is a reference
626
- // (and not a copy) to the L1 records we can use it for rebuild
627
- let rebuiltSnap;
628
- environment.rebuildSnapshot(snapshot, (rebuilt) => {
629
- rebuiltSnap = rebuilt;
630
- });
631
- return rebuiltSnap;
632
- }).then((result) => {
633
- onRebuild(result.snapshot);
634
- });
635
- });
636
- };
637
- const withContext = function (adapter, options) {
638
- validateNotDisposed();
639
- const { contextId, contextVersion, onContextLoaded } = options;
640
- let context = undefined;
641
- let contextKey = `${contextId}`;
642
- // if a context version is supplied, key with the version encoded
643
- if (contextVersion !== undefined) {
644
- contextKey += `::${contextVersion}`;
645
- }
646
- contextKey += ADAPTER_CONTEXT_ID_SUFFIX;
647
- const contextAsPromise = reviveOrCreateContext(contextKey, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded);
648
- return (config, requestContext) => {
649
- if (context === undefined) {
650
- return contextAsPromise.then((revivedContext) => {
651
- context = revivedContext;
652
- return adapter(config, context, requestContext); // TODO - remove as any cast after https://github.com/salesforce-experience-platform-emu/luvio/pull/230
653
- });
654
- }
655
- return adapter(config, context, requestContext);
656
- };
657
- };
658
- const storeRedirect = function (existingKey, canonicalKey) {
659
- validateNotDisposed();
660
- // call redirect on staging store so "old" keys are removed from L2 on
661
- // the next publishChangesToDurableStore. NOTE: we don't need to call
662
- // redirect on the base environment store because staging store and base
663
- // L1 store share the same redirect and reverseRedirectKeys
664
- if (ingestStagingStore === null) {
665
- ingestStagingStore = buildIngestStagingStore(environment);
666
- }
667
- ingestStagingStore.redirect(existingKey, canonicalKey);
668
- };
669
- const storeSetTTLOverride = function (namespace, representationName, ttl) {
670
- validateNotDisposed();
671
- return Promise.all([
672
- environment.storeSetTTLOverride(namespace, representationName, ttl),
673
- durableTTLStore.setDurableTTLOverride(namespace, representationName, ttl),
674
- ]).then();
675
- };
676
- const storeSetDefaultTTLOverride = function (ttl) {
677
- validateNotDisposed();
678
- return Promise.all([
679
- environment.storeSetDefaultTTLOverride(ttl),
680
- durableTTLStore.setDefaultDurableTTLOverrides(ttl),
681
- ]).then();
682
- };
683
- const getDurableTTLOverrides = function () {
684
- validateNotDisposed();
685
- return durableTTLStore.getDurableTTLOverrides();
686
- };
687
- const dispatchResourceRequest = async function (request, context, eventObservers) {
688
- validateNotDisposed();
689
- // non-GET adapters call dispatchResourceRequest before any other luvio
690
- // function so this is our chance to ensure we're initialized
691
- if (initializationPromise !== undefined) {
692
- await initializationPromise;
693
- }
694
- return environment.dispatchResourceRequest(request, context, eventObservers);
695
- };
696
- // NOTE: we can't use "async" keyword on this function because that would
697
- // force it to always be an async response. The signature is a union
698
- // of sync/async so no "awaiting" in this function, just promise-chaining
699
- const applyCachePolicy = function (luvio, adapterRequestContext, buildSnapshotContext, buildCachedSnapshot, buildNetworkSnapshot) {
700
- validateNotDisposed();
701
- const wrappedCacheLookup = (injectedBuildSnapshotContext, injectedStoreLookup) => {
702
- const snapshot = buildCachedSnapshot(injectedBuildSnapshotContext, injectedStoreLookup, luvio);
703
- // if the adapter attempted to do an L1 lookup and it was unfulfilled
704
- // then we can attempt an L2 lookup
705
- if (isUnfulfilledSnapshot(snapshot)) {
706
- const start = Date.now();
707
- emitDurableEnvironmentAdapterEvent({ type: 'l2-revive-start' }, adapterRequestContext.eventObservers);
708
- const revivedSnapshot = reviveSnapshot(environment, durableStore, snapshot, durableStoreErrorHandler, () => injectedStoreLookup(snapshot.select, snapshot.refresh)).then((result) => {
709
- emitDurableEnvironmentAdapterEvent({
710
- type: 'l2-revive-end',
711
- snapshot: result.snapshot,
712
- duration: Date.now() - start,
713
- l2Trips: result.metrics.l2Trips,
714
- }, adapterRequestContext.eventObservers);
715
- return result.snapshot;
716
- });
717
- return revivedSnapshot;
718
- }
719
- // otherwise just return what buildCachedSnapshot gave us
720
- return snapshot;
721
- };
722
- const wrappedApplyCachePolicy = () => {
723
- return environment.applyCachePolicy(luvio, adapterRequestContext, buildSnapshotContext, wrappedCacheLookup, buildNetworkSnapshot);
724
- };
725
- // GET adapters call applyCachePolicy before any other luvio
726
- // function so this is our chance to ensure we're initialized
727
- return initializationPromise !== undefined
728
- ? initializationPromise.then(wrappedApplyCachePolicy)
729
- : wrappedApplyCachePolicy();
730
- };
731
- const getIngestStagingStoreRecords = function () {
732
- validateNotDisposed();
733
- if (ingestStagingStore !== null) {
734
- return ingestStagingStore.fallbackStringKeyInMemoryStore.records;
735
- }
736
- return {};
737
- };
738
- const getIngestStagingStoreMetadata = function () {
739
- validateNotDisposed();
740
- if (ingestStagingStore !== null) {
741
- return ingestStagingStore.fallbackStringKeyInMemoryStore.metadata;
742
- }
743
- return {};
744
- };
745
- const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
746
- validateNotDisposed();
747
- const cacheKeyMap = getResponseCacheKeysFunc();
748
- const cacheKeyMapKeys = cacheKeyMap.keysAsArray();
749
- const keysToRevive = new engine.StoreKeySet();
750
- for (const cacheKeyMapKey of cacheKeyMapKeys) {
751
- const cacheKey = cacheKeyMap.get(cacheKeyMapKey);
752
- if (cacheKey.mergeable === true) {
753
- keysToRevive.add(cacheKeyMapKey);
754
- }
755
- }
756
- let snapshotFromMemoryIngest = undefined;
757
- // To-do: Once these are structured keys, will need to support them throughout durable logic W-12356727
758
- const keysToReviveAsArray = Array.from(keysToRevive.keysAsStrings());
759
- if (keysToReviveAsArray.length > 0) {
760
- // if we need to do an L2 read then L2 write then we need to synchronize
761
- // our read/merge/ingest/write Promise based on the keys so we don't
762
- // stomp over any data
763
- const readWritePromise = (async () => {
764
- const pendingPromises = [];
765
- for (const key of keysToReviveAsArray) {
766
- const pendingPromise = mergeKeysPromiseMap.get(key);
767
- if (pendingPromise !== undefined) {
768
- // IMPORTANT: while on the synchronous code path we get a
769
- // handle to pendingPromise and push it onto the array.
770
- // This is important because later in this synchronous code
771
- // path we will upsert readWritePromise into the
772
- // mergeKeysPromiseMap (essentially overwriting pendingPromise
773
- // in the map).
774
- pendingPromises.push(pendingPromise);
775
- }
776
- }
777
- await Promise.all(pendingPromises);
778
- const entries = await durableStore.getEntries(keysToReviveAsArray, DefaultDurableSegment);
779
- ingestStagingStore = buildIngestStagingStore(environment);
780
- publishDurableStoreEntries(entries, (key, record) => {
781
- if (typeof key === 'string') {
782
- ingestStagingStore.fallbackStringKeyInMemoryStore.records[key] =
783
- record;
784
- }
785
- else {
786
- ingestStagingStore.recordsMap.set(key, record);
787
- }
788
- },
789
- // we don't need to prime metadata
790
- () => { });
791
- snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
792
- })();
793
- for (const key of keysToReviveAsArray) {
794
- // we are overwriting the previous promise at this key, but that
795
- // is ok because we got a handle to it earlier (see the IMPORTANT
796
- // comment about 35 lines up)
797
- mergeKeysPromiseMap.set(key, readWritePromise);
798
- }
799
- try {
800
- await readWritePromise;
801
- }
802
- finally {
803
- for (const key of keysToReviveAsArray) {
804
- const pendingPromise = mergeKeysPromiseMap.get(key);
805
- // cleanup the entry from the map if this is the last promise
806
- // for that key
807
- if (pendingPromise === readWritePromise) {
808
- mergeKeysPromiseMap.delete(key);
809
- }
810
- }
811
- }
812
- }
813
- else {
814
- // we aren't doing any merging so we don't have to synchronize, the
815
- // underlying DurableStore implementation takes care of R/W sync
816
- // so all we have to do is ingest then write to L2
817
- ingestStagingStore = buildIngestStagingStore(environment);
818
- snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
819
- }
820
- if (snapshotFromMemoryIngest === undefined) {
821
- return undefined;
822
- }
823
- if (snapshotFromMemoryIngest.state !== 'Unfulfilled') {
824
- return snapshotFromMemoryIngest;
825
- }
826
- // if snapshot from staging store lookup is unfulfilled then do an L2 lookup
827
- const { select, refresh } = snapshotFromMemoryIngest;
828
- const result = await reviveSnapshot(environment, durableStore, snapshotFromMemoryIngest, durableStoreErrorHandler, () => environment.storeLookup(select, environment.createSnapshot, refresh));
829
- return result.snapshot;
830
- };
831
- const handleErrorResponse = async function (ingestAndBroadcastFunc) {
832
- validateNotDisposed();
833
- ingestStagingStore = buildIngestStagingStore(environment);
834
- return ingestAndBroadcastFunc();
835
- };
836
- const getNotifyChangeStoreEntries = function (keys) {
837
- validateNotDisposed();
838
- return durableStore
839
- .getEntries(keys.map(engine.serializeStructuredKey), DefaultDurableSegment)
840
- .then((durableRecords) => {
841
- const entries = [];
842
- publishDurableStoreEntries(durableRecords, (key, record) => {
843
- entries.push({
844
- key,
845
- record: record,
846
- });
847
- }, () => { });
848
- return entries;
849
- });
850
- };
851
- environment.defaultCachePolicy = {
852
- type: 'stale-while-revalidate',
853
- implementation: engine.buildStaleWhileRevalidateImplementation(Number.MAX_SAFE_INTEGER),
854
- };
855
- return create(environment, {
856
- publishStoreMetadata: { value: publishStoreMetadata },
857
- storeIngest: { value: storeIngest },
858
- storeIngestError: { value: storeIngestError },
859
- storeBroadcast: { value: storeBroadcast },
860
- storeLookup: { value: storeLookup },
861
- storeEvict: { value: storeEvict },
862
- wrapNormalizedGraphNode: { value: wrapNormalizedGraphNode },
863
- getNode: { value: getNode },
864
- rebuildSnapshot: { value: rebuildSnapshot },
865
- withContext: { value: withContext },
866
- storeSetTTLOverride: { value: storeSetTTLOverride },
867
- storeSetDefaultTTLOverride: { value: storeSetDefaultTTLOverride },
868
- storePublish: { value: storePublish },
869
- storeRedirect: { value: storeRedirect },
870
- dispose: { value: dispose },
871
- publishChangesToDurableStore: { value: publishChangesToDurableStore },
872
- getDurableTTLOverrides: { value: getDurableTTLOverrides },
873
- dispatchResourceRequest: { value: dispatchResourceRequest },
874
- applyCachePolicy: { value: applyCachePolicy },
875
- getIngestStagingStoreRecords: { value: getIngestStagingStoreRecords },
876
- getIngestStagingStoreMetadata: { value: getIngestStagingStoreMetadata },
877
- handleSuccessResponse: { value: handleSuccessResponse },
878
- handleErrorResponse: { value: handleErrorResponse },
879
- getNotifyChangeStoreEntries: { value: getNotifyChangeStoreEntries },
880
- });
385
+ const AdapterContextSegment = 'ADAPTER-CONTEXT';
386
+ const ADAPTER_CONTEXT_ID_SUFFIX = '__NAMED_CONTEXT';
387
+ async function reviveOrCreateContext(adapterId, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded) {
388
+ // initialize empty context store
389
+ contextStores[adapterId] = create(null);
390
+ const context = {
391
+ set(key, value) {
392
+ contextStores[adapterId][key] = value;
393
+ durableStore.setEntries({
394
+ [adapterId]: { data: contextStores[adapterId] },
395
+ }, AdapterContextSegment);
396
+ pendingContextStoreKeys.add(adapterId);
397
+ },
398
+ get(key) {
399
+ return contextStores[adapterId][key];
400
+ },
401
+ };
402
+ const contextReturn = () => {
403
+ if (onContextLoaded !== undefined) {
404
+ return onContextLoaded(context).then(() => {
405
+ return context;
406
+ });
407
+ }
408
+ return context;
409
+ };
410
+ try {
411
+ const entries = await durableStore.getEntries([adapterId], AdapterContextSegment);
412
+ if (entries !== undefined && entries[adapterId] !== undefined) {
413
+ // if durable store has a saved context then load it in the store
414
+ contextStores[adapterId] = entries[adapterId].data;
415
+ }
416
+ }
417
+ catch (error) {
418
+ durableStoreErrorHandler(error);
419
+ }
420
+ return contextReturn();
421
+ }
422
+ function isUnfulfilledSnapshot(cachedSnapshotResult) {
423
+ if (cachedSnapshotResult === undefined) {
424
+ return false;
425
+ }
426
+ if ('then' in cachedSnapshotResult) {
427
+ return false;
428
+ }
429
+ return cachedSnapshotResult.state === 'Unfulfilled';
430
+ }
431
+ /**
432
+ * Configures the environment to persist data into a durable store and attempt to resolve
433
+ * data from the persistent store before hitting the network.
434
+ *
435
+ * @param environment The base environment
436
+ * @param durableStore A DurableStore implementation
437
+ * @param instrumentation An instrumentation function implementation
438
+ */
439
+ function makeDurable(environment, { durableStore, instrumentation }) {
440
+ let ingestStagingStore = null;
441
+ const durableTTLStore = new DurableTTLStore(durableStore);
442
+ const mergeKeysPromiseMap = new engine.StoreKeyMap();
443
+ // When a context store is mutated we write it to L2, which causes DS on change
444
+ // event. If this instance of makeDurable caused that L2 write we can ignore that
445
+ // on change event. This Set helps us do that.
446
+ const pendingContextStoreKeys = new Set();
447
+ const contextStores = create(null);
448
+ let initializationPromise = new Promise((resolve) => {
449
+ const finish = () => {
450
+ resolve();
451
+ initializationPromise = undefined;
452
+ };
453
+ reviveTTLOverrides(durableTTLStore, environment).then(finish);
454
+ });
455
+ //instrumentation for durable store errors
456
+ const durableStoreErrorHandler = handleDurableStoreRejection(instrumentation);
457
+ let disposed = false;
458
+ const validateNotDisposed = () => {
459
+ if (disposed === true) {
460
+ throw new Error('This makeDurable instance has been disposed');
461
+ }
462
+ };
463
+ const unsubscribe = durableStore.registerOnChangedListener(async (changes) => {
464
+ const defaultSegmentKeys = [];
465
+ const adapterContextSegmentKeys = [];
466
+ for (let i = 0, len = changes.length; i < len; i++) {
467
+ const change = changes[i];
468
+ // we only care about changes to the data which is stored in the default
469
+ // segment or the adapter context
470
+ if (change.segment === DefaultDurableSegment) {
471
+ defaultSegmentKeys.push(...change.ids);
472
+ }
473
+ else if (change.segment === AdapterContextSegment) {
474
+ adapterContextSegmentKeys.push(...change.ids);
475
+ }
476
+ }
477
+ // process adapter context changes
478
+ const adapterContextKeysFromDifferentInstance = [];
479
+ for (const key of adapterContextSegmentKeys) {
480
+ if (pendingContextStoreKeys.has(key)) {
481
+ // if this instance caused the L2 write then remove from the
482
+ // "pending" Set and move on
483
+ pendingContextStoreKeys.delete(key);
484
+ }
485
+ else {
486
+ // else it came from another luvio instance and we need to
487
+ // read from L2
488
+ adapterContextKeysFromDifferentInstance.push(key);
489
+ }
490
+ }
491
+ if (adapterContextKeysFromDifferentInstance.length > 0) {
492
+ try {
493
+ const entries = await durableStore.getEntries(adapterContextKeysFromDifferentInstance, AdapterContextSegment);
494
+ if (entries !== undefined) {
495
+ const entryKeys = keys(entries);
496
+ for (let i = 0, len = entryKeys.length; i < len; i++) {
497
+ const entryKey = entryKeys[i];
498
+ const entry = entries[entryKey];
499
+ contextStores[entryKey] = entry.data;
500
+ }
501
+ }
502
+ }
503
+ catch (error) {
504
+ durableStoreErrorHandler(error);
505
+ }
506
+ }
507
+ // process default segment changes
508
+ const defaultSegmentKeysLength = defaultSegmentKeys.length;
509
+ if (defaultSegmentKeysLength > 0) {
510
+ for (let i = 0; i < defaultSegmentKeysLength; i++) {
511
+ const key = defaultSegmentKeys[i];
512
+ const canonical = environment.storeGetCanonicalKey(key);
513
+ if (canonical !== key) {
514
+ continue;
515
+ }
516
+ // TODO: W-8909393 If expiration is the only thing that changed we should not evict the data... so
517
+ // if we stored expiration and data at different keys (or same keys in different segments)
518
+ // then we could know if only the expiration has changed and we wouldn't need to evict
519
+ // and go through an entire broadcast/revive cycle for unchanged data
520
+ // call base environment storeEvict so this evict is not tracked for durable deletion
521
+ environment.storeEvict(key);
522
+ }
523
+ await environment.storeBroadcast(rebuildSnapshot, environment.snapshotAvailable);
524
+ }
525
+ });
526
+ const dispose = function () {
527
+ validateNotDisposed();
528
+ disposed = true;
529
+ return unsubscribe();
530
+ };
531
+ const storePublish = function (key, data) {
532
+ validateNotDisposed();
533
+ if (ingestStagingStore === null) {
534
+ ingestStagingStore = buildIngestStagingStore(environment);
535
+ }
536
+ ingestStagingStore.publish(key, data);
537
+ // remove record from main luvio L1 cache while we are on the synchronous path
538
+ // because we do not want some other code attempting to use the
539
+ // in-memory values before the durable store onChanged handler
540
+ // calls back and revives the values to in-memory
541
+ environment.storeEvict(key);
542
+ };
543
+ const publishStoreMetadata = function (recordId, storeMetadata) {
544
+ validateNotDisposed();
545
+ if (ingestStagingStore === null) {
546
+ ingestStagingStore = buildIngestStagingStore(environment);
547
+ }
548
+ ingestStagingStore.publishMetadata(recordId, storeMetadata);
549
+ };
550
+ const storeIngest = function (key, ingest, response, luvio) {
551
+ validateNotDisposed();
552
+ // we don't ingest to the luvio L1 store from network directly, we ingest to
553
+ // L2 and let DurableStore on change event revive keys into luvio L1 store
554
+ if (ingestStagingStore === null) {
555
+ ingestStagingStore = buildIngestStagingStore(environment);
556
+ }
557
+ environment.storeIngest(key, ingest, response, luvio, ingestStagingStore);
558
+ };
559
+ const storeIngestError = function (key, errorSnapshot, storeMetadataParams, _storeOverride) {
560
+ validateNotDisposed();
561
+ if (ingestStagingStore === null) {
562
+ ingestStagingStore = buildIngestStagingStore(environment);
563
+ }
564
+ environment.storeIngestError(key, errorSnapshot, storeMetadataParams, ingestStagingStore);
565
+ };
566
+ const storeBroadcast = function (_rebuildSnapshot, _snapshotDataAvailable) {
567
+ validateNotDisposed();
568
+ // publishing to L2 is essentially "broadcasting" because the onChanged
569
+ // handler will fire which will revive records to the main L1 store and
570
+ // call the base storeBroadcast
571
+ return publishChangesToDurableStore();
572
+ };
573
+ const publishChangesToDurableStore = function () {
574
+ validateNotDisposed();
575
+ if (ingestStagingStore === null) {
576
+ return Promise.resolve();
577
+ }
578
+ const promise = flushInMemoryStoreValuesToDurableStore(ingestStagingStore, durableStore, durableStoreErrorHandler);
579
+ ingestStagingStore = null;
580
+ return promise;
581
+ };
582
+ const storeLookup = function (sel, createSnapshot, refresh, ttlStrategy) {
583
+ validateNotDisposed();
584
+ // if this lookup is right after an ingest there will be a staging store
585
+ if (ingestStagingStore !== null) {
586
+ const reader = new engine.Reader(ingestStagingStore, sel.variables, refresh, undefined, ttlStrategy);
587
+ return reader.read(sel);
588
+ }
589
+ // otherwise this is from buildCachedSnapshot and we should use the luvio
590
+ // L1 store
591
+ return environment.storeLookup(sel, createSnapshot, refresh, ttlStrategy);
592
+ };
593
+ const storeEvict = function (key) {
594
+ validateNotDisposed();
595
+ if (ingestStagingStore === null) {
596
+ ingestStagingStore = buildIngestStagingStore(environment);
597
+ }
598
+ ingestStagingStore.evict(key);
599
+ };
600
+ const getNode = function (key) {
601
+ validateNotDisposed();
602
+ if (ingestStagingStore === null) {
603
+ ingestStagingStore = buildIngestStagingStore(environment);
604
+ }
605
+ return environment.getNode(key, ingestStagingStore);
606
+ };
607
+ const wrapNormalizedGraphNode = function (normalized) {
608
+ validateNotDisposed();
609
+ if (ingestStagingStore === null) {
610
+ ingestStagingStore = buildIngestStagingStore(environment);
611
+ }
612
+ return environment.wrapNormalizedGraphNode(normalized, ingestStagingStore);
613
+ };
614
+ const rebuildSnapshot = function (snapshot, onRebuild) {
615
+ validateNotDisposed();
616
+ // try rebuilding from memory
617
+ environment.rebuildSnapshot(snapshot, (rebuilt) => {
618
+ // only try reviving from durable store if snapshot is unfulfilled
619
+ if (rebuilt.state !== 'Unfulfilled') {
620
+ onRebuild(rebuilt);
621
+ return;
622
+ }
623
+ // Do an L2 revive and emit to subscriber using the callback.
624
+ reviveSnapshot(environment, durableStore, rebuilt, durableStoreErrorHandler, () => {
625
+ // reviveSnapshot will revive into L1, and since "records" is a reference
626
+ // (and not a copy) to the L1 records we can use it for rebuild
627
+ let rebuiltSnap;
628
+ environment.rebuildSnapshot(snapshot, (rebuilt) => {
629
+ rebuiltSnap = rebuilt;
630
+ });
631
+ return rebuiltSnap;
632
+ }).then((result) => {
633
+ onRebuild(result.snapshot);
634
+ });
635
+ });
636
+ };
637
+ const withContext = function (adapter, options) {
638
+ validateNotDisposed();
639
+ const { contextId, contextVersion, onContextLoaded } = options;
640
+ let context = undefined;
641
+ let contextKey = `${contextId}`;
642
+ // if a context version is supplied, key with the version encoded
643
+ if (contextVersion !== undefined) {
644
+ contextKey += `::${contextVersion}`;
645
+ }
646
+ contextKey += ADAPTER_CONTEXT_ID_SUFFIX;
647
+ const contextAsPromise = reviveOrCreateContext(contextKey, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded);
648
+ return (config, requestContext) => {
649
+ if (context === undefined) {
650
+ return contextAsPromise.then((revivedContext) => {
651
+ context = revivedContext;
652
+ return adapter(config, context, requestContext); // TODO - remove as any cast after https://github.com/salesforce-experience-platform-emu/luvio/pull/230
653
+ });
654
+ }
655
+ return adapter(config, context, requestContext);
656
+ };
657
+ };
658
+ const storeRedirect = function (existingKey, canonicalKey) {
659
+ validateNotDisposed();
660
+ // call redirect on staging store so "old" keys are removed from L2 on
661
+ // the next publishChangesToDurableStore. NOTE: we don't need to call
662
+ // redirect on the base environment store because staging store and base
663
+ // L1 store share the same redirect and reverseRedirectKeys
664
+ if (ingestStagingStore === null) {
665
+ ingestStagingStore = buildIngestStagingStore(environment);
666
+ }
667
+ ingestStagingStore.redirect(existingKey, canonicalKey);
668
+ };
669
+ const storeSetTTLOverride = function (namespace, representationName, ttl) {
670
+ validateNotDisposed();
671
+ return Promise.all([
672
+ environment.storeSetTTLOverride(namespace, representationName, ttl),
673
+ durableTTLStore.setDurableTTLOverride(namespace, representationName, ttl),
674
+ ]).then();
675
+ };
676
+ const storeSetDefaultTTLOverride = function (ttl) {
677
+ validateNotDisposed();
678
+ return Promise.all([
679
+ environment.storeSetDefaultTTLOverride(ttl),
680
+ durableTTLStore.setDefaultDurableTTLOverrides(ttl),
681
+ ]).then();
682
+ };
683
+ const getDurableTTLOverrides = function () {
684
+ validateNotDisposed();
685
+ return durableTTLStore.getDurableTTLOverrides();
686
+ };
687
+ const dispatchResourceRequest = async function (request, context, eventObservers) {
688
+ validateNotDisposed();
689
+ // non-GET adapters call dispatchResourceRequest before any other luvio
690
+ // function so this is our chance to ensure we're initialized
691
+ if (initializationPromise !== undefined) {
692
+ await initializationPromise;
693
+ }
694
+ return environment.dispatchResourceRequest(request, context, eventObservers);
695
+ };
696
+ // NOTE: we can't use "async" keyword on this function because that would
697
+ // force it to always be an async response. The signature is a union
698
+ // of sync/async so no "awaiting" in this function, just promise-chaining
699
+ const applyCachePolicy = function (luvio, adapterRequestContext, buildSnapshotContext, buildCachedSnapshot, buildNetworkSnapshot) {
700
+ validateNotDisposed();
701
+ const wrappedCacheLookup = (injectedBuildSnapshotContext, injectedStoreLookup) => {
702
+ const snapshot = buildCachedSnapshot(injectedBuildSnapshotContext, injectedStoreLookup, luvio);
703
+ // if the adapter attempted to do an L1 lookup and it was unfulfilled
704
+ // then we can attempt an L2 lookup
705
+ if (isUnfulfilledSnapshot(snapshot)) {
706
+ const start = Date.now();
707
+ emitDurableEnvironmentAdapterEvent({ type: 'l2-revive-start' }, adapterRequestContext.eventObservers);
708
+ const revivedSnapshot = reviveSnapshot(environment, durableStore, snapshot, durableStoreErrorHandler, () => injectedStoreLookup(snapshot.select, snapshot.refresh)).then((result) => {
709
+ emitDurableEnvironmentAdapterEvent({
710
+ type: 'l2-revive-end',
711
+ snapshot: result.snapshot,
712
+ duration: Date.now() - start,
713
+ l2Trips: result.metrics.l2Trips,
714
+ }, adapterRequestContext.eventObservers);
715
+ return result.snapshot;
716
+ });
717
+ return revivedSnapshot;
718
+ }
719
+ // otherwise just return what buildCachedSnapshot gave us
720
+ return snapshot;
721
+ };
722
+ const wrappedApplyCachePolicy = () => {
723
+ return environment.applyCachePolicy(luvio, adapterRequestContext, buildSnapshotContext, wrappedCacheLookup, buildNetworkSnapshot);
724
+ };
725
+ // GET adapters call applyCachePolicy before any other luvio
726
+ // function so this is our chance to ensure we're initialized
727
+ return initializationPromise !== undefined
728
+ ? initializationPromise.then(wrappedApplyCachePolicy)
729
+ : wrappedApplyCachePolicy();
730
+ };
731
+ const getIngestStagingStoreRecords = function () {
732
+ validateNotDisposed();
733
+ if (ingestStagingStore !== null) {
734
+ return ingestStagingStore.fallbackStringKeyInMemoryStore.records;
735
+ }
736
+ return {};
737
+ };
738
+ const getIngestStagingStoreMetadata = function () {
739
+ validateNotDisposed();
740
+ if (ingestStagingStore !== null) {
741
+ return ingestStagingStore.fallbackStringKeyInMemoryStore.metadata;
742
+ }
743
+ return {};
744
+ };
745
+ const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
746
+ validateNotDisposed();
747
+ const cacheKeyMap = getResponseCacheKeysFunc();
748
+ const cacheKeyMapKeys = cacheKeyMap.keysAsArray();
749
+ const keysToRevive = new engine.StoreKeySet();
750
+ for (const cacheKeyMapKey of cacheKeyMapKeys) {
751
+ const cacheKey = cacheKeyMap.get(cacheKeyMapKey);
752
+ if (cacheKey.mergeable === true) {
753
+ keysToRevive.add(cacheKeyMapKey);
754
+ }
755
+ }
756
+ let snapshotFromMemoryIngest = undefined;
757
+ // To-do: Once these are structured keys, will need to support them throughout durable logic W-12356727
758
+ const keysToReviveAsArray = Array.from(keysToRevive.keysAsStrings());
759
+ if (keysToReviveAsArray.length > 0) {
760
+ // if we need to do an L2 read then L2 write then we need to synchronize
761
+ // our read/merge/ingest/write Promise based on the keys so we don't
762
+ // stomp over any data
763
+ const readWritePromise = (async () => {
764
+ const pendingPromises = [];
765
+ for (const key of keysToReviveAsArray) {
766
+ const pendingPromise = mergeKeysPromiseMap.get(key);
767
+ if (pendingPromise !== undefined) {
768
+ // IMPORTANT: while on the synchronous code path we get a
769
+ // handle to pendingPromise and push it onto the array.
770
+ // This is important because later in this synchronous code
771
+ // path we will upsert readWritePromise into the
772
+ // mergeKeysPromiseMap (essentially overwriting pendingPromise
773
+ // in the map).
774
+ pendingPromises.push(pendingPromise);
775
+ }
776
+ }
777
+ await Promise.all(pendingPromises);
778
+ const entries = await durableStore.getEntries(keysToReviveAsArray, DefaultDurableSegment);
779
+ ingestStagingStore = buildIngestStagingStore(environment);
780
+ publishDurableStoreEntries(entries, (key, record) => {
781
+ if (typeof key === 'string') {
782
+ ingestStagingStore.fallbackStringKeyInMemoryStore.records[key] =
783
+ record;
784
+ }
785
+ else {
786
+ ingestStagingStore.recordsMap.set(key, record);
787
+ }
788
+ }, (key, metadata) => {
789
+ if (typeof key === 'string') {
790
+ ingestStagingStore.fallbackStringKeyInMemoryStore.metadata[key] =
791
+ metadata;
792
+ }
793
+ else {
794
+ ingestStagingStore.metadataMap.set(key, metadata);
795
+ }
796
+ });
797
+ snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
798
+ })();
799
+ for (const key of keysToReviveAsArray) {
800
+ // we are overwriting the previous promise at this key, but that
801
+ // is ok because we got a handle to it earlier (see the IMPORTANT
802
+ // comment about 35 lines up)
803
+ mergeKeysPromiseMap.set(key, readWritePromise);
804
+ }
805
+ try {
806
+ await readWritePromise;
807
+ }
808
+ finally {
809
+ for (const key of keysToReviveAsArray) {
810
+ const pendingPromise = mergeKeysPromiseMap.get(key);
811
+ // cleanup the entry from the map if this is the last promise
812
+ // for that key
813
+ if (pendingPromise === readWritePromise) {
814
+ mergeKeysPromiseMap.delete(key);
815
+ }
816
+ }
817
+ }
818
+ }
819
+ else {
820
+ // we aren't doing any merging so we don't have to synchronize, the
821
+ // underlying DurableStore implementation takes care of R/W sync
822
+ // so all we have to do is ingest then write to L2
823
+ ingestStagingStore = buildIngestStagingStore(environment);
824
+ snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
825
+ }
826
+ if (snapshotFromMemoryIngest === undefined) {
827
+ return undefined;
828
+ }
829
+ if (snapshotFromMemoryIngest.state !== 'Unfulfilled') {
830
+ return snapshotFromMemoryIngest;
831
+ }
832
+ // if snapshot from staging store lookup is unfulfilled then do an L2 lookup
833
+ const { select, refresh } = snapshotFromMemoryIngest;
834
+ const result = await reviveSnapshot(environment, durableStore, snapshotFromMemoryIngest, durableStoreErrorHandler, () => environment.storeLookup(select, environment.createSnapshot, refresh));
835
+ return result.snapshot;
836
+ };
837
+ const handleErrorResponse = async function (ingestAndBroadcastFunc) {
838
+ validateNotDisposed();
839
+ ingestStagingStore = buildIngestStagingStore(environment);
840
+ return ingestAndBroadcastFunc();
841
+ };
842
+ const getNotifyChangeStoreEntries = function (keys) {
843
+ validateNotDisposed();
844
+ return durableStore
845
+ .getEntries(keys.map(engine.serializeStructuredKey), DefaultDurableSegment)
846
+ .then((durableRecords) => {
847
+ const entries = [];
848
+ publishDurableStoreEntries(durableRecords, (key, record) => {
849
+ entries.push({
850
+ key,
851
+ record: record,
852
+ });
853
+ }, () => { });
854
+ return entries;
855
+ });
856
+ };
857
+ environment.defaultCachePolicy = {
858
+ type: 'stale-while-revalidate',
859
+ implementation: engine.buildStaleWhileRevalidateImplementation(Number.MAX_SAFE_INTEGER),
860
+ };
861
+ return create(environment, {
862
+ publishStoreMetadata: { value: publishStoreMetadata },
863
+ storeIngest: { value: storeIngest },
864
+ storeIngestError: { value: storeIngestError },
865
+ storeBroadcast: { value: storeBroadcast },
866
+ storeLookup: { value: storeLookup },
867
+ storeEvict: { value: storeEvict },
868
+ wrapNormalizedGraphNode: { value: wrapNormalizedGraphNode },
869
+ getNode: { value: getNode },
870
+ rebuildSnapshot: { value: rebuildSnapshot },
871
+ withContext: { value: withContext },
872
+ storeSetTTLOverride: { value: storeSetTTLOverride },
873
+ storeSetDefaultTTLOverride: { value: storeSetDefaultTTLOverride },
874
+ storePublish: { value: storePublish },
875
+ storeRedirect: { value: storeRedirect },
876
+ dispose: { value: dispose },
877
+ publishChangesToDurableStore: { value: publishChangesToDurableStore },
878
+ getDurableTTLOverrides: { value: getDurableTTLOverrides },
879
+ dispatchResourceRequest: { value: dispatchResourceRequest },
880
+ applyCachePolicy: { value: applyCachePolicy },
881
+ getIngestStagingStoreRecords: { value: getIngestStagingStoreRecords },
882
+ getIngestStagingStoreMetadata: { value: getIngestStagingStoreMetadata },
883
+ handleSuccessResponse: { value: handleSuccessResponse },
884
+ handleErrorResponse: { value: handleErrorResponse },
885
+ getNotifyChangeStoreEntries: { value: getNotifyChangeStoreEntries },
886
+ });
881
887
  }
882
888
 
883
889
  exports.DURABLE_METADATA_VERSION = DURABLE_METADATA_VERSION;