@luvio/environments 0.142.2 → 0.142.4

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