@memberjunction/core 6.2.2 → 6.3.0-edge.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
- package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
- package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
- package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
- package/dist/generic/appCapabilityRegistry.d.ts +106 -0
- package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
- package/dist/generic/appCapabilityRegistry.js +212 -0
- package/dist/generic/appCapabilityRegistry.js.map +1 -0
- package/dist/generic/baseEngine.d.ts +108 -3
- package/dist/generic/baseEngine.d.ts.map +1 -1
- package/dist/generic/baseEngine.js +891 -122
- package/dist/generic/baseEngine.js.map +1 -1
- package/dist/generic/baseEngineRegistry.d.ts +8 -0
- package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
- package/dist/generic/baseEngineRegistry.js +36 -11
- package/dist/generic/baseEngineRegistry.js.map +1 -1
- package/dist/generic/baseEntity.d.ts +155 -3
- package/dist/generic/baseEntity.d.ts.map +1 -1
- package/dist/generic/baseEntity.js +1146 -74
- package/dist/generic/baseEntity.js.map +1 -1
- package/dist/generic/baseRemotableOperation.d.ts +32 -0
- package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
- package/dist/generic/baseRemotableOperation.js +29 -0
- package/dist/generic/baseRemotableOperation.js.map +1 -1
- package/dist/generic/compositeKey.d.ts.map +1 -1
- package/dist/generic/compositeKey.js +3 -1
- package/dist/generic/compositeKey.js.map +1 -1
- package/dist/generic/constraintErrorRedaction.d.ts +26 -0
- package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
- package/dist/generic/constraintErrorRedaction.js +166 -0
- package/dist/generic/constraintErrorRedaction.js.map +1 -0
- package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
- package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
- package/dist/generic/crossEntityPolicyEngine.js +667 -0
- package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
- package/dist/generic/dataHooks.d.ts +41 -4
- package/dist/generic/dataHooks.d.ts.map +1 -1
- package/dist/generic/dataHooks.js +82 -0
- package/dist/generic/dataHooks.js.map +1 -1
- package/dist/generic/databaseProviderBase.d.ts +96 -1
- package/dist/generic/databaseProviderBase.d.ts.map +1 -1
- package/dist/generic/databaseProviderBase.js +414 -44
- package/dist/generic/databaseProviderBase.js.map +1 -1
- package/dist/generic/documentNumberingEngine.d.ts +190 -0
- package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
- package/dist/generic/documentNumberingEngine.js +739 -0
- package/dist/generic/documentNumberingEngine.js.map +1 -0
- package/dist/generic/entityInfo.d.ts +152 -8
- package/dist/generic/entityInfo.d.ts.map +1 -1
- package/dist/generic/entityInfo.js +507 -71
- package/dist/generic/entityInfo.js.map +1 -1
- package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
- package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
- package/dist/generic/entityLifecyclePolicy.js +708 -0
- package/dist/generic/entityLifecyclePolicy.js.map +1 -0
- package/dist/generic/entitySavePlan.d.ts +6 -0
- package/dist/generic/entitySavePlan.d.ts.map +1 -1
- package/dist/generic/entitySavePlan.js +145 -1
- package/dist/generic/entitySavePlan.js.map +1 -1
- package/dist/generic/entitySubtypeDriver.d.ts +49 -0
- package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
- package/dist/generic/entitySubtypeDriver.js +26 -0
- package/dist/generic/entitySubtypeDriver.js.map +1 -0
- package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
- package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
- package/dist/generic/fieldSecuritySQLGate.js +41 -1
- package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
- package/dist/generic/filters/compositeFilter.d.ts +5 -1
- package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
- package/dist/generic/filters/compositeFilter.js +127 -12
- package/dist/generic/filters/compositeFilter.js.map +1 -1
- package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
- package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
- package/dist/generic/filters/compositeFilterSQL.js +489 -0
- package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
- package/dist/generic/filters/filter.types.d.ts +5 -2
- package/dist/generic/filters/filter.types.d.ts.map +1 -1
- package/dist/generic/filters/filter.types.js +4 -1
- package/dist/generic/filters/filter.types.js.map +1 -1
- package/dist/generic/filters/filterBuilder.d.ts +75 -0
- package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
- package/dist/generic/filters/filterBuilder.js +104 -0
- package/dist/generic/filters/filterBuilder.js.map +1 -0
- package/dist/generic/filters/index.d.ts +2 -0
- package/dist/generic/filters/index.d.ts.map +1 -1
- package/dist/generic/filters/index.js +2 -0
- package/dist/generic/filters/index.js.map +1 -1
- package/dist/generic/interfaces.d.ts +125 -19
- package/dist/generic/interfaces.d.ts.map +1 -1
- package/dist/generic/interfaces.js +9 -10
- package/dist/generic/interfaces.js.map +1 -1
- package/dist/generic/localCacheManager.d.ts +54 -14
- package/dist/generic/localCacheManager.d.ts.map +1 -1
- package/dist/generic/localCacheManager.js +450 -106
- package/dist/generic/localCacheManager.js.map +1 -1
- package/dist/generic/metadata.d.ts +7 -5
- package/dist/generic/metadata.d.ts.map +1 -1
- package/dist/generic/metadata.js +29 -10
- package/dist/generic/metadata.js.map +1 -1
- package/dist/generic/providerBase.d.ts +405 -45
- package/dist/generic/providerBase.d.ts.map +1 -1
- package/dist/generic/providerBase.js +1107 -200
- package/dist/generic/providerBase.js.map +1 -1
- package/dist/generic/queryInfo.d.ts +5 -0
- package/dist/generic/queryInfo.d.ts.map +1 -1
- package/dist/generic/queryInfo.js +5 -0
- package/dist/generic/queryInfo.js.map +1 -1
- package/dist/generic/queryInfoInterfaces.d.ts +5 -0
- package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
- package/dist/generic/queryResultEnricher.d.ts +4 -1
- package/dist/generic/queryResultEnricher.d.ts.map +1 -1
- package/dist/generic/queryResultEnricher.js.map +1 -1
- package/dist/generic/queryTemplateContext.d.ts.map +1 -1
- package/dist/generic/queryTemplateContext.js +38 -3
- package/dist/generic/queryTemplateContext.js.map +1 -1
- package/dist/generic/relatedRecordCollection.d.ts +20 -0
- package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
- package/dist/generic/relatedRecordCollection.js +257 -22
- package/dist/generic/relatedRecordCollection.js.map +1 -1
- package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
- package/dist/generic/remoteOperationDispatch.js +13 -1
- package/dist/generic/remoteOperationDispatch.js.map +1 -1
- package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
- package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
- package/dist/generic/saveEntityGraphOperation.js +8 -0
- package/dist/generic/saveEntityGraphOperation.js.map +1 -1
- package/dist/generic/securityInfo.d.ts +49 -2
- package/dist/generic/securityInfo.d.ts.map +1 -1
- package/dist/generic/securityInfo.js +139 -12
- package/dist/generic/securityInfo.js.map +1 -1
- package/dist/generic/telemetryManager.d.ts +40 -4
- package/dist/generic/telemetryManager.d.ts.map +1 -1
- package/dist/generic/telemetryManager.js +68 -15
- package/dist/generic/telemetryManager.js.map +1 -1
- package/dist/generic/transactionGroup.d.ts +66 -23
- package/dist/generic/transactionGroup.d.ts.map +1 -1
- package/dist/generic/transactionGroup.js +225 -57
- package/dist/generic/transactionGroup.js.map +1 -1
- package/dist/generic/util.d.ts.map +1 -1
- package/dist/generic/util.js +9 -3
- package/dist/generic/util.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/views/runView.d.ts +61 -0
- package/dist/views/runView.d.ts.map +1 -1
- package/dist/views/runView.js +154 -3
- package/dist/views/runView.js.map +1 -1
- package/package.json +3 -3
- package/readme.md +6 -5
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { BaseSingleton, MJGlobal, MJEventType, IsValueEncrypted, ENCRYPTED_SENTINEL } from "@memberjunction/global";
|
|
2
|
-
import {
|
|
2
|
+
import { InMemoryLocalStorageProvider } from "./InMemoryLocalStorageProvider.js";
|
|
3
|
+
import { RunViewParametersKey, IsMaterializedDataSource, NormalizeAlternateBaseViewName } from "../views/runView.js";
|
|
3
4
|
import { GetEffectiveAlternateBaseViewName } from "./alternateBaseViews.js";
|
|
4
5
|
import { ViewPropertyValuesKey } from "../views/viewProperties.js";
|
|
6
|
+
import { CompositeFilter } from "./filters/compositeFilter.js";
|
|
7
|
+
import { CanonicalCompositeFilterKey } from "./filters/compositeFilterSQL.js";
|
|
5
8
|
import { LogError, LogStatusEx, LogWarning } from "./logging.js";
|
|
6
9
|
import { BaseEntity } from "./baseEntity.js";
|
|
7
10
|
import { Metadata } from "./metadata.js";
|
|
@@ -23,9 +26,13 @@ function LogStatusVerbose(message) {
|
|
|
23
26
|
* Freezing the ARRAY matters as much as the rows: `results.sort()` / `.push()` on a live
|
|
24
27
|
* cache array silently reorders or grows the cached slot for every later reader.
|
|
25
28
|
*
|
|
26
|
-
* Freezes BEFORE recursing
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
+
* Freezes BEFORE recursing and records each object in `visited`, which terminates cycles.
|
|
30
|
+
* Objects whose full reachable subgraph finishes freezing without throwing are recorded in
|
|
31
|
+
* {@link deeplyFrozenCacheObjects} so subsequent cache writes (`ApplyDifferentialUpdate`,
|
|
32
|
+
* multi-fingerprint saves, `SetDataset`, or derived `SetRunViewResult` slots) skip already
|
|
33
|
+
* deeply-frozen subtrees in O(1) without allocating `Object.values()` arrays, while still
|
|
34
|
+
* descending into objects that an external caller only froze shallowly via `Object.freeze(row)`.
|
|
35
|
+
* In-place slot maintenance also skips carried rows as a whole via {@link fullyFrozenResultArrays}.
|
|
29
36
|
*
|
|
30
37
|
* Two value kinds are skipped, not frozen — accepted residuals:
|
|
31
38
|
* - Binary payloads (`Buffer`/TypedArray/`ArrayBuffer`, e.g. `varbinary` columns): the spec
|
|
@@ -34,27 +41,72 @@ function LogStatusVerbose(message) {
|
|
|
34
41
|
* - `Date` internal slots: `Object.freeze` cannot protect them — `setHours` and friends
|
|
35
42
|
* still work.
|
|
36
43
|
*/
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
44
|
+
const deeplyFrozenCacheObjects = new WeakSet();
|
|
45
|
+
function deepFreezeCacheSubtree(target, visited, newlyFrozen) {
|
|
46
|
+
if (ArrayBuffer.isView(target) ||
|
|
47
|
+
target instanceof ArrayBuffer ||
|
|
48
|
+
deeplyFrozenCacheObjects.has(target) ||
|
|
49
|
+
visited.has(target)) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// Cycle termination and re-entry short-circuit key off `visited` and `deeplyFrozenCacheObjects`
|
|
53
|
+
// rather than `Object.isFrozen`. Those are not the same test: an object frozen SHALLOWLY by
|
|
54
|
+
// someone else (a caller that ran `Object.freeze(row)` before handing it over) reports frozen
|
|
55
|
+
// while its nested values are still writable, so keying off `isFrozen` would skip the subtree
|
|
56
|
+
// and leave shared state mutable. Only objects whose full subtree completed this walk enter
|
|
57
|
+
// `deeplyFrozenCacheObjects`.
|
|
58
|
+
visited.add(target);
|
|
59
|
+
Object.freeze(target);
|
|
60
|
+
newlyFrozen.push(target);
|
|
61
|
+
if (Array.isArray(target)) {
|
|
62
|
+
const items = target;
|
|
63
|
+
for (let i = 0; i < items.length; i++) {
|
|
64
|
+
const item = items[i];
|
|
65
|
+
if (item !== null && typeof item === 'object') {
|
|
66
|
+
deepFreezeCacheSubtree(item, visited, newlyFrozen);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const record = target;
|
|
72
|
+
for (const key in record) {
|
|
73
|
+
if (Object.prototype.hasOwnProperty.call(record, key)) {
|
|
74
|
+
const nested = record[key];
|
|
75
|
+
if (nested !== null && typeof nested === 'object') {
|
|
76
|
+
deepFreezeCacheSubtree(nested, visited, newlyFrozen);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
41
79
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
80
|
+
}
|
|
81
|
+
function deepFreezeCacheValue(value) {
|
|
82
|
+
if (value === null ||
|
|
83
|
+
typeof value !== 'object' ||
|
|
84
|
+
ArrayBuffer.isView(value) ||
|
|
85
|
+
value instanceof ArrayBuffer ||
|
|
86
|
+
deeplyFrozenCacheObjects.has(value)) {
|
|
49
87
|
return value;
|
|
50
88
|
}
|
|
51
|
-
visited
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
89
|
+
const visited = new WeakSet();
|
|
90
|
+
const newlyFrozen = [];
|
|
91
|
+
deepFreezeCacheSubtree(value, visited, newlyFrozen);
|
|
92
|
+
for (let i = 0; i < newlyFrozen.length; i++) {
|
|
93
|
+
deeplyFrozenCacheObjects.add(newlyFrozen[i]);
|
|
55
94
|
}
|
|
56
95
|
return value;
|
|
57
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* Result arrays known to be deeply frozen: a complete walk of the array finished, or the array
|
|
99
|
+
* was built from an array in this set and rows that were deep-frozen. The binary and Date
|
|
100
|
+
* exceptions above apply.
|
|
101
|
+
*/
|
|
102
|
+
const fullyFrozenResultArrays = new WeakSet();
|
|
103
|
+
/** Adds `payload.results` to {@link fullyFrozenResultArrays} when it is an array. */
|
|
104
|
+
function markResultsFullyFrozen(payload) {
|
|
105
|
+
if ('results' in payload && Array.isArray(payload.results)) {
|
|
106
|
+
fullyFrozenResultArrays.add(payload.results);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const cachedResultPkIndexes = new WeakMap();
|
|
58
110
|
// ============================================================================
|
|
59
111
|
// DEFAULT CONFIGURATION
|
|
60
112
|
// ============================================================================
|
|
@@ -238,8 +290,12 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
238
290
|
? this._initializePromise.then(() => { this.UpdateConfig(config); })
|
|
239
291
|
: this._initializePromise;
|
|
240
292
|
}
|
|
241
|
-
// First caller - start initialization and store the promise
|
|
242
|
-
|
|
293
|
+
// First caller - start initialization and store the promise.
|
|
294
|
+
// Fall back to the currently configured storage provider or a fresh in-memory
|
|
295
|
+
// provider when a caller passes only `config` overrides before any provider has
|
|
296
|
+
// initialized the cache manager (e.g. single-node MJServer without Redis).
|
|
297
|
+
const effectiveProvider = storageProvider ?? this._storageProvider ?? new InMemoryLocalStorageProvider();
|
|
298
|
+
this._initializePromise = this.doInitialize(effectiveProvider, config);
|
|
243
299
|
return this._initializePromise;
|
|
244
300
|
}
|
|
245
301
|
/**
|
|
@@ -873,6 +929,24 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
873
929
|
}
|
|
874
930
|
return max === Number.NEGATIVE_INFINITY ? '' : new Date(max).toISOString();
|
|
875
931
|
}
|
|
932
|
+
/**
|
|
933
|
+
* Resolves the primary key field names for a given entity name against the provided or default metadata provider.
|
|
934
|
+
*/
|
|
935
|
+
resolveEntityPrimaryKeyFields(entityName, provider) {
|
|
936
|
+
if (!entityName)
|
|
937
|
+
return undefined;
|
|
938
|
+
try {
|
|
939
|
+
const md = provider ?? new Metadata();
|
|
940
|
+
const entity = md.EntityByName(entityName);
|
|
941
|
+
if (entity?.PrimaryKeys && entity.PrimaryKeys.length > 0) {
|
|
942
|
+
return entity.PrimaryKeys.map(pk => pk.Name);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
catch {
|
|
946
|
+
// fail-safe: ignore errors when metadata is unavailable
|
|
947
|
+
}
|
|
948
|
+
return undefined;
|
|
949
|
+
}
|
|
876
950
|
/**
|
|
877
951
|
* Storage write options for a RunView slot: the entity name as index group, so a shared
|
|
878
952
|
* provider can find the slot from any process, and the time left before the slot's own expiry
|
|
@@ -880,8 +954,10 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
880
954
|
*
|
|
881
955
|
* @param fingerprint - The slot key
|
|
882
956
|
* @param expiresAt - Absolute expiry (ms since epoch), when the slot has one
|
|
957
|
+
* @param pubSubOverride - Compact row-delta payload and action when broadcasting row updates
|
|
958
|
+
* @param primaryKeyFields - Ordered primary-key field names for the entity
|
|
883
959
|
*/
|
|
884
|
-
runViewWriteOptions(fingerprint, expiresAt, pubSubOverride) {
|
|
960
|
+
runViewWriteOptions(fingerprint, expiresAt, pubSubOverride, primaryKeyFields) {
|
|
885
961
|
const options = {};
|
|
886
962
|
const entity = this.extractEntityFromFingerprint(fingerprint);
|
|
887
963
|
if (entity) {
|
|
@@ -894,6 +970,9 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
894
970
|
options.pubSubAction = pubSubOverride.pubSubAction;
|
|
895
971
|
options.pubSubData = pubSubOverride.pubSubData;
|
|
896
972
|
}
|
|
973
|
+
if (primaryKeyFields && primaryKeyFields.length > 0) {
|
|
974
|
+
options.PrimaryKeyFields = primaryKeyFields;
|
|
975
|
+
}
|
|
897
976
|
return options;
|
|
898
977
|
}
|
|
899
978
|
/** Storage write options for any registry entry; only RunView slots are indexed. */
|
|
@@ -1470,16 +1549,25 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
1470
1549
|
*/
|
|
1471
1550
|
async applyEntityChangesToSlot(fingerprint, changes, nowISO, savesComplete = LocalCacheManager.everySavedRowComplete(changes)) {
|
|
1472
1551
|
const hasSave = changes.some(c => c.Type === 'save');
|
|
1552
|
+
const structuredFilters = hasSave ? this.extractStructuredFiltersOnly(fingerprint) : null;
|
|
1473
1553
|
// Subset and aggregate slots cannot be maintained in place; filtered slots cannot take an
|
|
1474
|
-
// upsert (
|
|
1554
|
+
// upsert (unless their only filter is a structured `cf:` filter evaluated below) but can drop deleted rows.
|
|
1475
1555
|
// A saved row missing columns cannot replace a full-width row either (see RowHasEveryField).
|
|
1476
1556
|
if (this.isSubsetFingerprint(fingerprint) || this.hasAggregates(fingerprint.split('|'))
|
|
1477
|
-
|| (hasSave && this.isFilteredFingerprint(fingerprint))
|
|
1557
|
+
|| (hasSave && this.isFilteredFingerprint(fingerprint) && !structuredFilters)
|
|
1478
1558
|
|| !savesComplete) {
|
|
1479
1559
|
await this.InvalidateRunViewResult(fingerprint);
|
|
1480
1560
|
return;
|
|
1481
1561
|
}
|
|
1482
|
-
const rowChanges = changes.map(c =>
|
|
1562
|
+
const rowChanges = changes.map(c => {
|
|
1563
|
+
if (c.Type !== 'save') {
|
|
1564
|
+
return { Key: c.Key, Row: null };
|
|
1565
|
+
}
|
|
1566
|
+
if (structuredFilters && (!c.Record || !structuredFilters.every(f => f.Evaluate({ '': c.Record })))) {
|
|
1567
|
+
return { Key: c.Key, Row: null };
|
|
1568
|
+
}
|
|
1569
|
+
return { Key: c.Key, Row: c.Record };
|
|
1570
|
+
});
|
|
1483
1571
|
const maintained = await this.ApplyRowChanges(fingerprint, rowChanges, nowISO);
|
|
1484
1572
|
await this.invalidateIfNotMaintained(fingerprint, maintained);
|
|
1485
1573
|
}
|
|
@@ -1582,10 +1670,17 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
1582
1670
|
&& !LocalCacheManager.RowContainsPlaintextEncryptedField(entityInfo, recordData); // per row, not per slot
|
|
1583
1671
|
for (const fingerprint of fingerprintSnapshot) {
|
|
1584
1672
|
try {
|
|
1585
|
-
// Subset slot (MaxRows/StartRow): upserting would
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1673
|
+
// Subset slot (MaxRows/StartRow) or aggregate slot: upserting/removing would corrupt row limits or aggregates.
|
|
1674
|
+
if (rowComplete && !this.isSubsetFingerprint(fingerprint) && !this.hasAggregates(fingerprint.split('|'))) {
|
|
1675
|
+
if (!this.isFilteredFingerprint(fingerprint) || this.matchesStructuredFilterOnlyFingerprint(fingerprint, recordData)) {
|
|
1676
|
+
await this.UpsertSingleEntity(fingerprint, recordData, key, nowISO);
|
|
1677
|
+
}
|
|
1678
|
+
else if (this.isStructuredFilterOnlyFingerprint(fingerprint)) {
|
|
1679
|
+
await this.RemoveSingleEntity(fingerprint, key, nowISO);
|
|
1680
|
+
}
|
|
1681
|
+
else {
|
|
1682
|
+
await this.InvalidateRunViewResult(fingerprint);
|
|
1683
|
+
}
|
|
1589
1684
|
}
|
|
1590
1685
|
else {
|
|
1591
1686
|
await this.InvalidateRunViewResult(fingerprint);
|
|
@@ -1701,10 +1796,10 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
1701
1796
|
const maintained = await this.RemoveSingleEntity(fingerprint, key, nowISO);
|
|
1702
1797
|
await this.invalidateIfNotMaintained(fingerprint, maintained);
|
|
1703
1798
|
}
|
|
1704
|
-
else if (!this.isFilteredFingerprint(fingerprint)) {
|
|
1705
|
-
// Unfiltered cache: update the record in place,
|
|
1706
|
-
// or carries decrypted plaintext on an Encrypt=true field
|
|
1707
|
-
// in-memory plaintext after Save(), which must never be persisted to shared cache/Redis).
|
|
1799
|
+
else if (!this.isFilteredFingerprint(fingerprint) || this.isStructuredFilterOnlyFingerprint(fingerprint)) {
|
|
1800
|
+
// Unfiltered or structured-filter-only (`cf:`) cache: update or remove the record in place,
|
|
1801
|
+
// unless the saved row is missing columns or carries decrypted plaintext on an Encrypt=true field
|
|
1802
|
+
// (BaseEntity.GetAll() holds in-memory plaintext after Save(), which must never be persisted to shared cache/Redis).
|
|
1708
1803
|
const entityData = baseEntity.GetAll();
|
|
1709
1804
|
if (!LocalCacheManager.RowHasEveryField(baseEntity.EntityInfo, entityData) ||
|
|
1710
1805
|
LocalCacheManager.RowContainsPlaintextEncryptedField(baseEntity.EntityInfo, entityData)) {
|
|
@@ -1712,9 +1807,16 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
1712
1807
|
await this.InvalidateRunViewResult(fingerprint);
|
|
1713
1808
|
return;
|
|
1714
1809
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1810
|
+
if (!this.isFilteredFingerprint(fingerprint) || this.matchesStructuredFilterOnlyFingerprint(fingerprint, entityData)) {
|
|
1811
|
+
LogStatusVerbose(`LocalCacheManager: Upserting entity ${keyStr} in cache "${fingerprint.substring(0, 60)}"`);
|
|
1812
|
+
const maintained = await this.UpsertSingleEntity(fingerprint, entityData, key, nowISO);
|
|
1813
|
+
await this.invalidateIfNotMaintained(fingerprint, maintained);
|
|
1814
|
+
}
|
|
1815
|
+
else {
|
|
1816
|
+
LogStatusVerbose(`LocalCacheManager: Removing non-matching entity ${keyStr} from structured-filtered cache "${fingerprint.substring(0, 60)}"`);
|
|
1817
|
+
const maintained = await this.RemoveSingleEntity(fingerprint, key, nowISO);
|
|
1818
|
+
await this.invalidateIfNotMaintained(fingerprint, maintained);
|
|
1819
|
+
}
|
|
1718
1820
|
}
|
|
1719
1821
|
else {
|
|
1720
1822
|
// Filtered cache: conservatively invalidate (can't verify filter match)
|
|
@@ -1796,19 +1898,89 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
1796
1898
|
}
|
|
1797
1899
|
/**
|
|
1798
1900
|
* True when a saved row may be written into `fingerprint`'s slot in place: the slot is neither
|
|
1799
|
-
* filtered (including row-security and field-security segments) nor a subset
|
|
1800
|
-
*
|
|
1901
|
+
* filtered (including row-security and field-security segments) nor a subset — or its only
|
|
1902
|
+
* narrowing predicate is a structured `CompositeFilter` (`cf:...`) that `row` satisfies — and
|
|
1903
|
+
* the row carries every column ({@link RowHasEveryField}) with no plaintext secrets.
|
|
1904
|
+
* Otherwise the slot must be invalidated.
|
|
1801
1905
|
*
|
|
1802
1906
|
* @param fingerprint - The slot to maintain
|
|
1803
1907
|
* @param entity - The saved record's entity
|
|
1804
1908
|
* @param row - The values the save carries
|
|
1805
1909
|
*/
|
|
1806
1910
|
CanUpsertRowIntoSlot(fingerprint, entity, row) {
|
|
1807
|
-
return !this.isFilteredFingerprint(fingerprint)
|
|
1911
|
+
return (!this.isFilteredFingerprint(fingerprint) || this.matchesStructuredFilterOnlyFingerprint(fingerprint, row))
|
|
1808
1912
|
&& !this.isSubsetFingerprint(fingerprint)
|
|
1809
1913
|
&& LocalCacheManager.RowHasEveryField(entity, row)
|
|
1810
1914
|
&& !LocalCacheManager.RowContainsPlaintextEncryptedField(entity, row);
|
|
1811
1915
|
}
|
|
1916
|
+
/**
|
|
1917
|
+
* Parses and returns the structured `CompositeFilter` list when `fingerprint`'s only narrowing
|
|
1918
|
+
* segment is one or more `cf:<json>` segments (no SQL `ExtraFilter`, `OrderBy`, `UserSearch`,
|
|
1919
|
+
* aggregates, or other narrowing segments such as `vw:`, `rls:`, `fls:`, `abv:`, `prm:`, `ds:`,
|
|
1920
|
+
* or narrow `f:`). Returns `null` otherwise.
|
|
1921
|
+
*/
|
|
1922
|
+
extractStructuredFiltersOnly(fingerprint) {
|
|
1923
|
+
const parts = fingerprint.split('|');
|
|
1924
|
+
const BASE_SEGMENTS = 7;
|
|
1925
|
+
if (parts.length < BASE_SEGMENTS) {
|
|
1926
|
+
return null;
|
|
1927
|
+
}
|
|
1928
|
+
if ((parts[1] !== '_' && parts[1] !== '')
|
|
1929
|
+
|| this.hasOrderBy(parts)
|
|
1930
|
+
|| this.hasUserSearch(parts)
|
|
1931
|
+
|| this.hasAggregates(parts)) {
|
|
1932
|
+
return null;
|
|
1933
|
+
}
|
|
1934
|
+
const cfSegments = [];
|
|
1935
|
+
for (let i = BASE_SEGMENTS; i < parts.length; i++) {
|
|
1936
|
+
const seg = parts[i];
|
|
1937
|
+
if (!seg || seg.startsWith('imr:') || seg.includes('://') || seg === 'f:*') {
|
|
1938
|
+
continue;
|
|
1939
|
+
}
|
|
1940
|
+
if (seg.startsWith('cf:')) {
|
|
1941
|
+
cfSegments.push(seg.slice(3).replace(/\\u007c/g, '|'));
|
|
1942
|
+
continue;
|
|
1943
|
+
}
|
|
1944
|
+
return null;
|
|
1945
|
+
}
|
|
1946
|
+
if (cfSegments.length === 0) {
|
|
1947
|
+
return null;
|
|
1948
|
+
}
|
|
1949
|
+
try {
|
|
1950
|
+
return cfSegments.map(cfJson => CompositeFilter.FromJSON(cfJson));
|
|
1951
|
+
}
|
|
1952
|
+
catch {
|
|
1953
|
+
return null;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* Returns true when `fingerprint`'s only narrowing segment is one or more valid structured
|
|
1958
|
+
* `CompositeFilter` segments (`cf:<json>`).
|
|
1959
|
+
*/
|
|
1960
|
+
isStructuredFilterOnlyFingerprint(fingerprint) {
|
|
1961
|
+
return this.extractStructuredFiltersOnly(fingerprint) !== null;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Returns true when `fingerprint`'s only narrowing segment is one or more structured
|
|
1965
|
+
* `CompositeFilter` segments (`cf:<json>`) and `row` satisfies every such filter in memory.
|
|
1966
|
+
* Any SQL `ExtraFilter`, `OrderBy`, `UserSearch`, aggregate, or other narrowing segment
|
|
1967
|
+
* (`vw:`, `rls:`, `fls:`, `abv:`, `prm:`, `ds:`, narrow `f:`) returns false.
|
|
1968
|
+
*/
|
|
1969
|
+
matchesStructuredFilterOnlyFingerprint(fingerprint, row) {
|
|
1970
|
+
if (!row || typeof row !== 'object') {
|
|
1971
|
+
return false;
|
|
1972
|
+
}
|
|
1973
|
+
const filters = this.extractStructuredFiltersOnly(fingerprint);
|
|
1974
|
+
if (!filters) {
|
|
1975
|
+
return false;
|
|
1976
|
+
}
|
|
1977
|
+
try {
|
|
1978
|
+
return filters.every(f => f.Evaluate({ '': row }));
|
|
1979
|
+
}
|
|
1980
|
+
catch {
|
|
1981
|
+
return false;
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1812
1984
|
/**
|
|
1813
1985
|
* Handles a save/delete that could not be applied to a slot this process indexed — in practice
|
|
1814
1986
|
* because the slot expired or was removed by someone else.
|
|
@@ -2280,15 +2452,23 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
2280
2452
|
if (propertyKey.length > 0) {
|
|
2281
2453
|
parts.push(`vp:${propertyKey}`);
|
|
2282
2454
|
}
|
|
2455
|
+
// Bound-parameter segment (RunViewParams.Parameters). Two calls that share the same
|
|
2456
|
+
// parameterized ExtraFilter template (e.g. `Status = @status`) but supply different bound
|
|
2457
|
+
// values must never share a cache slot, and a parameterized view is a narrowed view
|
|
2458
|
+
// (`hasNarrowingSegment` checks index >= 7). Appended ONLY when at least one defined
|
|
2459
|
+
// parameter is present, so non-parameterized calls keep their exact fingerprint.
|
|
2460
|
+
const paramsKey = RunViewParametersKey(params.Parameters);
|
|
2461
|
+
if (paramsKey.length > 0) {
|
|
2462
|
+
parts.push(`prm:${paramsKey}`);
|
|
2463
|
+
}
|
|
2464
|
+
const filterKey = CanonicalCompositeFilterKey(params.Filter);
|
|
2465
|
+
if (filterKey.length > 0) {
|
|
2466
|
+
parts.push(`cf:${filterKey.replace(/\|/g, '\\u007c')}`);
|
|
2467
|
+
}
|
|
2283
2468
|
// Dataset namespace. `GetDatasetByName` caches each dataset ITEM's rows through this same
|
|
2284
2469
|
// builder, supplying only entity + the item's WhereClause — and every shipped item has a
|
|
2285
2470
|
// NULL WhereClause, so without this segment a dataset item emits the identical fingerprint
|
|
2286
|
-
// to a plain unfiltered read of the same entity and the two silently share one slot.
|
|
2287
|
-
// is not merely a stale-data risk: the MJ_Metadata dataset writes its rows with
|
|
2288
|
-
// `ProviderInternalScaffolding` (deliberately UNFROZEN, because bootstrap rearranges them
|
|
2289
|
-
// in place), so the shared slot hands ordinary callers unprotected rows for the hottest
|
|
2290
|
-
// entities in the process — and, in the other direction, an ordinary read repopulating an
|
|
2291
|
-
// evicted slot stores it FROZEN and the next metadata refresh throws.
|
|
2471
|
+
// to a plain unfiltered read of the same entity and the two silently share one slot.
|
|
2292
2472
|
//
|
|
2293
2473
|
// Dataset items may also project columns (`DatasetItem.Columns`), where a RunView slot is
|
|
2294
2474
|
// always the full field set — so the two are not interchangeable in shape either.
|
|
@@ -2499,7 +2679,11 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
2499
2679
|
return payload;
|
|
2500
2680
|
}
|
|
2501
2681
|
try {
|
|
2502
|
-
|
|
2682
|
+
deepFreezeCacheValue(payload);
|
|
2683
|
+
if (payload !== null && typeof payload === 'object') {
|
|
2684
|
+
markResultsFullyFrozen(payload);
|
|
2685
|
+
}
|
|
2686
|
+
return payload;
|
|
2503
2687
|
}
|
|
2504
2688
|
catch (e) {
|
|
2505
2689
|
// The freeze is protective, never load-bearing — an exotic value Object.freeze
|
|
@@ -2670,7 +2854,8 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
2670
2854
|
// Native object storage — IDB structured-clones, localStorage / Redis serialize internally.
|
|
2671
2855
|
const writeNow = Date.now();
|
|
2672
2856
|
const expiresAt = ttlMs ? writeNow + ttlMs : undefined;
|
|
2673
|
-
|
|
2857
|
+
const primaryKeyFields = this.resolveEntityPrimaryKeyFields(params.EntityName, provider);
|
|
2858
|
+
await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, this.runViewWriteOptions(fingerprint, expiresAt, undefined, primaryKeyFields));
|
|
2674
2859
|
this._lastVerifiedAt.set(fingerprint, writeNow);
|
|
2675
2860
|
this.registerEntry({
|
|
2676
2861
|
key: fingerprint,
|
|
@@ -3136,24 +3321,144 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3136
3321
|
return false;
|
|
3137
3322
|
}
|
|
3138
3323
|
const pkFieldNames = changes[0].Key.KeyValuePairs.map(kv => kv.FieldName);
|
|
3139
|
-
const
|
|
3140
|
-
|
|
3141
|
-
if (!
|
|
3324
|
+
const pkSignature = pkFieldNames.join('\u001f');
|
|
3325
|
+
let pkIndex = cachedResultPkIndexes.get(cached.results);
|
|
3326
|
+
if (!pkIndex || pkIndex.PkSignature !== pkSignature) {
|
|
3327
|
+
const indexByKey = new Map();
|
|
3328
|
+
const nullPkIndices = [];
|
|
3329
|
+
for (let i = 0; i < cached.results.length; i++) {
|
|
3330
|
+
const rowObj = cached.results[i];
|
|
3331
|
+
if (pkFieldNames.some(fn => rowObj[fn] == null)) {
|
|
3332
|
+
nullPkIndices.push(i);
|
|
3333
|
+
continue;
|
|
3334
|
+
}
|
|
3335
|
+
indexByKey.set(this.cheapRowKey(rowObj, pkFieldNames), i);
|
|
3336
|
+
}
|
|
3337
|
+
pkIndex = { PkSignature: pkSignature, IndexByKey: indexByKey, NullPkIndices: nullPkIndices };
|
|
3338
|
+
cachedResultPkIndexes.set(cached.results, pkIndex);
|
|
3339
|
+
}
|
|
3340
|
+
let changed = false;
|
|
3341
|
+
let displacedMaxTimestamp = pkIndex.NullPkIndices.length > 0;
|
|
3342
|
+
const upsertsByKey = new Map();
|
|
3343
|
+
const deletesByKey = new Map();
|
|
3344
|
+
const deletedOriginalIndices = new Set(pkIndex.NullPkIndices);
|
|
3345
|
+
const updatedRowByIndex = new Map();
|
|
3346
|
+
for (const change of changes) {
|
|
3347
|
+
const keyStr = this.cheapKeyFromCompositeKey(change.Key);
|
|
3348
|
+
const existingIdx = pkIndex.IndexByKey.get(keyStr);
|
|
3349
|
+
const oldRow = existingIdx !== undefined ? cached.results[existingIdx] : undefined;
|
|
3350
|
+
if (change.Row) {
|
|
3351
|
+
const rowObj = change.Row;
|
|
3352
|
+
if (oldRow && cached.maxUpdatedAt && oldRow.__mj_UpdatedAt === cached.maxUpdatedAt) {
|
|
3353
|
+
displacedMaxTimestamp = true;
|
|
3354
|
+
}
|
|
3355
|
+
upsertsByKey.set(keyStr, rowObj);
|
|
3356
|
+
deletesByKey.delete(keyStr);
|
|
3357
|
+
if (existingIdx !== undefined && !deletedOriginalIndices.has(existingIdx)) {
|
|
3358
|
+
updatedRowByIndex.set(existingIdx, rowObj);
|
|
3359
|
+
}
|
|
3360
|
+
changed = true;
|
|
3361
|
+
}
|
|
3362
|
+
else {
|
|
3363
|
+
// Deletion
|
|
3364
|
+
let wasPresent = false;
|
|
3365
|
+
if (upsertsByKey.has(keyStr)) {
|
|
3366
|
+
upsertsByKey.delete(keyStr);
|
|
3367
|
+
wasPresent = true;
|
|
3368
|
+
}
|
|
3369
|
+
if (existingIdx !== undefined && !deletedOriginalIndices.has(existingIdx)) {
|
|
3370
|
+
deletedOriginalIndices.add(existingIdx);
|
|
3371
|
+
updatedRowByIndex.delete(existingIdx);
|
|
3372
|
+
wasPresent = true;
|
|
3373
|
+
}
|
|
3374
|
+
if (wasPresent) {
|
|
3375
|
+
if (oldRow && cached.maxUpdatedAt && oldRow.__mj_UpdatedAt === cached.maxUpdatedAt) {
|
|
3376
|
+
displacedMaxTimestamp = true;
|
|
3377
|
+
}
|
|
3378
|
+
if (existingIdx !== undefined) {
|
|
3379
|
+
const pkRecord = {};
|
|
3380
|
+
for (const kv of change.Key.KeyValuePairs) {
|
|
3381
|
+
const v = kv.Value;
|
|
3382
|
+
pkRecord[kv.FieldName] =
|
|
3383
|
+
typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null
|
|
3384
|
+
? v
|
|
3385
|
+
: String(v);
|
|
3386
|
+
}
|
|
3387
|
+
deletesByKey.set(keyStr, pkRecord);
|
|
3388
|
+
}
|
|
3389
|
+
changed = true;
|
|
3390
|
+
}
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
if (!changed) {
|
|
3142
3394
|
return true; // only removals of rows the slot does not hold
|
|
3143
3395
|
}
|
|
3144
|
-
|
|
3396
|
+
let nextResults;
|
|
3397
|
+
let nextIndexByKey;
|
|
3398
|
+
if (deletedOriginalIndices.size === 0) {
|
|
3399
|
+
// Fast path: pure updates and/or inserts (the 99% case)
|
|
3400
|
+
nextResults = cached.results.slice();
|
|
3401
|
+
nextIndexByKey = new Map(pkIndex.IndexByKey);
|
|
3402
|
+
for (const [keyStr, rowObj] of upsertsByKey) {
|
|
3403
|
+
const existingIdx = nextIndexByKey.get(keyStr);
|
|
3404
|
+
if (existingIdx !== undefined) {
|
|
3405
|
+
nextResults[existingIdx] = rowObj;
|
|
3406
|
+
}
|
|
3407
|
+
else {
|
|
3408
|
+
const newIdx = nextResults.length;
|
|
3409
|
+
nextResults.push(rowObj);
|
|
3410
|
+
nextIndexByKey.set(keyStr, newIdx);
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
}
|
|
3414
|
+
else {
|
|
3415
|
+
// Delete pass: compact array and re-index in a single pass
|
|
3416
|
+
nextResults = [];
|
|
3417
|
+
nextIndexByKey = new Map();
|
|
3418
|
+
const indexMap = new Int32Array(cached.results.length);
|
|
3419
|
+
let nextIdx = 0;
|
|
3420
|
+
for (let i = 0; i < cached.results.length; i++) {
|
|
3421
|
+
if (deletedOriginalIndices.has(i)) {
|
|
3422
|
+
indexMap[i] = -1;
|
|
3423
|
+
}
|
|
3424
|
+
else {
|
|
3425
|
+
indexMap[i] = nextIdx++;
|
|
3426
|
+
const updated = updatedRowByIndex.get(i);
|
|
3427
|
+
nextResults.push(updated ?? cached.results[i]);
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
for (const [k, oldIdx] of pkIndex.IndexByKey) {
|
|
3431
|
+
const newIdx = indexMap[oldIdx];
|
|
3432
|
+
if (newIdx !== -1) {
|
|
3433
|
+
nextIndexByKey.set(k, newIdx);
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
for (const [keyStr, rowObj] of upsertsByKey) {
|
|
3437
|
+
if (!nextIndexByKey.has(keyStr)) {
|
|
3438
|
+
const newIdx = nextResults.length;
|
|
3439
|
+
nextResults.push(rowObj);
|
|
3440
|
+
nextIndexByKey.set(keyStr, newIdx);
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
cachedResultPkIndexes.set(nextResults, { PkSignature: pkSignature, IndexByKey: nextIndexByKey, NullPkIndices: [] });
|
|
3445
|
+
const upsertedRows = Array.from(upsertsByKey.values());
|
|
3446
|
+
const deletedPrimaryKeys = Array.from(deletesByKey.values());
|
|
3447
|
+
return await this.storeCachedResults(fingerprint, nextResults, newMaxUpdatedAt, {
|
|
3145
3448
|
totalRowCount: cached.totalRowCount,
|
|
3146
3449
|
rowCount: cached.results.length,
|
|
3147
3450
|
schemaHash: cached.schemaHash,
|
|
3148
3451
|
schemaStamp: cached.schemaStamp,
|
|
3149
3452
|
providerInternalScaffolding: cached.providerInternalScaffolding,
|
|
3453
|
+
priorMaxUpdatedAt: cached.maxUpdatedAt,
|
|
3454
|
+
displacedMaxTimestamp,
|
|
3150
3455
|
}, cached.providerInternalScaffolding
|
|
3151
3456
|
? undefined
|
|
3152
3457
|
: {
|
|
3153
|
-
upsertedRows
|
|
3154
|
-
deletedPrimaryKeys
|
|
3458
|
+
upsertedRows,
|
|
3459
|
+
deletedPrimaryKeys,
|
|
3155
3460
|
primaryKeyFields: pkFieldNames,
|
|
3156
|
-
});
|
|
3461
|
+
}, { priorResults: cached.results, changedRows: upsertedRows });
|
|
3157
3462
|
}
|
|
3158
3463
|
catch (e) {
|
|
3159
3464
|
LogError(`LocalCacheManager.ApplyRowChanges failed: ${e}`);
|
|
@@ -3162,52 +3467,32 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3162
3467
|
});
|
|
3163
3468
|
}
|
|
3164
3469
|
/**
|
|
3165
|
-
*
|
|
3166
|
-
*
|
|
3167
|
-
*
|
|
3470
|
+
* Freezes an in-place rewrite of a slot without re-walking the rows it carries forward.
|
|
3471
|
+
*
|
|
3472
|
+
* Applies only when the active provider shares references and `hint.priorResults` is in
|
|
3473
|
+
* {@link fullyFrozenResultArrays}. Every row of `data.results` other than `hint.changedRows`
|
|
3474
|
+
* then comes from that array and is already deeply frozen, so this freezes the new array,
|
|
3475
|
+
* deep-freezes the changed rows and the rest of the envelope, and marks the new array.
|
|
3476
|
+
*
|
|
3477
|
+
* @returns true when the entry is frozen; false when the caller must do the full walk.
|
|
3168
3478
|
*/
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
}
|
|
3177
|
-
return resultMap;
|
|
3178
|
-
}
|
|
3179
|
-
/** Applies `changes` to `rows` in order and collects the collapsed net row delta for pub/sub. */
|
|
3180
|
-
applyChangesToRowMap(rows, changes) {
|
|
3181
|
-
let changed = false;
|
|
3182
|
-
const upsertsByKey = new Map();
|
|
3183
|
-
const deletesByKey = new Map();
|
|
3184
|
-
for (const change of changes) {
|
|
3185
|
-
const keyStr = this.cheapKeyFromCompositeKey(change.Key);
|
|
3186
|
-
if (change.Row) {
|
|
3187
|
-
rows.set(keyStr, change.Row);
|
|
3188
|
-
deletesByKey.delete(keyStr);
|
|
3189
|
-
upsertsByKey.set(keyStr, change.Row);
|
|
3190
|
-
changed = true;
|
|
3191
|
-
}
|
|
3192
|
-
else if (rows.delete(keyStr)) {
|
|
3193
|
-
upsertsByKey.delete(keyStr);
|
|
3194
|
-
const pkRecord = {};
|
|
3195
|
-
for (const kv of change.Key.KeyValuePairs) {
|
|
3196
|
-
const v = kv.Value;
|
|
3197
|
-
pkRecord[kv.FieldName] =
|
|
3198
|
-
typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null
|
|
3199
|
-
? v
|
|
3200
|
-
: String(v);
|
|
3201
|
-
}
|
|
3202
|
-
deletesByKey.set(keyStr, pkRecord);
|
|
3203
|
-
changed = true;
|
|
3479
|
+
freezeChangedRowsOnly(data, hint) {
|
|
3480
|
+
if (!hint || !fullyFrozenResultArrays.has(hint.priorResults) || !this.activeProviderSharesReferences()) {
|
|
3481
|
+
return false;
|
|
3482
|
+
}
|
|
3483
|
+
try {
|
|
3484
|
+
for (const row of hint.changedRows) {
|
|
3485
|
+
deepFreezeCacheValue(row);
|
|
3204
3486
|
}
|
|
3487
|
+
Object.freeze(data.results);
|
|
3488
|
+
deeplyFrozenCacheObjects.add(data.results);
|
|
3489
|
+
deepFreezeCacheValue(data);
|
|
3205
3490
|
}
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3491
|
+
catch {
|
|
3492
|
+
return false;
|
|
3493
|
+
}
|
|
3494
|
+
fullyFrozenResultArrays.add(data.results);
|
|
3495
|
+
return true;
|
|
3211
3496
|
}
|
|
3212
3497
|
/**
|
|
3213
3498
|
* Stores updated results array back to the cache and updates the registry.
|
|
@@ -3223,12 +3508,30 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3223
3508
|
* full-dataset slot is unchanged (prior total == prior length) while a subset slot keeps a
|
|
3224
3509
|
* correct total.
|
|
3225
3510
|
*/
|
|
3226
|
-
async storeCachedResults(fingerprint, updatedResults, newMaxUpdatedAt, prior, rowDelta) {
|
|
3511
|
+
async storeCachedResults(fingerprint, updatedResults, newMaxUpdatedAt, prior, rowDelta, freezeHint) {
|
|
3227
3512
|
// Stamp the slot the way the fill path does — the newest row's __mj_UpdatedAt — so the
|
|
3228
3513
|
// stamp means the same thing whichever funnel wrote the slot and matches what the database
|
|
3229
3514
|
// reports for the same rows (the client smart-cache check compares the two). The caller's
|
|
3230
3515
|
// value (the event time) is used only when the rows carry no timestamp column.
|
|
3231
|
-
|
|
3516
|
+
let maxUpdatedAt;
|
|
3517
|
+
if (rowDelta && prior?.priorMaxUpdatedAt && !prior.displacedMaxTimestamp) {
|
|
3518
|
+
const priorEpoch = Date.parse(prior.priorMaxUpdatedAt);
|
|
3519
|
+
if (!Number.isNaN(priorEpoch)) {
|
|
3520
|
+
const deltaMax = LocalCacheManager.MaxUpdatedAtOfRows(rowDelta.upsertedRows);
|
|
3521
|
+
if (deltaMax) {
|
|
3522
|
+
const deltaEpoch = Date.parse(deltaMax);
|
|
3523
|
+
if (!Number.isNaN(deltaEpoch)) {
|
|
3524
|
+
maxUpdatedAt = deltaEpoch > priorEpoch ? deltaMax : prior.priorMaxUpdatedAt;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
else {
|
|
3528
|
+
maxUpdatedAt = prior.priorMaxUpdatedAt;
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
if (!maxUpdatedAt) {
|
|
3533
|
+
maxUpdatedAt = LocalCacheManager.MaxUpdatedAtOfRows(updatedResults) ?? newMaxUpdatedAt;
|
|
3534
|
+
}
|
|
3232
3535
|
const now = Date.now();
|
|
3233
3536
|
const existingEntry = this._registry.get(fingerprint);
|
|
3234
3537
|
const data = {
|
|
@@ -3271,10 +3574,10 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3271
3574
|
// unfiltered fingerprint, so avoiding a full serialization here matters most.
|
|
3272
3575
|
const sizeBytes = this.estimateResultsSize(updatedResults);
|
|
3273
3576
|
// Second write funnel — this path bypasses SetRunViewResult entirely, so it must
|
|
3274
|
-
// freeze too.
|
|
3275
|
-
//
|
|
3276
|
-
//
|
|
3277
|
-
if (!prior?.providerInternalScaffolding) {
|
|
3577
|
+
// freeze too. When the prior array is marked fully frozen, only the new array, the
|
|
3578
|
+
// envelope and the changed rows are frozen; otherwise the whole entry is walked.
|
|
3579
|
+
// Scaffolding slots stay exempt (see above).
|
|
3580
|
+
if (!prior?.providerInternalScaffolding && !this.freezeChangedRowsOnly(data, freezeHint)) {
|
|
3278
3581
|
this.freezeRowDataIfProviderSharesReferences(data);
|
|
3279
3582
|
}
|
|
3280
3583
|
let pubSubOverride;
|
|
@@ -3293,7 +3596,14 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3293
3596
|
pubSubData: JSON.stringify(deltaPayload),
|
|
3294
3597
|
};
|
|
3295
3598
|
}
|
|
3296
|
-
|
|
3599
|
+
const writeOpts = this.runViewWriteOptions(fingerprint, existingEntry?.expiresAt, pubSubOverride, rowDelta?.primaryKeyFields);
|
|
3600
|
+
let appliedDelta = false;
|
|
3601
|
+
if (pubSubOverride && typeof this._storageProvider.ApplyRunViewRowDelta === 'function') {
|
|
3602
|
+
appliedDelta = await this._storageProvider.ApplyRunViewRowDelta(fingerprint, pubSubOverride.pubSubData, data, writeOpts);
|
|
3603
|
+
}
|
|
3604
|
+
if (!appliedDelta) {
|
|
3605
|
+
await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, writeOpts);
|
|
3606
|
+
}
|
|
3297
3607
|
this._lastVerifiedAt.set(fingerprint, now);
|
|
3298
3608
|
if (existingEntry) {
|
|
3299
3609
|
existingEntry.maxUpdatedAt = maxUpdatedAt;
|
|
@@ -3310,27 +3620,61 @@ export class LocalCacheManager extends BaseSingleton {
|
|
|
3310
3620
|
* Useful when an entity's data changes and all related caches should be cleared.
|
|
3311
3621
|
*
|
|
3312
3622
|
* @param entityName - The entity name to invalidate
|
|
3623
|
+
* @param provider - The metadata provider to resolve the entity against (multi-provider
|
|
3624
|
+
* correctness). Falls back to a default Metadata instance, as the cache-write gate does.
|
|
3313
3625
|
*/
|
|
3314
|
-
async InvalidateEntityCaches(entityName) {
|
|
3626
|
+
async InvalidateEntityCaches(entityName, provider) {
|
|
3315
3627
|
if (!this._storageProvider)
|
|
3316
3628
|
return;
|
|
3629
|
+
// A non-cacheable entity never gets a cache write (see the cache-write gate in
|
|
3630
|
+
// SetRunViewResult), so there is nothing to find — skip the storage lookup and the
|
|
3631
|
+
// registry rewrite. Entries written before AllowCaching was turned off are still in the
|
|
3632
|
+
// local index, so they are still removed below.
|
|
3633
|
+
if (!this.hasLocalFingerprints(entityName) && this.isKnownNonCacheable(entityName, provider)) {
|
|
3634
|
+
return;
|
|
3635
|
+
}
|
|
3317
3636
|
const resolved = await this.resolveFingerprintsForEntity(entityName);
|
|
3318
3637
|
const toRemove = resolved ? Array.from(resolved) : [];
|
|
3319
3638
|
if (toRemove.length > 0) {
|
|
3320
3639
|
LogStatusEx({ message: ` 🗑️ [Cache INVALIDATE-ENTITY] "${entityName}" — removing ${toRemove.length} entries: ${toRemove.map(k => `"${k}"`).join(', ')}`, verboseOnly: true });
|
|
3321
3640
|
}
|
|
3641
|
+
let removed = 0;
|
|
3322
3642
|
for (const key of toRemove) {
|
|
3323
3643
|
try {
|
|
3324
3644
|
await this._storageProvider.Remove(key, CacheCategory.RunViewCache);
|
|
3325
3645
|
this._registry.delete(key);
|
|
3326
3646
|
this._lastVerifiedAt.delete(key);
|
|
3327
3647
|
this.removeFromEntityIndex(key);
|
|
3648
|
+
removed++;
|
|
3328
3649
|
}
|
|
3329
3650
|
catch (e) {
|
|
3330
3651
|
LogError(`LocalCacheManager.InvalidateEntityCaches failed for key ${key}: ${e}`);
|
|
3331
3652
|
}
|
|
3332
3653
|
}
|
|
3333
|
-
|
|
3654
|
+
// Rewriting the registry when nothing changed costs a full storage write per call.
|
|
3655
|
+
if (removed > 0) {
|
|
3656
|
+
await this.persistRegistry();
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
/** True when this process's entity index holds at least one fingerprint for the entity. */
|
|
3660
|
+
hasLocalFingerprints(entityName) {
|
|
3661
|
+
const local = this._entityFingerprintIndex.get(entityName);
|
|
3662
|
+
return local !== undefined && local.size > 0;
|
|
3663
|
+
}
|
|
3664
|
+
/**
|
|
3665
|
+
* True only when the entity resolves in metadata and has AllowCaching = false. An entity
|
|
3666
|
+
* that does not resolve (metadata not loaded yet, or unknown name) is treated as cacheable
|
|
3667
|
+
* so its invalidation still runs.
|
|
3668
|
+
*/
|
|
3669
|
+
isKnownNonCacheable(entityName, provider) {
|
|
3670
|
+
try {
|
|
3671
|
+
const md = provider ?? new Metadata();
|
|
3672
|
+
const entity = md.EntityByName(entityName);
|
|
3673
|
+
return entity !== undefined && entity !== null && !this.IsCachingEnabledForEntity(entity);
|
|
3674
|
+
}
|
|
3675
|
+
catch {
|
|
3676
|
+
return false;
|
|
3677
|
+
}
|
|
3334
3678
|
}
|
|
3335
3679
|
// ========================================================================
|
|
3336
3680
|
// RUNQUERY CACHING
|