@salesforce/lds-runtime-mobile 1.128.0 → 1.129.0

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 (3) hide show
  1. package/dist/main.js +877 -875
  2. package/package.json +1 -1
  3. package/sfdc/main.js +877 -875
package/dist/main.js CHANGED
@@ -497,883 +497,883 @@ function platformNetworkAdapter(baseNetworkAdapter) {
497
497
  };
498
498
  }
499
499
 
500
- // the last version the metadata shape was altered
501
- const DURABLE_METADATA_VERSION = '0.111.0';
502
- function isDeprecatedDurableStoreEntry(durableRecord) {
503
- if (durableRecord.expiration !== undefined) {
504
- return true;
505
- }
506
- const metadata = durableRecord.metadata;
507
- if (metadata !== undefined) {
508
- const { metadataVersion } = metadata;
509
- // eventually we will want to assert that metadataVersion is defined
510
- if (metadataVersion !== undefined && metadataVersion !== DURABLE_METADATA_VERSION) {
511
- return true;
512
- }
513
- }
514
- // Add more deprecated shape checks here
515
- return false;
516
- }
500
+ // the last version the metadata shape was altered
501
+ const DURABLE_METADATA_VERSION = '0.111.0';
502
+ function isDeprecatedDurableStoreEntry(durableRecord) {
503
+ if (durableRecord.expiration !== undefined) {
504
+ return true;
505
+ }
506
+ const metadata = durableRecord.metadata;
507
+ if (metadata !== undefined) {
508
+ const { metadataVersion } = metadata;
509
+ // eventually we will want to assert that metadataVersion is defined
510
+ if (metadataVersion !== undefined && metadataVersion !== DURABLE_METADATA_VERSION) {
511
+ return true;
512
+ }
513
+ }
514
+ // Add more deprecated shape checks here
515
+ return false;
516
+ }
517
517
  const DefaultDurableSegment = 'DEFAULT';
518
518
 
519
- const { keys: keys$5, create: create$5, assign: assign$4, freeze: freeze$1 } = Object;
519
+ const { keys: keys$5, create: create$5, assign: assign$4, freeze: freeze$1 } = Object;
520
520
  const { isArray: isArray$5 } = Array;
521
521
 
522
- //Durable store error instrumentation key
523
- const DURABLE_STORE_ERROR = 'durable-store-error';
524
- /**
525
- * Returns a function that processes errors from durable store promise rejections.
526
- * If running in a non-production environment, the error is rethrown.
527
- * When running in production the error is sent to instrumentation.
528
- * @param instrument Instrumentation function implementation
529
- */
530
- function handleDurableStoreRejection(instrument) {
531
- return (error) => {
532
- if (process.env.NODE_ENV !== 'production') {
533
- throw error;
534
- }
535
- if (instrument !== undefined) {
536
- instrument(() => {
537
- return {
538
- [DURABLE_STORE_ERROR]: true,
539
- error: error,
540
- };
541
- });
542
- }
543
- };
544
- }
545
-
546
- function deepFreeze(value) {
547
- // No need to freeze primitives
548
- if (typeof value !== 'object' || value === null) {
549
- return;
550
- }
551
- if (isArray$5(value)) {
552
- for (let i = 0, len = value.length; i < len; i += 1) {
553
- deepFreeze(value[i]);
554
- }
555
- }
556
- else {
557
- const keys$1 = keys$5(value);
558
- for (let i = 0, len = keys$1.length; i < len; i += 1) {
559
- deepFreeze(value[keys$1[i]]);
560
- }
561
- }
562
- freeze$1(value);
563
- }
564
-
565
- function isStoreEntryError(storeRecord) {
566
- return storeRecord.__type === 'error';
567
- }
568
-
569
- /**
570
- * Takes a set of entries from DurableStore and publishes them via the passed in funcs.
571
- * This respects expiration and checks for valid DurableStore data shapes. This should
572
- * be used over manually parsing DurableStoreEntries
573
- *
574
- * @param durableRecords The DurableStoreEntries to parse
575
- * @param publish A function to call with the data of each DurableStoreEntry
576
- * @param publishMetadata A function to call with the metadata of each DurableStoreEntry
577
- * @param pendingWriter the PendingWriter (this is going away soon)
578
- * @returns
579
- */
580
- function publishDurableStoreEntries(durableRecords, publish, publishMetadata) {
581
- const revivedKeys = new StoreKeySet();
582
- let hadUnexpectedShape = false;
583
- if (durableRecords === undefined) {
584
- return { revivedKeys, hadUnexpectedShape };
585
- }
586
- const durableKeys = keys$5(durableRecords);
587
- if (durableKeys.length === 0) {
588
- // no records to revive
589
- return { revivedKeys, hadUnexpectedShape };
590
- }
591
- for (let i = 0, len = durableKeys.length; i < len; i += 1) {
592
- const key = durableKeys[i];
593
- const durableRecord = durableRecords[key];
594
- if (isDeprecatedDurableStoreEntry(durableRecord)) {
595
- // had the old shape, skip reviving this entry.
596
- hadUnexpectedShape = true;
597
- continue;
598
- }
599
- const { metadata, data } = durableRecord;
600
- if (data === undefined) {
601
- // if unexpected data skip reviving
602
- hadUnexpectedShape = true;
603
- continue;
604
- }
605
- if (metadata !== undefined) {
606
- const { expirationTimestamp } = metadata;
607
- if (expirationTimestamp === undefined) {
608
- // if unexpected expiration data skip reviving
609
- hadUnexpectedShape = true;
610
- continue;
611
- }
612
- publishMetadata(key, metadata);
613
- }
614
- if (isStoreEntryError(data)) {
615
- // freeze errors on way into L1
616
- deepFreeze(data.error);
617
- }
618
- publish(key, data);
619
- revivedKeys.add(key);
620
- }
621
- return { revivedKeys, hadUnexpectedShape };
622
- }
623
- /**
624
- * This method returns a Promise to a snapshot that is revived from L2 cache. If
625
- * L2 does not have the entries necessary to fulfill the snapshot then this method
626
- * will refresh the snapshot from network, and then run the results from network
627
- * through L2 ingestion, returning the subsequent revived snapshot.
628
- */
629
- function reviveSnapshot(baseEnvironment, durableStore,
630
- // TODO [W-10165787]: We should only allow Unfulfilled snapshot be passed in
631
- unavailableSnapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics = { l2Trips: [] }) {
632
- const { recordId, select, seenRecords, state } = unavailableSnapshot;
633
- // L2 can only revive Unfulfilled snapshots that have a selector since they have the
634
- // info needed to revive (like missingLinks) and rebuild. Otherwise return L1 snapshot.
635
- if (state !== 'Unfulfilled' || select === undefined) {
636
- return Promise.resolve({
637
- snapshot: unavailableSnapshot,
638
- metrics: reviveMetrics,
639
- });
640
- }
641
- // in case L1 store changes/deallocs a record while we are doing the async read
642
- // we attempt to read all keys from L2 - so combine recordId with any seenRecords
643
- const keysToReviveSet = new StoreKeySet().add(recordId);
644
- keysToReviveSet.merge(seenRecords);
645
- const keysToRevive = keysToReviveSet.keysAsArray();
646
- const canonicalKeys = keysToRevive.map((x) => serializeStructuredKey(baseEnvironment.storeGetCanonicalKey(x)));
647
- const start = Date.now();
648
- const { l2Trips } = reviveMetrics;
649
- return durableStore.getEntries(canonicalKeys, DefaultDurableSegment).then((durableRecords) => {
650
- l2Trips.push({
651
- duration: Date.now() - start,
652
- keysRequestedCount: canonicalKeys.length,
653
- });
654
- const { revivedKeys, hadUnexpectedShape } = publishDurableStoreEntries(durableRecords,
655
- // TODO [W-10072584]: instead of implicitly using L1 we should take in
656
- // publish and publishMetadata funcs, so callers can decide where to
657
- // revive to (like they pass in how to do the buildL1Snapshot)
658
- baseEnvironment.storePublish.bind(baseEnvironment), baseEnvironment.publishStoreMetadata.bind(baseEnvironment));
659
- // if the data coming back from DS had an unexpected shape then just
660
- // return the L1 snapshot
661
- if (hadUnexpectedShape === true) {
662
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
663
- }
664
- if (revivedKeys.size() === 0) {
665
- // durable store doesn't have what we asked for so return L1 snapshot
666
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
667
- }
668
- // try building the snapshot from L1 now that we have revived the missingLinks
669
- const snapshot = buildL1Snapshot();
670
- // if snapshot is pending then some other in-flight refresh will broadcast
671
- // later
672
- if (snapshot.state === 'Pending') {
673
- return { snapshot, metrics: reviveMetrics };
674
- }
675
- if (snapshot.state === 'Unfulfilled') {
676
- // have to check if the new snapshot has any additional seenRecords
677
- // and revive again if so
678
- const { seenRecords: newSnapshotSeenRecords, recordId: newSnapshotRecordId } = snapshot;
679
- const newKeysToReviveSet = new StoreKeySet();
680
- newKeysToReviveSet.add(newSnapshotRecordId);
681
- newKeysToReviveSet.merge(newSnapshotSeenRecords);
682
- const newKeys = newKeysToReviveSet.keysAsArray();
683
- // in case DS returned additional entries we combine the requested
684
- // and returned keys
685
- const alreadyRequestedOrRevivedSet = keysToReviveSet;
686
- alreadyRequestedOrRevivedSet.merge(revivedKeys);
687
- // if there's any seen keys in the newly rebuilt snapshot that
688
- // haven't already been requested or returned then revive again
689
- for (let i = 0, len = newKeys.length; i < len; i++) {
690
- const newSnapshotSeenKey = newKeys[i];
691
- if (!alreadyRequestedOrRevivedSet.has(newSnapshotSeenKey)) {
692
- return reviveSnapshot(baseEnvironment, durableStore, snapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics);
693
- }
694
- }
695
- }
696
- return { snapshot, metrics: reviveMetrics };
697
- }, (error) => {
698
- durableStoreErrorHandler(error);
699
- // getEntries failed, return the L1 snapshot
700
- return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
701
- });
702
- }
703
-
704
- const TTL_DURABLE_SEGMENT = 'TTL_DURABLE_SEGMENT';
705
- const TTL_DEFAULT_KEY = 'TTL_DEFAULT_KEY';
706
- function buildDurableTTLOverrideStoreKey(namespace, representationName) {
707
- return `${namespace}::${representationName}`;
708
- }
709
- function isEntryDurableTTLOverride(entry) {
710
- if (typeof entry === 'object' && entry !== undefined && entry !== null) {
711
- const data = entry.data;
712
- if (data !== undefined) {
713
- return (data.namespace !== undefined &&
714
- data.representationName !== undefined &&
715
- data.ttl !== undefined);
716
- }
717
- }
718
- return false;
719
- }
720
- function isDefaultDurableTTLOverride(override) {
721
- return (override.namespace === TTL_DEFAULT_KEY && override.representationName === TTL_DEFAULT_KEY);
722
- }
723
- /**
724
- * Class to set and get the TTL override values in the Durable Store
725
- */
726
- class DurableTTLStore {
727
- constructor(durableStore) {
728
- this.durableStore = durableStore;
729
- }
730
- setDefaultDurableTTLOverrides(ttl) {
731
- return this.durableStore.setEntries({
732
- [buildDurableTTLOverrideStoreKey(TTL_DEFAULT_KEY, TTL_DEFAULT_KEY)]: {
733
- data: {
734
- namespace: TTL_DEFAULT_KEY,
735
- representationName: TTL_DEFAULT_KEY,
736
- ttl,
737
- },
738
- },
739
- }, TTL_DURABLE_SEGMENT);
740
- }
741
- setDurableTTLOverride(namespace, representationName, ttl) {
742
- return this.durableStore.setEntries({
743
- [buildDurableTTLOverrideStoreKey(namespace, representationName)]: {
744
- data: { namespace, representationName, ttl },
745
- },
746
- }, TTL_DURABLE_SEGMENT);
747
- }
748
- getDurableTTLOverrides() {
749
- return this.durableStore
750
- .getAllEntries(TTL_DURABLE_SEGMENT)
751
- .then((entries) => {
752
- const overrides = [];
753
- let defaultTTL = undefined;
754
- if (entries === undefined) {
755
- return {
756
- defaultTTL,
757
- overrides,
758
- };
759
- }
760
- const keys$1 = keys$5(entries);
761
- for (let i = 0, len = keys$1.length; i < len; i++) {
762
- const key = keys$1[i];
763
- const entry = entries[key];
764
- if (entry !== undefined && isEntryDurableTTLOverride(entry)) {
765
- if (isDefaultDurableTTLOverride(entry.data)) {
766
- defaultTTL = entry.data;
767
- }
768
- else {
769
- overrides.push(entry.data);
770
- }
771
- }
772
- }
773
- return {
774
- defaultTTL,
775
- overrides,
776
- };
777
- });
778
- }
779
- }
780
-
781
- function copy(source) {
782
- if (typeof source !== 'object' || source === null) {
783
- return source;
784
- }
785
- if (isArray$5(source)) {
786
- // TS doesn't trust that this new array is an array unless we cast it
787
- return [...source];
788
- }
789
- return { ...source };
790
- }
791
- function flushInMemoryStoreValuesToDurableStore(store, durableStore, durableStoreErrorHandler) {
792
- const durableRecords = create$5(null);
793
- const evictedRecords = create$5(null);
794
- const { records, metadata: storeMetadata, visitedIds, refreshedIds, } = store.fallbackStringKeyInMemoryStore;
795
- // TODO: W-8909393 Once metadata is stored in its own segment we need to
796
- // call setEntries for the visitedIds on default segment and call setEntries
797
- // on the metadata segment for the refreshedIds
798
- const keys$1 = keys$5({ ...visitedIds, ...refreshedIds });
799
- for (let i = 0, len = keys$1.length; i < len; i += 1) {
800
- const key = keys$1[i];
801
- const record = records[key];
802
- // this record has been evicted, evict from DS
803
- if (record === undefined) {
804
- evictedRecords[key] = true;
805
- continue;
806
- }
807
- const metadata = storeMetadata[key];
808
- durableRecords[key] = {
809
- // copy the data in case the store is mutated during the
810
- // async setEntries call
811
- data: copy(record),
812
- };
813
- if (metadata !== undefined) {
814
- durableRecords[key].metadata = {
815
- ...metadata,
816
- metadataVersion: DURABLE_METADATA_VERSION,
817
- };
818
- }
819
- }
820
- const durableStoreOperations = [];
821
- // publishes
822
- const recordKeys = keys$5(durableRecords);
823
- if (recordKeys.length > 0) {
824
- durableStoreOperations.push({
825
- type: 'setEntries',
826
- entries: durableRecords,
827
- segment: DefaultDurableSegment,
828
- });
829
- }
830
- // evicts
831
- const evictedKeys = keys$5(evictedRecords);
832
- if (evictedKeys.length > 0) {
833
- durableStoreOperations.push({
834
- type: 'evictEntries',
835
- ids: evictedKeys,
836
- segment: DefaultDurableSegment,
837
- });
838
- }
839
- if (durableStoreOperations.length > 0) {
840
- return durableStore.batchOperations(durableStoreOperations).catch(durableStoreErrorHandler);
841
- }
842
- return Promise.resolve();
843
- }
844
-
845
- const DurableEnvironmentEventDiscriminator = 'durable';
846
- function emitDurableEnvironmentAdapterEvent(eventData, observers) {
847
- emitAdapterEvent({
848
- type: 'environment',
849
- timestamp: Date.now(),
850
- environment: DurableEnvironmentEventDiscriminator,
851
- data: eventData,
852
- }, observers);
853
- }
854
-
855
- async function reviveTTLOverrides(ttlStore, environment) {
856
- const map = await ttlStore.getDurableTTLOverrides();
857
- const { defaultTTL, overrides } = map;
858
- if (defaultTTL !== undefined) {
859
- environment.storeSetDefaultTTLOverride(defaultTTL.ttl);
860
- }
861
- for (let i = 0, len = overrides.length; i < len; i++) {
862
- const { namespace, representationName, ttl } = overrides[i];
863
- environment.storeSetTTLOverride(namespace, representationName, ttl);
864
- }
865
- }
866
-
867
- /**
868
- * Returns an empty InMemoryStore that can be used for ingestion. Copies over
869
- * the TTLOverrides from the given Environment's Store.
870
- */
871
- function buildIngestStagingStore(environment) {
872
- return environment.storeBuildIngestionStagingStore();
873
- }
874
-
875
- const AdapterContextSegment = 'ADAPTER-CONTEXT';
876
- const ADAPTER_CONTEXT_ID_SUFFIX = '__NAMED_CONTEXT';
877
- async function reviveOrCreateContext(adapterId, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded) {
878
- // initialize empty context store
879
- contextStores[adapterId] = create$5(null);
880
- const context = {
881
- set(key, value) {
882
- contextStores[adapterId][key] = value;
883
- durableStore.setEntries({
884
- [adapterId]: { data: contextStores[adapterId] },
885
- }, AdapterContextSegment);
886
- pendingContextStoreKeys.add(adapterId);
887
- },
888
- get(key) {
889
- return contextStores[adapterId][key];
890
- },
891
- };
892
- const contextReturn = () => {
893
- if (onContextLoaded !== undefined) {
894
- return onContextLoaded(context).then(() => {
895
- return context;
896
- });
897
- }
898
- return context;
899
- };
900
- try {
901
- const entries = await durableStore.getEntries([adapterId], AdapterContextSegment);
902
- if (entries !== undefined && entries[adapterId] !== undefined) {
903
- // if durable store has a saved context then load it in the store
904
- contextStores[adapterId] = entries[adapterId].data;
905
- }
906
- }
907
- catch (error) {
908
- durableStoreErrorHandler(error);
909
- }
910
- return contextReturn();
911
- }
912
- function isUnfulfilledSnapshot(cachedSnapshotResult) {
913
- if (cachedSnapshotResult === undefined) {
914
- return false;
915
- }
916
- if ('then' in cachedSnapshotResult) {
917
- return false;
918
- }
919
- return cachedSnapshotResult.state === 'Unfulfilled';
920
- }
921
- /**
922
- * Configures the environment to persist data into a durable store and attempt to resolve
923
- * data from the persistent store before hitting the network.
924
- *
925
- * @param environment The base environment
926
- * @param durableStore A DurableStore implementation
927
- * @param instrumentation An instrumentation function implementation
928
- */
929
- function makeDurable(environment, { durableStore, instrumentation }) {
930
- let ingestStagingStore = null;
931
- const durableTTLStore = new DurableTTLStore(durableStore);
932
- const mergeKeysPromiseMap = new StoreKeyMap();
933
- // When a context store is mutated we write it to L2, which causes DS on change
934
- // event. If this instance of makeDurable caused that L2 write we can ignore that
935
- // on change event. This Set helps us do that.
936
- const pendingContextStoreKeys = new Set();
937
- const contextStores = create$5(null);
938
- let initializationPromise = new Promise((resolve) => {
939
- const finish = () => {
940
- resolve();
941
- initializationPromise = undefined;
942
- };
943
- reviveTTLOverrides(durableTTLStore, environment).then(finish);
944
- });
945
- //instrumentation for durable store errors
946
- const durableStoreErrorHandler = handleDurableStoreRejection(instrumentation);
947
- let disposed = false;
948
- const validateNotDisposed = () => {
949
- if (disposed === true) {
950
- throw new Error('This makeDurable instance has been disposed');
951
- }
952
- };
953
- const unsubscribe = durableStore.registerOnChangedListener(async (changes) => {
954
- const defaultSegmentKeys = [];
955
- const adapterContextSegmentKeys = [];
956
- for (let i = 0, len = changes.length; i < len; i++) {
957
- const change = changes[i];
958
- // we only care about changes to the data which is stored in the default
959
- // segment or the adapter context
960
- if (change.segment === DefaultDurableSegment) {
961
- defaultSegmentKeys.push(...change.ids);
962
- }
963
- else if (change.segment === AdapterContextSegment) {
964
- adapterContextSegmentKeys.push(...change.ids);
965
- }
966
- }
967
- // process adapter context changes
968
- const adapterContextKeysFromDifferentInstance = [];
969
- for (const key of adapterContextSegmentKeys) {
970
- if (pendingContextStoreKeys.has(key)) {
971
- // if this instance caused the L2 write then remove from the
972
- // "pending" Set and move on
973
- pendingContextStoreKeys.delete(key);
974
- }
975
- else {
976
- // else it came from another luvio instance and we need to
977
- // read from L2
978
- adapterContextKeysFromDifferentInstance.push(key);
979
- }
980
- }
981
- if (adapterContextKeysFromDifferentInstance.length > 0) {
982
- try {
983
- const entries = await durableStore.getEntries(adapterContextKeysFromDifferentInstance, AdapterContextSegment);
984
- if (entries !== undefined) {
985
- const entryKeys = keys$5(entries);
986
- for (let i = 0, len = entryKeys.length; i < len; i++) {
987
- const entryKey = entryKeys[i];
988
- const entry = entries[entryKey];
989
- contextStores[entryKey] = entry.data;
990
- }
991
- }
992
- }
993
- catch (error) {
994
- durableStoreErrorHandler(error);
995
- }
996
- }
997
- // process default segment changes
998
- const defaultSegmentKeysLength = defaultSegmentKeys.length;
999
- if (defaultSegmentKeysLength > 0) {
1000
- for (let i = 0; i < defaultSegmentKeysLength; i++) {
1001
- const key = defaultSegmentKeys[i];
1002
- const canonical = environment.storeGetCanonicalKey(key);
1003
- if (canonical !== key) {
1004
- continue;
1005
- }
1006
- // TODO: W-8909393 If expiration is the only thing that changed we should not evict the data... so
1007
- // if we stored expiration and data at different keys (or same keys in different segments)
1008
- // then we could know if only the expiration has changed and we wouldn't need to evict
1009
- // and go through an entire broadcast/revive cycle for unchanged data
1010
- // call base environment storeEvict so this evict is not tracked for durable deletion
1011
- environment.storeEvict(key);
1012
- }
1013
- await environment.storeBroadcast(rebuildSnapshot, environment.snapshotAvailable);
1014
- }
1015
- });
1016
- const dispose = function () {
1017
- validateNotDisposed();
1018
- disposed = true;
1019
- return unsubscribe();
1020
- };
1021
- const storePublish = function (key, data) {
1022
- validateNotDisposed();
1023
- if (ingestStagingStore === null) {
1024
- ingestStagingStore = buildIngestStagingStore(environment);
1025
- }
1026
- ingestStagingStore.publish(key, data);
1027
- // remove record from main luvio L1 cache while we are on the synchronous path
1028
- // because we do not want some other code attempting to use the
1029
- // in-memory values before the durable store onChanged handler
1030
- // calls back and revives the values to in-memory
1031
- environment.storeEvict(key);
1032
- };
1033
- const publishStoreMetadata = function (recordId, storeMetadata) {
1034
- validateNotDisposed();
1035
- if (ingestStagingStore === null) {
1036
- ingestStagingStore = buildIngestStagingStore(environment);
1037
- }
1038
- ingestStagingStore.publishMetadata(recordId, storeMetadata);
1039
- };
1040
- const storeIngest = function (key, ingest, response, luvio) {
1041
- validateNotDisposed();
1042
- // we don't ingest to the luvio L1 store from network directly, we ingest to
1043
- // L2 and let DurableStore on change event revive keys into luvio L1 store
1044
- if (ingestStagingStore === null) {
1045
- ingestStagingStore = buildIngestStagingStore(environment);
1046
- }
1047
- environment.storeIngest(key, ingest, response, luvio, ingestStagingStore);
1048
- };
1049
- const storeIngestError = function (key, errorSnapshot, storeMetadataParams, _storeOverride) {
1050
- validateNotDisposed();
1051
- if (ingestStagingStore === null) {
1052
- ingestStagingStore = buildIngestStagingStore(environment);
1053
- }
1054
- environment.storeIngestError(key, errorSnapshot, storeMetadataParams, ingestStagingStore);
1055
- };
1056
- const storeBroadcast = function (_rebuildSnapshot, _snapshotDataAvailable) {
1057
- validateNotDisposed();
1058
- // publishing to L2 is essentially "broadcasting" because the onChanged
1059
- // handler will fire which will revive records to the main L1 store and
1060
- // call the base storeBroadcast
1061
- return publishChangesToDurableStore();
1062
- };
1063
- const publishChangesToDurableStore = function () {
1064
- validateNotDisposed();
1065
- if (ingestStagingStore === null) {
1066
- return Promise.resolve();
1067
- }
1068
- const promise = flushInMemoryStoreValuesToDurableStore(ingestStagingStore, durableStore, durableStoreErrorHandler);
1069
- ingestStagingStore = null;
1070
- return promise;
1071
- };
1072
- const storeLookup = function (sel, createSnapshot, refresh, ttlStrategy) {
1073
- validateNotDisposed();
1074
- // if this lookup is right after an ingest there will be a staging store
1075
- if (ingestStagingStore !== null) {
1076
- const reader = new Reader(ingestStagingStore, sel.variables, refresh, undefined, ttlStrategy);
1077
- return reader.read(sel);
1078
- }
1079
- // otherwise this is from buildCachedSnapshot and we should use the luvio
1080
- // L1 store
1081
- return environment.storeLookup(sel, createSnapshot, refresh, ttlStrategy);
1082
- };
1083
- const storeEvict = function (key) {
1084
- validateNotDisposed();
1085
- if (ingestStagingStore === null) {
1086
- ingestStagingStore = buildIngestStagingStore(environment);
1087
- }
1088
- ingestStagingStore.evict(key);
1089
- };
1090
- const getNode = function (key) {
1091
- validateNotDisposed();
1092
- if (ingestStagingStore === null) {
1093
- ingestStagingStore = buildIngestStagingStore(environment);
1094
- }
1095
- return environment.getNode(key, ingestStagingStore);
1096
- };
1097
- const wrapNormalizedGraphNode = function (normalized) {
1098
- validateNotDisposed();
1099
- if (ingestStagingStore === null) {
1100
- ingestStagingStore = buildIngestStagingStore(environment);
1101
- }
1102
- return environment.wrapNormalizedGraphNode(normalized, ingestStagingStore);
1103
- };
1104
- const rebuildSnapshot = function (snapshot, onRebuild) {
1105
- validateNotDisposed();
1106
- // try rebuilding from memory
1107
- environment.rebuildSnapshot(snapshot, (rebuilt) => {
1108
- // only try reviving from durable store if snapshot is unfulfilled
1109
- if (rebuilt.state !== 'Unfulfilled') {
1110
- onRebuild(rebuilt);
1111
- return;
1112
- }
1113
- // Do an L2 revive and emit to subscriber using the callback.
1114
- reviveSnapshot(environment, durableStore, rebuilt, durableStoreErrorHandler, () => {
1115
- // reviveSnapshot will revive into L1, and since "records" is a reference
1116
- // (and not a copy) to the L1 records we can use it for rebuild
1117
- let rebuiltSnap;
1118
- environment.rebuildSnapshot(snapshot, (rebuilt) => {
1119
- rebuiltSnap = rebuilt;
1120
- });
1121
- return rebuiltSnap;
1122
- }).then((result) => {
1123
- onRebuild(result.snapshot);
1124
- });
1125
- });
1126
- };
1127
- const withContext = function (adapter, options) {
1128
- validateNotDisposed();
1129
- const { contextId, contextVersion, onContextLoaded } = options;
1130
- let context = undefined;
1131
- let contextKey = `${contextId}`;
1132
- // if a context version is supplied, key with the version encoded
1133
- if (contextVersion !== undefined) {
1134
- contextKey += `::${contextVersion}`;
1135
- }
1136
- contextKey += ADAPTER_CONTEXT_ID_SUFFIX;
1137
- const contextAsPromise = reviveOrCreateContext(contextKey, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded);
1138
- return (config, requestContext) => {
1139
- if (context === undefined) {
1140
- return contextAsPromise.then((revivedContext) => {
1141
- context = revivedContext;
1142
- return adapter(config, context, requestContext); // TODO - remove as any cast after https://github.com/salesforce-experience-platform-emu/luvio/pull/230
1143
- });
1144
- }
1145
- return adapter(config, context, requestContext);
1146
- };
1147
- };
1148
- const storeRedirect = function (existingKey, canonicalKey) {
1149
- validateNotDisposed();
1150
- // call redirect on staging store so "old" keys are removed from L2 on
1151
- // the next publishChangesToDurableStore. NOTE: we don't need to call
1152
- // redirect on the base environment store because staging store and base
1153
- // L1 store share the same redirect and reverseRedirectKeys
1154
- if (ingestStagingStore === null) {
1155
- ingestStagingStore = buildIngestStagingStore(environment);
1156
- }
1157
- ingestStagingStore.redirect(existingKey, canonicalKey);
1158
- };
1159
- const storeSetTTLOverride = function (namespace, representationName, ttl) {
1160
- validateNotDisposed();
1161
- return Promise.all([
1162
- environment.storeSetTTLOverride(namespace, representationName, ttl),
1163
- durableTTLStore.setDurableTTLOverride(namespace, representationName, ttl),
1164
- ]).then();
1165
- };
1166
- const storeSetDefaultTTLOverride = function (ttl) {
1167
- validateNotDisposed();
1168
- return Promise.all([
1169
- environment.storeSetDefaultTTLOverride(ttl),
1170
- durableTTLStore.setDefaultDurableTTLOverrides(ttl),
1171
- ]).then();
1172
- };
1173
- const getDurableTTLOverrides = function () {
1174
- validateNotDisposed();
1175
- return durableTTLStore.getDurableTTLOverrides();
1176
- };
1177
- const dispatchResourceRequest = async function (request, context, eventObservers) {
1178
- validateNotDisposed();
1179
- // non-GET adapters call dispatchResourceRequest before any other luvio
1180
- // function so this is our chance to ensure we're initialized
1181
- if (initializationPromise !== undefined) {
1182
- await initializationPromise;
1183
- }
1184
- return environment.dispatchResourceRequest(request, context, eventObservers);
1185
- };
1186
- // NOTE: we can't use "async" keyword on this function because that would
1187
- // force it to always be an async response. The signature is a union
1188
- // of sync/async so no "awaiting" in this function, just promise-chaining
1189
- const applyCachePolicy = function (luvio, adapterRequestContext, buildSnapshotContext, buildCachedSnapshot, buildNetworkSnapshot) {
1190
- validateNotDisposed();
1191
- const wrappedCacheLookup = (injectedBuildSnapshotContext, injectedStoreLookup) => {
1192
- const snapshot = buildCachedSnapshot(injectedBuildSnapshotContext, injectedStoreLookup, luvio);
1193
- // if the adapter attempted to do an L1 lookup and it was unfulfilled
1194
- // then we can attempt an L2 lookup
1195
- if (isUnfulfilledSnapshot(snapshot)) {
1196
- const start = Date.now();
1197
- emitDurableEnvironmentAdapterEvent({ type: 'l2-revive-start' }, adapterRequestContext.eventObservers);
1198
- const revivedSnapshot = reviveSnapshot(environment, durableStore, snapshot, durableStoreErrorHandler, () => injectedStoreLookup(snapshot.select, snapshot.refresh)).then((result) => {
1199
- emitDurableEnvironmentAdapterEvent({
1200
- type: 'l2-revive-end',
1201
- snapshot: result.snapshot,
1202
- duration: Date.now() - start,
1203
- l2Trips: result.metrics.l2Trips,
1204
- }, adapterRequestContext.eventObservers);
1205
- return result.snapshot;
1206
- });
1207
- return revivedSnapshot;
1208
- }
1209
- // otherwise just return what buildCachedSnapshot gave us
1210
- return snapshot;
1211
- };
1212
- const wrappedApplyCachePolicy = () => {
1213
- return environment.applyCachePolicy(luvio, adapterRequestContext, buildSnapshotContext, wrappedCacheLookup, buildNetworkSnapshot);
1214
- };
1215
- // GET adapters call applyCachePolicy before any other luvio
1216
- // function so this is our chance to ensure we're initialized
1217
- return initializationPromise !== undefined
1218
- ? initializationPromise.then(wrappedApplyCachePolicy)
1219
- : wrappedApplyCachePolicy();
1220
- };
1221
- const getIngestStagingStoreRecords = function () {
1222
- validateNotDisposed();
1223
- if (ingestStagingStore !== null) {
1224
- return ingestStagingStore.fallbackStringKeyInMemoryStore.records;
1225
- }
1226
- return {};
1227
- };
1228
- const getIngestStagingStoreMetadata = function () {
1229
- validateNotDisposed();
1230
- if (ingestStagingStore !== null) {
1231
- return ingestStagingStore.fallbackStringKeyInMemoryStore.metadata;
1232
- }
1233
- return {};
1234
- };
1235
- const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
1236
- validateNotDisposed();
1237
- const cacheKeyMap = getResponseCacheKeysFunc();
1238
- const cacheKeyMapKeys = cacheKeyMap.keysAsArray();
1239
- const keysToRevive = new StoreKeySet();
1240
- for (const cacheKeyMapKey of cacheKeyMapKeys) {
1241
- const cacheKey = cacheKeyMap.get(cacheKeyMapKey);
1242
- if (cacheKey.mergeable === true) {
1243
- keysToRevive.add(cacheKeyMapKey);
1244
- }
1245
- }
1246
- let snapshotFromMemoryIngest = undefined;
1247
- // To-do: Once these are structured keys, will need to support them throughout durable logic W-12356727
1248
- const keysToReviveAsArray = Array.from(keysToRevive.keysAsStrings());
1249
- if (keysToReviveAsArray.length > 0) {
1250
- // if we need to do an L2 read then L2 write then we need to synchronize
1251
- // our read/merge/ingest/write Promise based on the keys so we don't
1252
- // stomp over any data
1253
- const readWritePromise = (async () => {
1254
- const pendingPromises = [];
1255
- for (const key of keysToReviveAsArray) {
1256
- const pendingPromise = mergeKeysPromiseMap.get(key);
1257
- if (pendingPromise !== undefined) {
1258
- // IMPORTANT: while on the synchronous code path we get a
1259
- // handle to pendingPromise and push it onto the array.
1260
- // This is important because later in this synchronous code
1261
- // path we will upsert readWritePromise into the
1262
- // mergeKeysPromiseMap (essentially overwriting pendingPromise
1263
- // in the map).
1264
- pendingPromises.push(pendingPromise);
1265
- }
1266
- }
1267
- await Promise.all(pendingPromises);
1268
- const entries = await durableStore.getEntries(keysToReviveAsArray, DefaultDurableSegment);
1269
- ingestStagingStore = buildIngestStagingStore(environment);
1270
- publishDurableStoreEntries(entries, (key, record) => {
1271
- if (typeof key === 'string') {
1272
- ingestStagingStore.fallbackStringKeyInMemoryStore.records[key] =
1273
- record;
1274
- }
1275
- else {
1276
- ingestStagingStore.recordsMap.set(key, record);
1277
- }
1278
- }, (key, metadata) => {
1279
- if (typeof key === 'string') {
1280
- ingestStagingStore.fallbackStringKeyInMemoryStore.metadata[key] =
1281
- metadata;
1282
- }
1283
- else {
1284
- ingestStagingStore.metadataMap.set(key, metadata);
1285
- }
1286
- });
1287
- snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
1288
- })();
1289
- for (const key of keysToReviveAsArray) {
1290
- // we are overwriting the previous promise at this key, but that
1291
- // is ok because we got a handle to it earlier (see the IMPORTANT
1292
- // comment about 35 lines up)
1293
- mergeKeysPromiseMap.set(key, readWritePromise);
1294
- }
1295
- try {
1296
- await readWritePromise;
1297
- }
1298
- finally {
1299
- for (const key of keysToReviveAsArray) {
1300
- const pendingPromise = mergeKeysPromiseMap.get(key);
1301
- // cleanup the entry from the map if this is the last promise
1302
- // for that key
1303
- if (pendingPromise === readWritePromise) {
1304
- mergeKeysPromiseMap.delete(key);
1305
- }
1306
- }
1307
- }
1308
- }
1309
- else {
1310
- // we aren't doing any merging so we don't have to synchronize, the
1311
- // underlying DurableStore implementation takes care of R/W sync
1312
- // so all we have to do is ingest then write to L2
1313
- ingestStagingStore = buildIngestStagingStore(environment);
1314
- snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
1315
- }
1316
- if (snapshotFromMemoryIngest === undefined) {
1317
- return undefined;
1318
- }
1319
- if (snapshotFromMemoryIngest.state !== 'Unfulfilled') {
1320
- return snapshotFromMemoryIngest;
1321
- }
1322
- // if snapshot from staging store lookup is unfulfilled then do an L2 lookup
1323
- const { select, refresh } = snapshotFromMemoryIngest;
1324
- const result = await reviveSnapshot(environment, durableStore, snapshotFromMemoryIngest, durableStoreErrorHandler, () => environment.storeLookup(select, environment.createSnapshot, refresh));
1325
- return result.snapshot;
1326
- };
1327
- const handleErrorResponse = async function (ingestAndBroadcastFunc) {
1328
- validateNotDisposed();
1329
- ingestStagingStore = buildIngestStagingStore(environment);
1330
- return ingestAndBroadcastFunc();
1331
- };
1332
- const getNotifyChangeStoreEntries = function (keys) {
1333
- validateNotDisposed();
1334
- return durableStore
1335
- .getEntries(keys.map(serializeStructuredKey), DefaultDurableSegment)
1336
- .then((durableRecords) => {
1337
- const entries = [];
1338
- publishDurableStoreEntries(durableRecords, (key, record) => {
1339
- entries.push({
1340
- key,
1341
- record: record,
1342
- });
1343
- }, () => { });
1344
- return entries;
1345
- });
1346
- };
1347
- environment.defaultCachePolicy = {
1348
- type: 'stale-while-revalidate',
1349
- implementation: buildStaleWhileRevalidateImplementation(Number.MAX_SAFE_INTEGER),
1350
- };
1351
- return create$5(environment, {
1352
- publishStoreMetadata: { value: publishStoreMetadata },
1353
- storeIngest: { value: storeIngest },
1354
- storeIngestError: { value: storeIngestError },
1355
- storeBroadcast: { value: storeBroadcast },
1356
- storeLookup: { value: storeLookup },
1357
- storeEvict: { value: storeEvict },
1358
- wrapNormalizedGraphNode: { value: wrapNormalizedGraphNode },
1359
- getNode: { value: getNode },
1360
- rebuildSnapshot: { value: rebuildSnapshot },
1361
- withContext: { value: withContext },
1362
- storeSetTTLOverride: { value: storeSetTTLOverride },
1363
- storeSetDefaultTTLOverride: { value: storeSetDefaultTTLOverride },
1364
- storePublish: { value: storePublish },
1365
- storeRedirect: { value: storeRedirect },
1366
- dispose: { value: dispose },
1367
- publishChangesToDurableStore: { value: publishChangesToDurableStore },
1368
- getDurableTTLOverrides: { value: getDurableTTLOverrides },
1369
- dispatchResourceRequest: { value: dispatchResourceRequest },
1370
- applyCachePolicy: { value: applyCachePolicy },
1371
- getIngestStagingStoreRecords: { value: getIngestStagingStoreRecords },
1372
- getIngestStagingStoreMetadata: { value: getIngestStagingStoreMetadata },
1373
- handleSuccessResponse: { value: handleSuccessResponse },
1374
- handleErrorResponse: { value: handleErrorResponse },
1375
- getNotifyChangeStoreEntries: { value: getNotifyChangeStoreEntries },
1376
- });
522
+ //Durable store error instrumentation key
523
+ const DURABLE_STORE_ERROR = 'durable-store-error';
524
+ /**
525
+ * Returns a function that processes errors from durable store promise rejections.
526
+ * If running in a non-production environment, the error is rethrown.
527
+ * When running in production the error is sent to instrumentation.
528
+ * @param instrument Instrumentation function implementation
529
+ */
530
+ function handleDurableStoreRejection(instrument) {
531
+ return (error) => {
532
+ if (process.env.NODE_ENV !== 'production') {
533
+ throw error;
534
+ }
535
+ if (instrument !== undefined) {
536
+ instrument(() => {
537
+ return {
538
+ [DURABLE_STORE_ERROR]: true,
539
+ error: error,
540
+ };
541
+ });
542
+ }
543
+ };
544
+ }
545
+
546
+ function deepFreeze(value) {
547
+ // No need to freeze primitives
548
+ if (typeof value !== 'object' || value === null) {
549
+ return;
550
+ }
551
+ if (isArray$5(value)) {
552
+ for (let i = 0, len = value.length; i < len; i += 1) {
553
+ deepFreeze(value[i]);
554
+ }
555
+ }
556
+ else {
557
+ const keys$1 = keys$5(value);
558
+ for (let i = 0, len = keys$1.length; i < len; i += 1) {
559
+ deepFreeze(value[keys$1[i]]);
560
+ }
561
+ }
562
+ freeze$1(value);
563
+ }
564
+
565
+ function isStoreEntryError(storeRecord) {
566
+ return storeRecord.__type === 'error';
567
+ }
568
+
569
+ /**
570
+ * Takes a set of entries from DurableStore and publishes them via the passed in funcs.
571
+ * This respects expiration and checks for valid DurableStore data shapes. This should
572
+ * be used over manually parsing DurableStoreEntries
573
+ *
574
+ * @param durableRecords The DurableStoreEntries to parse
575
+ * @param publish A function to call with the data of each DurableStoreEntry
576
+ * @param publishMetadata A function to call with the metadata of each DurableStoreEntry
577
+ * @param pendingWriter the PendingWriter (this is going away soon)
578
+ * @returns
579
+ */
580
+ function publishDurableStoreEntries(durableRecords, publish, publishMetadata) {
581
+ const revivedKeys = new StoreKeySet();
582
+ let hadUnexpectedShape = false;
583
+ if (durableRecords === undefined) {
584
+ return { revivedKeys, hadUnexpectedShape };
585
+ }
586
+ const durableKeys = keys$5(durableRecords);
587
+ if (durableKeys.length === 0) {
588
+ // no records to revive
589
+ return { revivedKeys, hadUnexpectedShape };
590
+ }
591
+ for (let i = 0, len = durableKeys.length; i < len; i += 1) {
592
+ const key = durableKeys[i];
593
+ const durableRecord = durableRecords[key];
594
+ if (isDeprecatedDurableStoreEntry(durableRecord)) {
595
+ // had the old shape, skip reviving this entry.
596
+ hadUnexpectedShape = true;
597
+ continue;
598
+ }
599
+ const { metadata, data } = durableRecord;
600
+ if (data === undefined) {
601
+ // if unexpected data skip reviving
602
+ hadUnexpectedShape = true;
603
+ continue;
604
+ }
605
+ if (metadata !== undefined) {
606
+ const { expirationTimestamp } = metadata;
607
+ if (expirationTimestamp === undefined) {
608
+ // if unexpected expiration data skip reviving
609
+ hadUnexpectedShape = true;
610
+ continue;
611
+ }
612
+ publishMetadata(key, metadata);
613
+ }
614
+ if (isStoreEntryError(data)) {
615
+ // freeze errors on way into L1
616
+ deepFreeze(data.error);
617
+ }
618
+ publish(key, data);
619
+ revivedKeys.add(key);
620
+ }
621
+ return { revivedKeys, hadUnexpectedShape };
622
+ }
623
+ /**
624
+ * This method returns a Promise to a snapshot that is revived from L2 cache. If
625
+ * L2 does not have the entries necessary to fulfill the snapshot then this method
626
+ * will refresh the snapshot from network, and then run the results from network
627
+ * through L2 ingestion, returning the subsequent revived snapshot.
628
+ */
629
+ function reviveSnapshot(baseEnvironment, durableStore,
630
+ // TODO [W-10165787]: We should only allow Unfulfilled snapshot be passed in
631
+ unavailableSnapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics = { l2Trips: [] }) {
632
+ const { recordId, select, seenRecords, state } = unavailableSnapshot;
633
+ // L2 can only revive Unfulfilled snapshots that have a selector since they have the
634
+ // info needed to revive (like missingLinks) and rebuild. Otherwise return L1 snapshot.
635
+ if (state !== 'Unfulfilled' || select === undefined) {
636
+ return Promise.resolve({
637
+ snapshot: unavailableSnapshot,
638
+ metrics: reviveMetrics,
639
+ });
640
+ }
641
+ // in case L1 store changes/deallocs a record while we are doing the async read
642
+ // we attempt to read all keys from L2 - so combine recordId with any seenRecords
643
+ const keysToReviveSet = new StoreKeySet().add(recordId);
644
+ keysToReviveSet.merge(seenRecords);
645
+ const keysToRevive = keysToReviveSet.keysAsArray();
646
+ const canonicalKeys = keysToRevive.map((x) => serializeStructuredKey(baseEnvironment.storeGetCanonicalKey(x)));
647
+ const start = Date.now();
648
+ const { l2Trips } = reviveMetrics;
649
+ return durableStore.getEntries(canonicalKeys, DefaultDurableSegment).then((durableRecords) => {
650
+ l2Trips.push({
651
+ duration: Date.now() - start,
652
+ keysRequestedCount: canonicalKeys.length,
653
+ });
654
+ const { revivedKeys, hadUnexpectedShape } = publishDurableStoreEntries(durableRecords,
655
+ // TODO [W-10072584]: instead of implicitly using L1 we should take in
656
+ // publish and publishMetadata funcs, so callers can decide where to
657
+ // revive to (like they pass in how to do the buildL1Snapshot)
658
+ baseEnvironment.storePublish.bind(baseEnvironment), baseEnvironment.publishStoreMetadata.bind(baseEnvironment));
659
+ // if the data coming back from DS had an unexpected shape then just
660
+ // return the L1 snapshot
661
+ if (hadUnexpectedShape === true) {
662
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
663
+ }
664
+ if (revivedKeys.size() === 0) {
665
+ // durable store doesn't have what we asked for so return L1 snapshot
666
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
667
+ }
668
+ // try building the snapshot from L1 now that we have revived the missingLinks
669
+ const snapshot = buildL1Snapshot();
670
+ // if snapshot is pending then some other in-flight refresh will broadcast
671
+ // later
672
+ if (snapshot.state === 'Pending') {
673
+ return { snapshot, metrics: reviveMetrics };
674
+ }
675
+ if (snapshot.state === 'Unfulfilled') {
676
+ // have to check if the new snapshot has any additional seenRecords
677
+ // and revive again if so
678
+ const { seenRecords: newSnapshotSeenRecords, recordId: newSnapshotRecordId } = snapshot;
679
+ const newKeysToReviveSet = new StoreKeySet();
680
+ newKeysToReviveSet.add(newSnapshotRecordId);
681
+ newKeysToReviveSet.merge(newSnapshotSeenRecords);
682
+ const newKeys = newKeysToReviveSet.keysAsArray();
683
+ // in case DS returned additional entries we combine the requested
684
+ // and returned keys
685
+ const alreadyRequestedOrRevivedSet = keysToReviveSet;
686
+ alreadyRequestedOrRevivedSet.merge(revivedKeys);
687
+ // if there's any seen keys in the newly rebuilt snapshot that
688
+ // haven't already been requested or returned then revive again
689
+ for (let i = 0, len = newKeys.length; i < len; i++) {
690
+ const newSnapshotSeenKey = newKeys[i];
691
+ if (!alreadyRequestedOrRevivedSet.has(newSnapshotSeenKey)) {
692
+ return reviveSnapshot(baseEnvironment, durableStore, snapshot, durableStoreErrorHandler, buildL1Snapshot, reviveMetrics);
693
+ }
694
+ }
695
+ }
696
+ return { snapshot, metrics: reviveMetrics };
697
+ }, (error) => {
698
+ durableStoreErrorHandler(error);
699
+ // getEntries failed, return the L1 snapshot
700
+ return { snapshot: unavailableSnapshot, metrics: reviveMetrics };
701
+ });
702
+ }
703
+
704
+ const TTL_DURABLE_SEGMENT = 'TTL_DURABLE_SEGMENT';
705
+ const TTL_DEFAULT_KEY = 'TTL_DEFAULT_KEY';
706
+ function buildDurableTTLOverrideStoreKey(namespace, representationName) {
707
+ return `${namespace}::${representationName}`;
708
+ }
709
+ function isEntryDurableTTLOverride(entry) {
710
+ if (typeof entry === 'object' && entry !== undefined && entry !== null) {
711
+ const data = entry.data;
712
+ if (data !== undefined) {
713
+ return (data.namespace !== undefined &&
714
+ data.representationName !== undefined &&
715
+ data.ttl !== undefined);
716
+ }
717
+ }
718
+ return false;
719
+ }
720
+ function isDefaultDurableTTLOverride(override) {
721
+ return (override.namespace === TTL_DEFAULT_KEY && override.representationName === TTL_DEFAULT_KEY);
722
+ }
723
+ /**
724
+ * Class to set and get the TTL override values in the Durable Store
725
+ */
726
+ class DurableTTLStore {
727
+ constructor(durableStore) {
728
+ this.durableStore = durableStore;
729
+ }
730
+ setDefaultDurableTTLOverrides(ttl) {
731
+ return this.durableStore.setEntries({
732
+ [buildDurableTTLOverrideStoreKey(TTL_DEFAULT_KEY, TTL_DEFAULT_KEY)]: {
733
+ data: {
734
+ namespace: TTL_DEFAULT_KEY,
735
+ representationName: TTL_DEFAULT_KEY,
736
+ ttl,
737
+ },
738
+ },
739
+ }, TTL_DURABLE_SEGMENT);
740
+ }
741
+ setDurableTTLOverride(namespace, representationName, ttl) {
742
+ return this.durableStore.setEntries({
743
+ [buildDurableTTLOverrideStoreKey(namespace, representationName)]: {
744
+ data: { namespace, representationName, ttl },
745
+ },
746
+ }, TTL_DURABLE_SEGMENT);
747
+ }
748
+ getDurableTTLOverrides() {
749
+ return this.durableStore
750
+ .getAllEntries(TTL_DURABLE_SEGMENT)
751
+ .then((entries) => {
752
+ const overrides = [];
753
+ let defaultTTL = undefined;
754
+ if (entries === undefined) {
755
+ return {
756
+ defaultTTL,
757
+ overrides,
758
+ };
759
+ }
760
+ const keys$1 = keys$5(entries);
761
+ for (let i = 0, len = keys$1.length; i < len; i++) {
762
+ const key = keys$1[i];
763
+ const entry = entries[key];
764
+ if (entry !== undefined && isEntryDurableTTLOverride(entry)) {
765
+ if (isDefaultDurableTTLOverride(entry.data)) {
766
+ defaultTTL = entry.data;
767
+ }
768
+ else {
769
+ overrides.push(entry.data);
770
+ }
771
+ }
772
+ }
773
+ return {
774
+ defaultTTL,
775
+ overrides,
776
+ };
777
+ });
778
+ }
779
+ }
780
+
781
+ function copy(source) {
782
+ if (typeof source !== 'object' || source === null) {
783
+ return source;
784
+ }
785
+ if (isArray$5(source)) {
786
+ // TS doesn't trust that this new array is an array unless we cast it
787
+ return [...source];
788
+ }
789
+ return { ...source };
790
+ }
791
+ function flushInMemoryStoreValuesToDurableStore(store, durableStore, durableStoreErrorHandler) {
792
+ const durableRecords = create$5(null);
793
+ const evictedRecords = create$5(null);
794
+ const { records, metadata: storeMetadata, visitedIds, refreshedIds, } = store.fallbackStringKeyInMemoryStore;
795
+ // TODO: W-8909393 Once metadata is stored in its own segment we need to
796
+ // call setEntries for the visitedIds on default segment and call setEntries
797
+ // on the metadata segment for the refreshedIds
798
+ const keys$1 = keys$5({ ...visitedIds, ...refreshedIds });
799
+ for (let i = 0, len = keys$1.length; i < len; i += 1) {
800
+ const key = keys$1[i];
801
+ const record = records[key];
802
+ // this record has been evicted, evict from DS
803
+ if (record === undefined) {
804
+ evictedRecords[key] = true;
805
+ continue;
806
+ }
807
+ const metadata = storeMetadata[key];
808
+ durableRecords[key] = {
809
+ // copy the data in case the store is mutated during the
810
+ // async setEntries call
811
+ data: copy(record),
812
+ };
813
+ if (metadata !== undefined) {
814
+ durableRecords[key].metadata = {
815
+ ...metadata,
816
+ metadataVersion: DURABLE_METADATA_VERSION,
817
+ };
818
+ }
819
+ }
820
+ const durableStoreOperations = [];
821
+ // publishes
822
+ const recordKeys = keys$5(durableRecords);
823
+ if (recordKeys.length > 0) {
824
+ durableStoreOperations.push({
825
+ type: 'setEntries',
826
+ entries: durableRecords,
827
+ segment: DefaultDurableSegment,
828
+ });
829
+ }
830
+ // evicts
831
+ const evictedKeys = keys$5(evictedRecords);
832
+ if (evictedKeys.length > 0) {
833
+ durableStoreOperations.push({
834
+ type: 'evictEntries',
835
+ ids: evictedKeys,
836
+ segment: DefaultDurableSegment,
837
+ });
838
+ }
839
+ if (durableStoreOperations.length > 0) {
840
+ return durableStore.batchOperations(durableStoreOperations).catch(durableStoreErrorHandler);
841
+ }
842
+ return Promise.resolve();
843
+ }
844
+
845
+ const DurableEnvironmentEventDiscriminator = 'durable';
846
+ function emitDurableEnvironmentAdapterEvent(eventData, observers) {
847
+ emitAdapterEvent({
848
+ type: 'environment',
849
+ timestamp: Date.now(),
850
+ environment: DurableEnvironmentEventDiscriminator,
851
+ data: eventData,
852
+ }, observers);
853
+ }
854
+
855
+ async function reviveTTLOverrides(ttlStore, environment) {
856
+ const map = await ttlStore.getDurableTTLOverrides();
857
+ const { defaultTTL, overrides } = map;
858
+ if (defaultTTL !== undefined) {
859
+ environment.storeSetDefaultTTLOverride(defaultTTL.ttl);
860
+ }
861
+ for (let i = 0, len = overrides.length; i < len; i++) {
862
+ const { namespace, representationName, ttl } = overrides[i];
863
+ environment.storeSetTTLOverride(namespace, representationName, ttl);
864
+ }
865
+ }
866
+
867
+ /**
868
+ * Returns an empty InMemoryStore that can be used for ingestion. Copies over
869
+ * the TTLOverrides from the given Environment's Store.
870
+ */
871
+ function buildIngestStagingStore(environment) {
872
+ return environment.storeBuildIngestionStagingStore();
873
+ }
874
+
875
+ const AdapterContextSegment = 'ADAPTER-CONTEXT';
876
+ const ADAPTER_CONTEXT_ID_SUFFIX = '__NAMED_CONTEXT';
877
+ async function reviveOrCreateContext(adapterId, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded) {
878
+ // initialize empty context store
879
+ contextStores[adapterId] = create$5(null);
880
+ const context = {
881
+ set(key, value) {
882
+ contextStores[adapterId][key] = value;
883
+ durableStore.setEntries({
884
+ [adapterId]: { data: contextStores[adapterId] },
885
+ }, AdapterContextSegment);
886
+ pendingContextStoreKeys.add(adapterId);
887
+ },
888
+ get(key) {
889
+ return contextStores[adapterId][key];
890
+ },
891
+ };
892
+ const contextReturn = () => {
893
+ if (onContextLoaded !== undefined) {
894
+ return onContextLoaded(context).then(() => {
895
+ return context;
896
+ });
897
+ }
898
+ return context;
899
+ };
900
+ try {
901
+ const entries = await durableStore.getEntries([adapterId], AdapterContextSegment);
902
+ if (entries !== undefined && entries[adapterId] !== undefined) {
903
+ // if durable store has a saved context then load it in the store
904
+ contextStores[adapterId] = entries[adapterId].data;
905
+ }
906
+ }
907
+ catch (error) {
908
+ durableStoreErrorHandler(error);
909
+ }
910
+ return contextReturn();
911
+ }
912
+ function isUnfulfilledSnapshot(cachedSnapshotResult) {
913
+ if (cachedSnapshotResult === undefined) {
914
+ return false;
915
+ }
916
+ if ('then' in cachedSnapshotResult) {
917
+ return false;
918
+ }
919
+ return cachedSnapshotResult.state === 'Unfulfilled';
920
+ }
921
+ /**
922
+ * Configures the environment to persist data into a durable store and attempt to resolve
923
+ * data from the persistent store before hitting the network.
924
+ *
925
+ * @param environment The base environment
926
+ * @param durableStore A DurableStore implementation
927
+ * @param instrumentation An instrumentation function implementation
928
+ */
929
+ function makeDurable(environment, { durableStore, instrumentation }) {
930
+ let ingestStagingStore = null;
931
+ const durableTTLStore = new DurableTTLStore(durableStore);
932
+ const mergeKeysPromiseMap = new StoreKeyMap();
933
+ // When a context store is mutated we write it to L2, which causes DS on change
934
+ // event. If this instance of makeDurable caused that L2 write we can ignore that
935
+ // on change event. This Set helps us do that.
936
+ const pendingContextStoreKeys = new Set();
937
+ const contextStores = create$5(null);
938
+ let initializationPromise = new Promise((resolve) => {
939
+ const finish = () => {
940
+ resolve();
941
+ initializationPromise = undefined;
942
+ };
943
+ reviveTTLOverrides(durableTTLStore, environment).then(finish);
944
+ });
945
+ //instrumentation for durable store errors
946
+ const durableStoreErrorHandler = handleDurableStoreRejection(instrumentation);
947
+ let disposed = false;
948
+ const validateNotDisposed = () => {
949
+ if (disposed === true) {
950
+ throw new Error('This makeDurable instance has been disposed');
951
+ }
952
+ };
953
+ const unsubscribe = durableStore.registerOnChangedListener(async (changes) => {
954
+ const defaultSegmentKeys = [];
955
+ const adapterContextSegmentKeys = [];
956
+ for (let i = 0, len = changes.length; i < len; i++) {
957
+ const change = changes[i];
958
+ // we only care about changes to the data which is stored in the default
959
+ // segment or the adapter context
960
+ if (change.segment === DefaultDurableSegment) {
961
+ defaultSegmentKeys.push(...change.ids);
962
+ }
963
+ else if (change.segment === AdapterContextSegment) {
964
+ adapterContextSegmentKeys.push(...change.ids);
965
+ }
966
+ }
967
+ // process adapter context changes
968
+ const adapterContextKeysFromDifferentInstance = [];
969
+ for (const key of adapterContextSegmentKeys) {
970
+ if (pendingContextStoreKeys.has(key)) {
971
+ // if this instance caused the L2 write then remove from the
972
+ // "pending" Set and move on
973
+ pendingContextStoreKeys.delete(key);
974
+ }
975
+ else {
976
+ // else it came from another luvio instance and we need to
977
+ // read from L2
978
+ adapterContextKeysFromDifferentInstance.push(key);
979
+ }
980
+ }
981
+ if (adapterContextKeysFromDifferentInstance.length > 0) {
982
+ try {
983
+ const entries = await durableStore.getEntries(adapterContextKeysFromDifferentInstance, AdapterContextSegment);
984
+ if (entries !== undefined) {
985
+ const entryKeys = keys$5(entries);
986
+ for (let i = 0, len = entryKeys.length; i < len; i++) {
987
+ const entryKey = entryKeys[i];
988
+ const entry = entries[entryKey];
989
+ contextStores[entryKey] = entry.data;
990
+ }
991
+ }
992
+ }
993
+ catch (error) {
994
+ durableStoreErrorHandler(error);
995
+ }
996
+ }
997
+ // process default segment changes
998
+ const defaultSegmentKeysLength = defaultSegmentKeys.length;
999
+ if (defaultSegmentKeysLength > 0) {
1000
+ for (let i = 0; i < defaultSegmentKeysLength; i++) {
1001
+ const key = defaultSegmentKeys[i];
1002
+ const canonical = environment.storeGetCanonicalKey(key);
1003
+ if (canonical !== key) {
1004
+ continue;
1005
+ }
1006
+ // TODO: W-8909393 If expiration is the only thing that changed we should not evict the data... so
1007
+ // if we stored expiration and data at different keys (or same keys in different segments)
1008
+ // then we could know if only the expiration has changed and we wouldn't need to evict
1009
+ // and go through an entire broadcast/revive cycle for unchanged data
1010
+ // call base environment storeEvict so this evict is not tracked for durable deletion
1011
+ environment.storeEvict(key);
1012
+ }
1013
+ await environment.storeBroadcast(rebuildSnapshot, environment.snapshotAvailable);
1014
+ }
1015
+ });
1016
+ const dispose = function () {
1017
+ validateNotDisposed();
1018
+ disposed = true;
1019
+ return unsubscribe();
1020
+ };
1021
+ const storePublish = function (key, data) {
1022
+ validateNotDisposed();
1023
+ if (ingestStagingStore === null) {
1024
+ ingestStagingStore = buildIngestStagingStore(environment);
1025
+ }
1026
+ ingestStagingStore.publish(key, data);
1027
+ // remove record from main luvio L1 cache while we are on the synchronous path
1028
+ // because we do not want some other code attempting to use the
1029
+ // in-memory values before the durable store onChanged handler
1030
+ // calls back and revives the values to in-memory
1031
+ environment.storeEvict(key);
1032
+ };
1033
+ const publishStoreMetadata = function (recordId, storeMetadata) {
1034
+ validateNotDisposed();
1035
+ if (ingestStagingStore === null) {
1036
+ ingestStagingStore = buildIngestStagingStore(environment);
1037
+ }
1038
+ ingestStagingStore.publishMetadata(recordId, storeMetadata);
1039
+ };
1040
+ const storeIngest = function (key, ingest, response, luvio) {
1041
+ validateNotDisposed();
1042
+ // we don't ingest to the luvio L1 store from network directly, we ingest to
1043
+ // L2 and let DurableStore on change event revive keys into luvio L1 store
1044
+ if (ingestStagingStore === null) {
1045
+ ingestStagingStore = buildIngestStagingStore(environment);
1046
+ }
1047
+ environment.storeIngest(key, ingest, response, luvio, ingestStagingStore);
1048
+ };
1049
+ const storeIngestError = function (key, errorSnapshot, storeMetadataParams, _storeOverride) {
1050
+ validateNotDisposed();
1051
+ if (ingestStagingStore === null) {
1052
+ ingestStagingStore = buildIngestStagingStore(environment);
1053
+ }
1054
+ environment.storeIngestError(key, errorSnapshot, storeMetadataParams, ingestStagingStore);
1055
+ };
1056
+ const storeBroadcast = function (_rebuildSnapshot, _snapshotDataAvailable) {
1057
+ validateNotDisposed();
1058
+ // publishing to L2 is essentially "broadcasting" because the onChanged
1059
+ // handler will fire which will revive records to the main L1 store and
1060
+ // call the base storeBroadcast
1061
+ return publishChangesToDurableStore();
1062
+ };
1063
+ const publishChangesToDurableStore = function () {
1064
+ validateNotDisposed();
1065
+ if (ingestStagingStore === null) {
1066
+ return Promise.resolve();
1067
+ }
1068
+ const promise = flushInMemoryStoreValuesToDurableStore(ingestStagingStore, durableStore, durableStoreErrorHandler);
1069
+ ingestStagingStore = null;
1070
+ return promise;
1071
+ };
1072
+ const storeLookup = function (sel, createSnapshot, refresh, ttlStrategy) {
1073
+ validateNotDisposed();
1074
+ // if this lookup is right after an ingest there will be a staging store
1075
+ if (ingestStagingStore !== null) {
1076
+ const reader = new Reader(ingestStagingStore, sel.variables, refresh, undefined, ttlStrategy);
1077
+ return reader.read(sel);
1078
+ }
1079
+ // otherwise this is from buildCachedSnapshot and we should use the luvio
1080
+ // L1 store
1081
+ return environment.storeLookup(sel, createSnapshot, refresh, ttlStrategy);
1082
+ };
1083
+ const storeEvict = function (key) {
1084
+ validateNotDisposed();
1085
+ if (ingestStagingStore === null) {
1086
+ ingestStagingStore = buildIngestStagingStore(environment);
1087
+ }
1088
+ ingestStagingStore.evict(key);
1089
+ };
1090
+ const getNode = function (key) {
1091
+ validateNotDisposed();
1092
+ if (ingestStagingStore === null) {
1093
+ ingestStagingStore = buildIngestStagingStore(environment);
1094
+ }
1095
+ return environment.getNode(key, ingestStagingStore);
1096
+ };
1097
+ const wrapNormalizedGraphNode = function (normalized) {
1098
+ validateNotDisposed();
1099
+ if (ingestStagingStore === null) {
1100
+ ingestStagingStore = buildIngestStagingStore(environment);
1101
+ }
1102
+ return environment.wrapNormalizedGraphNode(normalized, ingestStagingStore);
1103
+ };
1104
+ const rebuildSnapshot = function (snapshot, onRebuild) {
1105
+ validateNotDisposed();
1106
+ // try rebuilding from memory
1107
+ environment.rebuildSnapshot(snapshot, (rebuilt) => {
1108
+ // only try reviving from durable store if snapshot is unfulfilled
1109
+ if (rebuilt.state !== 'Unfulfilled') {
1110
+ onRebuild(rebuilt);
1111
+ return;
1112
+ }
1113
+ // Do an L2 revive and emit to subscriber using the callback.
1114
+ reviveSnapshot(environment, durableStore, rebuilt, durableStoreErrorHandler, () => {
1115
+ // reviveSnapshot will revive into L1, and since "records" is a reference
1116
+ // (and not a copy) to the L1 records we can use it for rebuild
1117
+ let rebuiltSnap;
1118
+ environment.rebuildSnapshot(snapshot, (rebuilt) => {
1119
+ rebuiltSnap = rebuilt;
1120
+ });
1121
+ return rebuiltSnap;
1122
+ }).then((result) => {
1123
+ onRebuild(result.snapshot);
1124
+ });
1125
+ });
1126
+ };
1127
+ const withContext = function (adapter, options) {
1128
+ validateNotDisposed();
1129
+ const { contextId, contextVersion, onContextLoaded } = options;
1130
+ let context = undefined;
1131
+ let contextKey = `${contextId}`;
1132
+ // if a context version is supplied, key with the version encoded
1133
+ if (contextVersion !== undefined) {
1134
+ contextKey += `::${contextVersion}`;
1135
+ }
1136
+ contextKey += ADAPTER_CONTEXT_ID_SUFFIX;
1137
+ const contextAsPromise = reviveOrCreateContext(contextKey, durableStore, durableStoreErrorHandler, contextStores, pendingContextStoreKeys, onContextLoaded);
1138
+ return (config, requestContext) => {
1139
+ if (context === undefined) {
1140
+ return contextAsPromise.then((revivedContext) => {
1141
+ context = revivedContext;
1142
+ return adapter(config, context, requestContext); // TODO - remove as any cast after https://github.com/salesforce-experience-platform-emu/luvio/pull/230
1143
+ });
1144
+ }
1145
+ return adapter(config, context, requestContext);
1146
+ };
1147
+ };
1148
+ const storeRedirect = function (existingKey, canonicalKey) {
1149
+ validateNotDisposed();
1150
+ // call redirect on staging store so "old" keys are removed from L2 on
1151
+ // the next publishChangesToDurableStore. NOTE: we don't need to call
1152
+ // redirect on the base environment store because staging store and base
1153
+ // L1 store share the same redirect and reverseRedirectKeys
1154
+ if (ingestStagingStore === null) {
1155
+ ingestStagingStore = buildIngestStagingStore(environment);
1156
+ }
1157
+ ingestStagingStore.redirect(existingKey, canonicalKey);
1158
+ };
1159
+ const storeSetTTLOverride = function (namespace, representationName, ttl) {
1160
+ validateNotDisposed();
1161
+ return Promise.all([
1162
+ environment.storeSetTTLOverride(namespace, representationName, ttl),
1163
+ durableTTLStore.setDurableTTLOverride(namespace, representationName, ttl),
1164
+ ]).then();
1165
+ };
1166
+ const storeSetDefaultTTLOverride = function (ttl) {
1167
+ validateNotDisposed();
1168
+ return Promise.all([
1169
+ environment.storeSetDefaultTTLOverride(ttl),
1170
+ durableTTLStore.setDefaultDurableTTLOverrides(ttl),
1171
+ ]).then();
1172
+ };
1173
+ const getDurableTTLOverrides = function () {
1174
+ validateNotDisposed();
1175
+ return durableTTLStore.getDurableTTLOverrides();
1176
+ };
1177
+ const dispatchResourceRequest = async function (request, context, eventObservers) {
1178
+ validateNotDisposed();
1179
+ // non-GET adapters call dispatchResourceRequest before any other luvio
1180
+ // function so this is our chance to ensure we're initialized
1181
+ if (initializationPromise !== undefined) {
1182
+ await initializationPromise;
1183
+ }
1184
+ return environment.dispatchResourceRequest(request, context, eventObservers);
1185
+ };
1186
+ // NOTE: we can't use "async" keyword on this function because that would
1187
+ // force it to always be an async response. The signature is a union
1188
+ // of sync/async so no "awaiting" in this function, just promise-chaining
1189
+ const applyCachePolicy = function (luvio, adapterRequestContext, buildSnapshotContext, buildCachedSnapshot, buildNetworkSnapshot) {
1190
+ validateNotDisposed();
1191
+ const wrappedCacheLookup = (injectedBuildSnapshotContext, injectedStoreLookup) => {
1192
+ const snapshot = buildCachedSnapshot(injectedBuildSnapshotContext, injectedStoreLookup, luvio);
1193
+ // if the adapter attempted to do an L1 lookup and it was unfulfilled
1194
+ // then we can attempt an L2 lookup
1195
+ if (isUnfulfilledSnapshot(snapshot)) {
1196
+ const start = Date.now();
1197
+ emitDurableEnvironmentAdapterEvent({ type: 'l2-revive-start' }, adapterRequestContext.eventObservers);
1198
+ const revivedSnapshot = reviveSnapshot(environment, durableStore, snapshot, durableStoreErrorHandler, () => injectedStoreLookup(snapshot.select, snapshot.refresh)).then((result) => {
1199
+ emitDurableEnvironmentAdapterEvent({
1200
+ type: 'l2-revive-end',
1201
+ snapshot: result.snapshot,
1202
+ duration: Date.now() - start,
1203
+ l2Trips: result.metrics.l2Trips,
1204
+ }, adapterRequestContext.eventObservers);
1205
+ return result.snapshot;
1206
+ });
1207
+ return revivedSnapshot;
1208
+ }
1209
+ // otherwise just return what buildCachedSnapshot gave us
1210
+ return snapshot;
1211
+ };
1212
+ const wrappedApplyCachePolicy = () => {
1213
+ return environment.applyCachePolicy(luvio, adapterRequestContext, buildSnapshotContext, wrappedCacheLookup, buildNetworkSnapshot);
1214
+ };
1215
+ // GET adapters call applyCachePolicy before any other luvio
1216
+ // function so this is our chance to ensure we're initialized
1217
+ return initializationPromise !== undefined
1218
+ ? initializationPromise.then(wrappedApplyCachePolicy)
1219
+ : wrappedApplyCachePolicy();
1220
+ };
1221
+ const getIngestStagingStoreRecords = function () {
1222
+ validateNotDisposed();
1223
+ if (ingestStagingStore !== null) {
1224
+ return ingestStagingStore.fallbackStringKeyInMemoryStore.records;
1225
+ }
1226
+ return {};
1227
+ };
1228
+ const getIngestStagingStoreMetadata = function () {
1229
+ validateNotDisposed();
1230
+ if (ingestStagingStore !== null) {
1231
+ return ingestStagingStore.fallbackStringKeyInMemoryStore.metadata;
1232
+ }
1233
+ return {};
1234
+ };
1235
+ const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
1236
+ validateNotDisposed();
1237
+ const cacheKeyMap = getResponseCacheKeysFunc();
1238
+ const cacheKeyMapKeys = cacheKeyMap.keysAsArray();
1239
+ const keysToRevive = new StoreKeySet();
1240
+ for (const cacheKeyMapKey of cacheKeyMapKeys) {
1241
+ const cacheKey = cacheKeyMap.get(cacheKeyMapKey);
1242
+ if (cacheKey.mergeable === true) {
1243
+ keysToRevive.add(cacheKeyMapKey);
1244
+ }
1245
+ }
1246
+ let snapshotFromMemoryIngest = undefined;
1247
+ // To-do: Once these are structured keys, will need to support them throughout durable logic W-12356727
1248
+ const keysToReviveAsArray = Array.from(keysToRevive.keysAsStrings());
1249
+ if (keysToReviveAsArray.length > 0) {
1250
+ // if we need to do an L2 read then L2 write then we need to synchronize
1251
+ // our read/merge/ingest/write Promise based on the keys so we don't
1252
+ // stomp over any data
1253
+ const readWritePromise = (async () => {
1254
+ const pendingPromises = [];
1255
+ for (const key of keysToReviveAsArray) {
1256
+ const pendingPromise = mergeKeysPromiseMap.get(key);
1257
+ if (pendingPromise !== undefined) {
1258
+ // IMPORTANT: while on the synchronous code path we get a
1259
+ // handle to pendingPromise and push it onto the array.
1260
+ // This is important because later in this synchronous code
1261
+ // path we will upsert readWritePromise into the
1262
+ // mergeKeysPromiseMap (essentially overwriting pendingPromise
1263
+ // in the map).
1264
+ pendingPromises.push(pendingPromise);
1265
+ }
1266
+ }
1267
+ await Promise.all(pendingPromises);
1268
+ const entries = await durableStore.getEntries(keysToReviveAsArray, DefaultDurableSegment);
1269
+ ingestStagingStore = buildIngestStagingStore(environment);
1270
+ publishDurableStoreEntries(entries, (key, record) => {
1271
+ if (typeof key === 'string') {
1272
+ ingestStagingStore.fallbackStringKeyInMemoryStore.records[key] =
1273
+ record;
1274
+ }
1275
+ else {
1276
+ ingestStagingStore.recordsMap.set(key, record);
1277
+ }
1278
+ }, (key, metadata) => {
1279
+ if (typeof key === 'string') {
1280
+ ingestStagingStore.fallbackStringKeyInMemoryStore.metadata[key] =
1281
+ metadata;
1282
+ }
1283
+ else {
1284
+ ingestStagingStore.metadataMap.set(key, metadata);
1285
+ }
1286
+ });
1287
+ snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
1288
+ })();
1289
+ for (const key of keysToReviveAsArray) {
1290
+ // we are overwriting the previous promise at this key, but that
1291
+ // is ok because we got a handle to it earlier (see the IMPORTANT
1292
+ // comment about 35 lines up)
1293
+ mergeKeysPromiseMap.set(key, readWritePromise);
1294
+ }
1295
+ try {
1296
+ await readWritePromise;
1297
+ }
1298
+ finally {
1299
+ for (const key of keysToReviveAsArray) {
1300
+ const pendingPromise = mergeKeysPromiseMap.get(key);
1301
+ // cleanup the entry from the map if this is the last promise
1302
+ // for that key
1303
+ if (pendingPromise === readWritePromise) {
1304
+ mergeKeysPromiseMap.delete(key);
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ else {
1310
+ // we aren't doing any merging so we don't have to synchronize, the
1311
+ // underlying DurableStore implementation takes care of R/W sync
1312
+ // so all we have to do is ingest then write to L2
1313
+ ingestStagingStore = buildIngestStagingStore(environment);
1314
+ snapshotFromMemoryIngest = await ingestAndBroadcastFunc();
1315
+ }
1316
+ if (snapshotFromMemoryIngest === undefined) {
1317
+ return undefined;
1318
+ }
1319
+ if (snapshotFromMemoryIngest.state !== 'Unfulfilled') {
1320
+ return snapshotFromMemoryIngest;
1321
+ }
1322
+ // if snapshot from staging store lookup is unfulfilled then do an L2 lookup
1323
+ const { select, refresh } = snapshotFromMemoryIngest;
1324
+ const result = await reviveSnapshot(environment, durableStore, snapshotFromMemoryIngest, durableStoreErrorHandler, () => environment.storeLookup(select, environment.createSnapshot, refresh));
1325
+ return result.snapshot;
1326
+ };
1327
+ const handleErrorResponse = async function (ingestAndBroadcastFunc) {
1328
+ validateNotDisposed();
1329
+ ingestStagingStore = buildIngestStagingStore(environment);
1330
+ return ingestAndBroadcastFunc();
1331
+ };
1332
+ const getNotifyChangeStoreEntries = function (keys) {
1333
+ validateNotDisposed();
1334
+ return durableStore
1335
+ .getEntries(keys.map(serializeStructuredKey), DefaultDurableSegment)
1336
+ .then((durableRecords) => {
1337
+ const entries = [];
1338
+ publishDurableStoreEntries(durableRecords, (key, record) => {
1339
+ entries.push({
1340
+ key,
1341
+ record: record,
1342
+ });
1343
+ }, () => { });
1344
+ return entries;
1345
+ });
1346
+ };
1347
+ environment.defaultCachePolicy = {
1348
+ type: 'stale-while-revalidate',
1349
+ implementation: buildStaleWhileRevalidateImplementation(Number.MAX_SAFE_INTEGER),
1350
+ };
1351
+ return create$5(environment, {
1352
+ publishStoreMetadata: { value: publishStoreMetadata },
1353
+ storeIngest: { value: storeIngest },
1354
+ storeIngestError: { value: storeIngestError },
1355
+ storeBroadcast: { value: storeBroadcast },
1356
+ storeLookup: { value: storeLookup },
1357
+ storeEvict: { value: storeEvict },
1358
+ wrapNormalizedGraphNode: { value: wrapNormalizedGraphNode },
1359
+ getNode: { value: getNode },
1360
+ rebuildSnapshot: { value: rebuildSnapshot },
1361
+ withContext: { value: withContext },
1362
+ storeSetTTLOverride: { value: storeSetTTLOverride },
1363
+ storeSetDefaultTTLOverride: { value: storeSetDefaultTTLOverride },
1364
+ storePublish: { value: storePublish },
1365
+ storeRedirect: { value: storeRedirect },
1366
+ dispose: { value: dispose },
1367
+ publishChangesToDurableStore: { value: publishChangesToDurableStore },
1368
+ getDurableTTLOverrides: { value: getDurableTTLOverrides },
1369
+ dispatchResourceRequest: { value: dispatchResourceRequest },
1370
+ applyCachePolicy: { value: applyCachePolicy },
1371
+ getIngestStagingStoreRecords: { value: getIngestStagingStoreRecords },
1372
+ getIngestStagingStoreMetadata: { value: getIngestStagingStoreMetadata },
1373
+ handleSuccessResponse: { value: handleSuccessResponse },
1374
+ handleErrorResponse: { value: handleErrorResponse },
1375
+ getNotifyChangeStoreEntries: { value: getNotifyChangeStoreEntries },
1376
+ });
1377
1377
  }
1378
1378
 
1379
1379
  /**
@@ -12331,8 +12331,9 @@ function draftAwareGraphQLAdapterFactory(userId, objectInfoService, store, luvio
12331
12331
  if (!rebuildResult.errors) {
12332
12332
  rebuildResult = removeSyntheticFields(rebuildResult, config.query);
12333
12333
  }
12334
+ // 'originalSnapshot' is the local eval snapshot subscribed. It is always in 'Fulfilled' state. This behavior would change once W-1273462(rebuild non-evaluated snapshot when the graphql local eval rebuild is triggered) is resolved.
12334
12335
  return {
12335
- ...nonEvaluatedSnapshot,
12336
+ ...originalSnapshot,
12336
12337
  data: rebuildResult,
12337
12338
  recordId,
12338
12339
  seenRecords: createSeenRecords(seenRecordIds, nonEvaluatedSnapshot),
@@ -14864,6 +14865,7 @@ function formatDisplayValue(value, datatype) {
14864
14865
  }
14865
14866
  }
14866
14867
 
14868
+ //TODO: [W-12734162] - rebuild non-evaluated snapshot when graph rebuild is triggered. The dependency work on luvio needs to be done.
14867
14869
  function makeEnvironmentGraphqlAware(environment) {
14868
14870
  const rebuildSnapshot = function (snapshot, onRebuild) {
14869
14871
  if (isStoreEvalSnapshot(snapshot)) {
@@ -15625,4 +15627,4 @@ register({
15625
15627
  });
15626
15628
 
15627
15629
  export { getRuntime, registerReportObserver, reportGraphqlQueryParseError };
15628
- // version: 1.128.0-7bdcf55d3
15630
+ // version: 1.129.0-caa83ed0e