@memberjunction/core 6.3.0-edge.1 → 6.3.0-edge.3

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 (72) hide show
  1. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +11 -1
  2. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  3. package/dist/generic/QueryCache.d.ts +2 -2
  4. package/dist/generic/QueryCache.d.ts.map +1 -1
  5. package/dist/generic/QueryCache.js +12 -7
  6. package/dist/generic/QueryCache.js.map +1 -1
  7. package/dist/generic/baseEngine.d.ts +2 -1
  8. package/dist/generic/baseEngine.d.ts.map +1 -1
  9. package/dist/generic/baseEngine.js +13 -5
  10. package/dist/generic/baseEngine.js.map +1 -1
  11. package/dist/generic/baseEntity.d.ts +61 -3
  12. package/dist/generic/baseEntity.d.ts.map +1 -1
  13. package/dist/generic/baseEntity.js +54 -0
  14. package/dist/generic/baseEntity.js.map +1 -1
  15. package/dist/generic/baseRemotableOperation.d.ts +10 -0
  16. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  17. package/dist/generic/baseRemotableOperation.js.map +1 -1
  18. package/dist/generic/databaseProviderBase.d.ts +11 -7
  19. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  20. package/dist/generic/databaseProviderBase.js +69 -16
  21. package/dist/generic/databaseProviderBase.js.map +1 -1
  22. package/dist/generic/entityConfiguration.d.ts +1 -1
  23. package/dist/generic/entityConfiguration.js +2 -2
  24. package/dist/generic/entityInfo.d.ts +122 -2
  25. package/dist/generic/entityInfo.d.ts.map +1 -1
  26. package/dist/generic/entityInfo.js +219 -12
  27. package/dist/generic/entityInfo.js.map +1 -1
  28. package/dist/generic/entityValueFieldSecurity.d.ts.map +1 -1
  29. package/dist/generic/entityValueFieldSecurity.js +1 -0
  30. package/dist/generic/entityValueFieldSecurity.js.map +1 -1
  31. package/dist/generic/interfaces.d.ts +37 -6
  32. package/dist/generic/interfaces.d.ts.map +1 -1
  33. package/dist/generic/interfaces.js.map +1 -1
  34. package/dist/generic/limitsConfig.d.ts +628 -0
  35. package/dist/generic/limitsConfig.d.ts.map +1 -0
  36. package/dist/generic/limitsConfig.js +1266 -0
  37. package/dist/generic/limitsConfig.js.map +1 -0
  38. package/dist/generic/localCacheManager.d.ts +6 -4
  39. package/dist/generic/localCacheManager.d.ts.map +1 -1
  40. package/dist/generic/localCacheManager.js +8 -5
  41. package/dist/generic/localCacheManager.js.map +1 -1
  42. package/dist/generic/providerBase.d.ts +93 -1
  43. package/dist/generic/providerBase.d.ts.map +1 -1
  44. package/dist/generic/providerBase.js +349 -15
  45. package/dist/generic/providerBase.js.map +1 -1
  46. package/dist/generic/securityInfo.d.ts +34 -0
  47. package/dist/generic/securityInfo.d.ts.map +1 -1
  48. package/dist/generic/securityInfo.js +19 -4
  49. package/dist/generic/securityInfo.js.map +1 -1
  50. package/dist/generic/visibility.d.ts +172 -0
  51. package/dist/generic/visibility.d.ts.map +1 -0
  52. package/dist/generic/visibility.js +624 -0
  53. package/dist/generic/visibility.js.map +1 -0
  54. package/dist/generic/visibilityAudit.d.ts +61 -0
  55. package/dist/generic/visibilityAudit.d.ts.map +1 -0
  56. package/dist/generic/visibilityAudit.js +207 -0
  57. package/dist/generic/visibilityAudit.js.map +1 -0
  58. package/dist/generic/visibilityContentOrigin.d.ts +33 -0
  59. package/dist/generic/visibilityContentOrigin.d.ts.map +1 -0
  60. package/dist/generic/visibilityContentOrigin.js +267 -0
  61. package/dist/generic/visibilityContentOrigin.js.map +1 -0
  62. package/dist/index.d.ts +4 -0
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +4 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/tsconfig.tsbuildinfo +1 -1
  67. package/dist/views/decisionReadGuard.d.ts +143 -0
  68. package/dist/views/decisionReadGuard.d.ts.map +1 -0
  69. package/dist/views/decisionReadGuard.js +220 -0
  70. package/dist/views/decisionReadGuard.js.map +1 -0
  71. package/package.json +3 -3
  72. package/readme.md +5 -0
@@ -1,6 +1,6 @@
1
1
  import { BaseEntity } from "./baseEntity.js";
2
2
  import { IsTransportError } from './transportError.js';
3
- import { EntityDocumentTypeInfo, EntityFieldTSType, EntityInfo, EntityPermissionType, FieldSecurityDenialMessage, FieldSecurityError } from "./entityInfo.js";
3
+ import { EntityDocumentTypeInfo, EntityFieldTSType, EntityIndexInfo, EntityInfo, EntityPermissionType, FieldSecurityDenialMessage, FieldSecurityError } from "./entityInfo.js";
4
4
  import { GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride } from "./alternateBaseViews.js";
5
5
  import { ProviderType, AllMetadata } from "./interfaces.js";
6
6
  import { RecordChangeFieldSecurityProjector } from "./recordChangeFieldSecurity.js";
@@ -25,6 +25,7 @@ import { LoadRelatedRecordsBatched } from "./relatedRecordBatchLoader.js";
25
25
  import { GetLocalTimeZone } from "./contextTokens.js";
26
26
  import { FindQueryContextTokens, QueryContextCacheValues } from "./queryTemplateContext.js";
27
27
  import { CompositeFilterSQLCompiler } from "./filters/compositeFilterSQL.js";
28
+ import { WellKnownUserSource } from "./wellKnownUserSource.js";
28
29
  /**
29
30
  * Creates a new instance of AllMetadata from a simple object.
30
31
  * Handles deserialization and proper instantiation of all metadata classes.
@@ -374,6 +375,12 @@ export class ProviderBase {
374
375
  this._metadataScopedReloadFailures = 0;
375
376
  /** Debounce timer for {@link scheduleMetadataMemberRefresh}, and for {@link scheduleMetadataRefreshRetry}. */
376
377
  this._metadataMemberRefreshTimer = null;
378
+ this._entityIndexesMetadataGeneration = 0;
379
+ this._entityIndexesLoadedGeneration = -1;
380
+ this._entityIndexesLoadPromise = null;
381
+ this._entityIndexesLastFailedAt = 0;
382
+ this._entityIndexesLastFailedGeneration = -1;
383
+ this._entityIndexesSystemUserFallbackWarned = false;
377
384
  // ── Metadata change notices from other servers ─────────────────────
378
385
  /** When the current run of undebounced peer notices began; caps how long the check is deferred. */
379
386
  this._peerMetadataNoticeFirstAt = null;
@@ -381,6 +388,12 @@ export class ProviderBase {
381
388
  this._peerMetadataNoticeRetries = 0;
382
389
  /** Debounce timer for {@link HandlePeerMetadataNotice}. */
383
390
  this._peerMetadataNoticeTimer = null;
391
+ /**
392
+ * One-shot handoff from {@link RefreshAfterMetadataMemberChange} to {@link ReloadMetadata}
393
+ * (via {@link Refresh}) indicating that `_latestRemoteMetadataTimestamps` was just read from
394
+ * the authoritative status query and need not be re-queried on the first pass.
395
+ */
396
+ this._metadataRefreshStampsFresh = false;
384
397
  /**
385
398
  * Set by a write-event refresh that found a reload in flight and queued a follow-up pass; that
386
399
  * pass consumes it and applies {@link applyWriteEventRule}. Without it the follow-up would take
@@ -852,6 +865,151 @@ export class ProviderBase {
852
865
  get LoadsQueryMetadata() {
853
866
  return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
854
867
  }
868
+ /**
869
+ * Cooldown (ms) before retrying a failed {@link EnsureEntityIndexesLoaded} attempt within the
870
+ * same metadata generation, so callers do not trigger a retry storm on every request while
871
+ * still recovering automatically from transient backend errors (Finding 285).
872
+ */
873
+ static { this.EntityIndexesFailureCooldownMs = 30000; }
874
+ /**
875
+ * True when `EntityInfo.Indexes` / `EntityInfo.ActiveIndexes` have been hydrated for the
876
+ * current metadata generation via {@link EnsureEntityIndexesLoaded}.
877
+ */
878
+ get EntityIndexesLoaded() {
879
+ return this._entityIndexesLoadedGeneration === this._entityIndexesMetadataGeneration;
880
+ }
881
+ /**
882
+ * Resolves the principal used to hydrate shared index metadata (Finding 285):
883
+ * - On server (`ProviderType.Database`) providers, loads as the MJ system user via
884
+ * {@link WellKnownUserSource} so a restricted first caller can never cache a partial set
885
+ * process-wide (falling back to `this.CurrentUser ?? contextUser` only if no system user
886
+ * source is registered).
887
+ * - On client (`ProviderType.Network`) providers, uses `contextUser ?? this.CurrentUser`.
888
+ */
889
+ async resolveEntityIndexLoadUser(contextUser) {
890
+ if (this.ProviderType !== ProviderType.Database) {
891
+ return contextUser ?? this.CurrentUser;
892
+ }
893
+ let systemUser = null;
894
+ try {
895
+ const source = MJGlobal.Instance.ClassFactory.CreateInstance(WellKnownUserSource);
896
+ systemUser = (await source?.GetSystemUser(this)) ?? null;
897
+ }
898
+ catch (e) {
899
+ LogError(`EnsureEntityIndexesLoaded: WellKnownUserSource.GetSystemUser threw: ${e instanceof Error ? e.message : String(e)}`);
900
+ }
901
+ if (systemUser) {
902
+ return systemUser;
903
+ }
904
+ if (!this._entityIndexesSystemUserFallbackWarned && contextUser && !this.CurrentUser) {
905
+ this._entityIndexesSystemUserFallbackWarned = true;
906
+ LogWarning('EnsureEntityIndexesLoaded: could not resolve the MJ system user for server-side index metadata loading — ' +
907
+ 'falling back to the calling user. Index metadata is cached process-wide, so a restricted caller could leave incomplete data cached.', 'Cache');
908
+ }
909
+ return this.CurrentUser ?? contextUser;
910
+ }
911
+ /**
912
+ * Lazily loads `MJ: Entity Indices` and `MJ: Entity Index Fields` once per metadata generation
913
+ * and attaches them to each {@link EntityInfo} via {@link EntityInfo.SetIndexes} (Findings 267, 285).
914
+ * Single-flight and zero-cost once hydrated; keeps `MJ_Metadata` boot payloads free of ~4,600–5,800
915
+ * index rows (~8–10% overhead). Failed attempts back off for {@link EntityIndexesFailureCooldownMs}
916
+ * within the current metadata generation so callers do not retry-storm on every request.
917
+ */
918
+ async EnsureEntityIndexesLoaded(contextUser) {
919
+ if (this.EntityIndexesLoaded) {
920
+ return;
921
+ }
922
+ if (this._entityIndexesLoadPromise) {
923
+ return this._entityIndexesLoadPromise;
924
+ }
925
+ const gen = this._entityIndexesMetadataGeneration;
926
+ if (this._entityIndexesLastFailedGeneration === gen &&
927
+ ProviderBase.EntityIndexesFailureCooldownMs > 0 &&
928
+ (Date.now() - this._entityIndexesLastFailedAt) < ProviderBase.EntityIndexesFailureCooldownMs) {
929
+ return;
930
+ }
931
+ const loadPromise = (async () => {
932
+ try {
933
+ if (!this.EntityByName('MJ: Entity Indices') || !this.EntityByName('MJ: Entity Index Fields')) {
934
+ if (this._entityIndexesMetadataGeneration === gen) {
935
+ this._entityIndexesLoadedGeneration = gen;
936
+ this._entityIndexesLastFailedAt = 0;
937
+ this._entityIndexesLastFailedGeneration = -1;
938
+ }
939
+ return;
940
+ }
941
+ const loadUser = await this.resolveEntityIndexLoadUser(contextUser);
942
+ const results = await this.RunViews([
943
+ { EntityName: 'MJ: Entity Indices', ResultType: 'simple', IgnoreMaxRows: true },
944
+ { EntityName: 'MJ: Entity Index Fields', ResultType: 'simple', IgnoreMaxRows: true },
945
+ ], loadUser);
946
+ if (!results || results.length < 2 || !results[0].Success || !results[1].Success) {
947
+ if (this._entityIndexesMetadataGeneration === gen) {
948
+ this._entityIndexesLastFailedGeneration = gen;
949
+ this._entityIndexesLastFailedAt = Date.now();
950
+ }
951
+ LogError(`EnsureEntityIndexesLoaded failed: ` +
952
+ `indices=${results?.[0]?.ErrorMessage ?? 'no result'}, ` +
953
+ `fields=${results?.[1]?.ErrorMessage ?? 'no result'}`);
954
+ return;
955
+ }
956
+ if (this._entityIndexesMetadataGeneration !== gen) {
957
+ return;
958
+ }
959
+ const fieldsByIndexId = new Map();
960
+ for (const row of results[1].Results ?? []) {
961
+ const idxId = typeof row.EntityIndexID === 'string' ? NormalizeUUID(row.EntityIndexID) : '';
962
+ if (!idxId) {
963
+ continue;
964
+ }
965
+ let list = fieldsByIndexId.get(idxId);
966
+ if (!list) {
967
+ list = [];
968
+ fieldsByIndexId.set(idxId, list);
969
+ }
970
+ list.push(row);
971
+ }
972
+ const indexesByEntityId = new Map();
973
+ for (const row of results[0].Results ?? []) {
974
+ const entityId = typeof row.EntityID === 'string' ? NormalizeUUID(row.EntityID) : '';
975
+ const idxId = typeof row.ID === 'string' ? NormalizeUUID(row.ID) : '';
976
+ if (!entityId || !idxId) {
977
+ continue;
978
+ }
979
+ const idxInfo = new EntityIndexInfo({
980
+ ...row,
981
+ EntityIndexFields: fieldsByIndexId.get(idxId) ?? [],
982
+ });
983
+ let list = indexesByEntityId.get(entityId);
984
+ if (!list) {
985
+ list = [];
986
+ indexesByEntityId.set(entityId, list);
987
+ }
988
+ list.push(idxInfo);
989
+ }
990
+ for (const entity of this.Entities) {
991
+ entity.SetIndexes(indexesByEntityId.get(NormalizeUUID(entity.ID)) ?? []);
992
+ }
993
+ this._entityIndexesLastFailedAt = 0;
994
+ this._entityIndexesLastFailedGeneration = -1;
995
+ this._entityIndexesLoadedGeneration = gen;
996
+ }
997
+ catch (e) {
998
+ if (this._entityIndexesMetadataGeneration === gen) {
999
+ this._entityIndexesLastFailedGeneration = gen;
1000
+ this._entityIndexesLastFailedAt = Date.now();
1001
+ }
1002
+ LogError(`EnsureEntityIndexesLoaded threw: ${e instanceof Error ? e.message : String(e)}`);
1003
+ }
1004
+ finally {
1005
+ if (this._entityIndexesLoadPromise === loadPromise) {
1006
+ this._entityIndexesLoadPromise = null;
1007
+ }
1008
+ }
1009
+ })();
1010
+ this._entityIndexesLoadPromise = loadPromise;
1011
+ return loadPromise;
1012
+ }
855
1013
  /**
856
1014
  * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
857
1015
  * local dataset cache — so all of them describe the same row set. Null when every item is read.
@@ -1121,6 +1279,17 @@ export class ProviderBase {
1121
1279
  && (event.Category || CacheCategory.Default) === CacheCategory.Default
1122
1280
  && event.CacheKey === this.LocalStoragePrefix + ProviderBase.localStorageTimestampsKey;
1123
1281
  }
1282
+ /**
1283
+ * True while a peer metadata notice check must wait rather than run immediately.
1284
+ * Defaults to {@link MetadataMemberRefreshMustWait} for providers whose metadata reads
1285
+ * cannot bypass an open transaction. Database providers whose `MJ_Metadata` reads run on
1286
+ * the connection pool regardless of unrelated ambient transactions (#4514) override this
1287
+ * to `false` unless {@link MetadataReadsJoinTransaction} is set, so unrelated background
1288
+ * writes on the global provider (such as scheduled jobs) do not defer peer metadata sync.
1289
+ */
1290
+ get PeerMetadataNoticeMustWait() {
1291
+ return this.MetadataMemberRefreshMustWait;
1292
+ }
1124
1293
  /**
1125
1294
  * Reacts to another server saving its metadata snapshot: after a short debounce, runs the
1126
1295
  * normal staleness check ({@link RefreshIfNeeded}, bypassing the check throttle). The check
@@ -1129,6 +1298,11 @@ export class ProviderBase {
1129
1298
  * poll. A server that is already current does no refresh and saves nothing, so notices do not
1130
1299
  * echo around the fleet.
1131
1300
  *
1301
+ * Random thundering-herd jitter ({@link PeerMetadataNoticeJitterMs}) applies only to `removed`
1302
+ * notices (e.g. `mj migrate` clearing the shared snapshot so every server would otherwise query
1303
+ * the database together). On a `set` notice the peer's updated snapshot is already in shared
1304
+ * storage, so only {@link MetadataDatasetRefreshDebounceMs} is waited.
1305
+ *
1132
1306
  * @returns true when the event was a metadata notice (and a check was scheduled)
1133
1307
  */
1134
1308
  HandlePeerMetadataNotice(event) {
@@ -1145,21 +1319,24 @@ export class ProviderBase {
1145
1319
  if (this._peerMetadataNoticeTimer) {
1146
1320
  clearTimeout(this._peerMetadataNoticeTimer);
1147
1321
  }
1322
+ const jitterMs = event.Action === 'removed'
1323
+ ? Math.floor(Math.random() * ProviderBase.PeerMetadataNoticeJitterMs)
1324
+ : 0;
1148
1325
  const timer = setTimeout(() => {
1149
1326
  this._peerMetadataNoticeTimer = null;
1150
- // A provider inside a transaction cannot run the check now (its reads would see the
1151
- // transaction's own uncommitted world, and SQL Server's RefreshIfNeeded refuses
1152
- // outright). Re-arm instead of dropping the notice, which used to lose it entirely.
1327
+ // A provider whose metadata reads would join an open transaction cannot run the check
1328
+ // now (its reads would see the transaction's own uncommitted world). Re-arm instead of
1329
+ // dropping the notice, which used to lose it entirely.
1153
1330
  // The deferral budget is deliberately NOT cleared here: it bounds how long one check
1154
1331
  // may be put off, and the check has not run yet. Clearing it as the timer fires ended
1155
1332
  // the budget exactly when deferral began, leaving the retry count as the only real
1156
1333
  // bound.
1157
- if (this.MetadataMemberRefreshMustWait) {
1334
+ if (this.PeerMetadataNoticeMustWait) {
1158
1335
  this.handlePeerMetadataNoticeRetry();
1159
1336
  return;
1160
1337
  }
1161
1338
  this.runPeerMetadataCheck();
1162
- }, ProviderBase.MetadataDatasetRefreshDebounceMs + Math.floor(Math.random() * ProviderBase.PeerMetadataNoticeJitterMs));
1339
+ }, ProviderBase.MetadataDatasetRefreshDebounceMs + jitterMs);
1163
1340
  if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
1164
1341
  timer.unref();
1165
1342
  }
@@ -1198,7 +1375,7 @@ export class ProviderBase {
1198
1375
  }
1199
1376
  const timer = setTimeout(() => {
1200
1377
  this._peerMetadataNoticeTimer = null;
1201
- if (this.MetadataMemberRefreshMustWait) {
1378
+ if (this.PeerMetadataNoticeMustWait) {
1202
1379
  this.handlePeerMetadataNoticeRetry();
1203
1380
  return;
1204
1381
  }
@@ -1290,7 +1467,16 @@ export class ProviderBase {
1290
1467
  return this.ReloadMetadata(true, undefined, true, true);
1291
1468
  }
1292
1469
  LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
1293
- return this.Refresh();
1470
+ // RefreshRemoteMetadataTimestamps() just succeeded above, so let the first ReloadMetadata
1471
+ // pass triggered by Refresh() reuse those timestamps instead of issuing a second full
1472
+ // metadata-status SQL batch back-to-back.
1473
+ this._metadataRefreshStampsFresh = true;
1474
+ try {
1475
+ return await this.Refresh();
1476
+ }
1477
+ finally {
1478
+ this._metadataRefreshStampsFresh = false;
1479
+ }
1294
1480
  }
1295
1481
  /**
1296
1482
  * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
@@ -1389,6 +1575,20 @@ export class ProviderBase {
1389
1575
  get TrustLocalCacheCompletely() {
1390
1576
  return false;
1391
1577
  }
1578
+ /**
1579
+ * Whether {@link CheckToSeeIfRefreshNeeded} may inspect remote timestamps and adopt a newer
1580
+ * snapshot from shared storage. Defaults to {@link AllowRefresh}.
1581
+ *
1582
+ * Providers that transiently suspend {@link AllowRefresh} while a save is running SQL
1583
+ * (such as `SQLServerDataProvider`) can override this to `true`: metadata status queries run
1584
+ * on the connection pool (`ignoreAmbientTransaction`), and adopting a peer's snapshot from
1585
+ * shared storage atomically replaces `_localMetadata` without mutating any `EntityInfo` held
1586
+ * by an in-flight save. Suspending checks on in-flight saves caused peer metadata notices
1587
+ * arriving during background writes (e.g. scheduled jobs) to be silently dropped.
1588
+ */
1589
+ get AllowRefreshCheck() {
1590
+ return this.AllowRefresh;
1591
+ }
1392
1592
  /**
1393
1593
  * Returns a record's name for synchronous display code, or `undefined` when it is not at hand.
1394
1594
  *
@@ -1591,6 +1791,9 @@ export class ProviderBase {
1591
1791
  return this.enqueueCoalescedRunViews(params, contextUser);
1592
1792
  }
1593
1793
  const key = this.generateDedupKey(params, contextUser);
1794
+ if (key === null) {
1795
+ return this.executeRunViewsPipeline(params, contextUser);
1796
+ }
1594
1797
  const existing = this._inflightViews.get(key);
1595
1798
  // ── Linger hit: resolved result still within the linger window ──
1596
1799
  if (existing?.resolvedResults && existing.resolvedAt) {
@@ -1841,6 +2044,11 @@ export class ProviderBase {
1841
2044
  const entryIndices = [];
1842
2045
  for (const param of entry.params) {
1843
2046
  const key = this.generateDedupKey([param], contextUser);
2047
+ if (key === null) {
2048
+ entryIndices.push(uniqueParams.length);
2049
+ uniqueParams.push(param);
2050
+ continue;
2051
+ }
1844
2052
  let idx = uniqueKeys.get(key);
1845
2053
  if (idx === undefined) {
1846
2054
  idx = uniqueParams.length;
@@ -2003,6 +2211,9 @@ export class ProviderBase {
2003
2211
  }
2004
2212
  async runViewsUncoalesced(params, contextUser) {
2005
2213
  const key = this.generateDedupKey(params, contextUser);
2214
+ if (key === null) {
2215
+ return this.executeRunViewsPipeline(params, contextUser);
2216
+ }
2006
2217
  const existing = this._inflightViews.get(key);
2007
2218
  // ── Linger hit ──
2008
2219
  if (existing?.resolvedResults && existing.resolvedAt) {
@@ -2251,7 +2462,18 @@ export class ProviderBase {
2251
2462
  }
2252
2463
  return result;
2253
2464
  }
2465
+ static { this.UUID_VALUE_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; }
2466
+ static normalizeDedupScalarString(value) {
2467
+ const trimmed = value.trim();
2468
+ return ProviderBase.UUID_VALUE_REGEX.test(trimmed) ? NormalizeUUID(trimmed) : trimmed;
2469
+ }
2254
2470
  generateDedupKey(params, contextUser) {
2471
+ const effectiveUser = contextUser ?? this.CurrentUser;
2472
+ const contextScope = this.ComputeRunViewDedupContextScope(effectiveUser);
2473
+ if (contextScope === null) {
2474
+ return null;
2475
+ }
2476
+ const userIdSegment = contextUser?.ID ? NormalizeUUID(contextUser.ID) : '';
2255
2477
  const parts = params.map(p => {
2256
2478
  const base = LocalCacheManager.Instance.GenerateRunViewFingerprint(p, this.InstanceConnectionString);
2257
2479
  const extras = [
@@ -2262,11 +2484,101 @@ export class ProviderBase {
2262
2484
  p.ViewName ?? '',
2263
2485
  IsExplicitBaseViewOverride(p) ? 'abv_override:base' : '',
2264
2486
  p.TimeZone ?? '',
2265
- contextUser?.ID ?? ''
2487
+ userIdSegment
2266
2488
  ].join('|');
2267
2489
  return `${base}|${extras}`;
2268
2490
  });
2269
- return `${parts.join('||')}|||${this.RunViewDedupScope}`;
2491
+ const baseScope = this.RunViewDedupScope;
2492
+ const combinedScope = contextScope
2493
+ ? (baseScope ? `${baseScope}|${contextScope}` : contextScope)
2494
+ : baseScope;
2495
+ return `${parts.join('||')}|||${combinedScope}`;
2496
+ }
2497
+ /**
2498
+ * Per-call security and tenant scope appended to the RunView dedup key alongside
2499
+ * {@link RunViewDedupScope}. Because request deduplication and the linger window run
2500
+ * before `PreRunView` hooks (which inject tenant filters from `contextUser.TenantContext`)
2501
+ * and before RLS evaluation, two callers sharing the same `contextUser.ID` under different
2502
+ * tenant, magic-link, widget-guest, or API-key scopes must never share an in-flight or
2503
+ * lingering dedup slot.
2504
+ *
2505
+ * Returns `''` when the user carries no per-request isolation context, keeping unscoped
2506
+ * dedup keys unchanged. Returns `null` to bypass deduplication for the call when an
2507
+ * unknown / non-primitive `TenantContext` field shape (e.g. a nested object or array of
2508
+ * objects) is present so isolation is never silently weakened. Subclasses may override
2509
+ * this (calling `super`) to fold in additional per-call scope such as async-local tenant state.
2510
+ */
2511
+ ComputeRunViewDedupContextScope(contextUser) {
2512
+ if (!contextUser)
2513
+ return '';
2514
+ const segments = [];
2515
+ if (contextUser.TenantContext) {
2516
+ const scalarEntries = [];
2517
+ for (const [key, value] of Object.entries(contextUser.TenantContext)) {
2518
+ if (value === undefined || value === null) {
2519
+ continue;
2520
+ }
2521
+ if (typeof value === 'string') {
2522
+ // Only lower-case genuine UUIDs; non-UUID tenant IDs can be case-sensitive (e.g. PostgreSQL)
2523
+ scalarEntries.push(`${key}=${ProviderBase.normalizeDedupScalarString(value)}`);
2524
+ }
2525
+ else if (typeof value === 'number' || typeof value === 'boolean') {
2526
+ scalarEntries.push(`${key}=${String(value)}`);
2527
+ }
2528
+ else if (Array.isArray(value) && value.every(v => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')) {
2529
+ const serialized = value
2530
+ .map(v => (typeof v === 'string' ? ProviderBase.normalizeDedupScalarString(v) : String(v)))
2531
+ .sort()
2532
+ .join(',');
2533
+ scalarEntries.push(`${key}=[${serialized}]`);
2534
+ }
2535
+ else {
2536
+ // Fail closed: nested objects or arrays of objects cannot be safely folded
2537
+ // into a flat scalar key, so bypass dedup for this call.
2538
+ return null;
2539
+ }
2540
+ }
2541
+ scalarEntries.sort();
2542
+ segments.push(`tc:${scalarEntries.join(',')}`);
2543
+ }
2544
+ if (contextUser.MagicLinkScope) {
2545
+ const rt = (contextUser.MagicLinkScope.ResourceType ?? '').trim().toLowerCase();
2546
+ const rid = contextUser.MagicLinkScope.ResourceID ? NormalizeUUID(contextUser.MagicLinkScope.ResourceID) : '';
2547
+ segments.push(`ml:${rt}:${rid}`);
2548
+ }
2549
+ if (contextUser.APIKeyActingContext) {
2550
+ const ak = contextUser.APIKeyActingContext;
2551
+ const orgId = ak.ActingOrganizationID ? NormalizeUUID(ak.ActingOrganizationID) : '';
2552
+ const personId = ak.ActingPersonID ? NormalizeUUID(ak.ActingPersonID) : '';
2553
+ const scopeId = (ak.ActingScopeID ?? '').trim().toLowerCase();
2554
+ const companies = (ak.ActingCompanyIDs ?? []).map(id => NormalizeUUID(id)).sort().join(',');
2555
+ segments.push(`ak:${orgId}:${personId}:${scopeId}:${companies}`);
2556
+ }
2557
+ if (contextUser.APIKeyRowFilters && contextUser.APIKeyRowFilters.length > 0) {
2558
+ const filters = contextUser.APIKeyRowFilters
2559
+ .map(f => `${NormalizeUUID(f.EntityID)}:${f.PermissionType}:${NormalizeUUID(f.FilterID)}`)
2560
+ .sort()
2561
+ .join(',');
2562
+ segments.push(`akf:${filters}`);
2563
+ }
2564
+ if (contextUser.WidgetGuestContext) {
2565
+ const widgetId = contextUser.WidgetGuestContext.WidgetID
2566
+ ? NormalizeUUID(contextUser.WidgetGuestContext.WidgetID)
2567
+ : '';
2568
+ segments.push(`wg:${widgetId}`);
2569
+ }
2570
+ if (contextUser.AnonymousVisitorID) {
2571
+ segments.push(`av:${contextUser.AnonymousVisitorID.trim().toLowerCase()}`);
2572
+ }
2573
+ if (contextUser.IsMagicLinkAnonymous) {
2574
+ const roles = (contextUser.UserRoles ?? [])
2575
+ .map(r => (r.RoleID ? NormalizeUUID(r.RoleID) : ''))
2576
+ .filter(Boolean)
2577
+ .sort()
2578
+ .join(',');
2579
+ segments.push(`mla:1:${roles}`);
2580
+ }
2581
+ return segments.join('|');
2270
2582
  }
2271
2583
  /**
2272
2584
  * What, besides the request itself and the user, decides whether two identical RunViews may
@@ -5389,10 +5701,12 @@ export class ProviderBase {
5389
5701
  await this._metadataReloadInFlight;
5390
5702
  return true;
5391
5703
  }
5704
+ const initialStampsFresh = stampsFresh || this._metadataRefreshStampsFresh;
5705
+ this._metadataRefreshStampsFresh = false;
5392
5706
  this._metadataReloadInFlight = (async () => {
5393
5707
  let effectiveHardRefresh = hardRefresh;
5394
5708
  let tryScoped = scopedFirst;
5395
- let timestampsFresh = stampsFresh;
5709
+ let timestampsFresh = initialStampsFresh;
5396
5710
  do {
5397
5711
  this._metadataReloadQueued = false;
5398
5712
  // The local timestamps must describe the snapshot about to be loaded. On the
@@ -6141,7 +6455,7 @@ export class ProviderBase {
6141
6455
  // the dataset's own rows stay exactly as read (see metadataAssemblyInput).
6142
6456
  const simpleMetadata = ProviderBase.metadataAssemblyInput(d);
6143
6457
  // Post Process Entities because there's some special handling of the sub-objects
6144
- simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews, simpleMetadata.EntityUniqueKeys);
6458
+ simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews, simpleMetadata.EntityUniqueKeys, simpleMetadata.EntityIndexes, simpleMetadata.EntityIndexFields);
6145
6459
  // Post Process the Applications, because we want to handle the sub-objects properly.
6146
6460
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
6147
6461
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
@@ -6172,7 +6486,7 @@ export class ProviderBase {
6172
6486
  * field rows their values and field permissions; organic keys their related entities;
6173
6487
  * applications their entities and settings. The entity array is also sorted.
6174
6488
  */
6175
- static { this._assemblyWrittenItemCodes = new Set(['Entities', 'EntityFields', 'EntityOrganicKeys', 'Applications']); }
6489
+ static { this._assemblyWrittenItemCodes = new Set(['Entities', 'EntityFields', 'EntityOrganicKeys', 'EntityIndexes', 'Applications']); }
6176
6490
  /**
6177
6491
  * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
6178
6492
  * the assembly writes to are shallow copies (a new array of new row objects), the rest are the
@@ -6258,7 +6572,7 @@ export class ProviderBase {
6258
6572
  }
6259
6573
  return map;
6260
6574
  }
6261
- PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys) {
6575
+ PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys, entityIndexes, entityIndexFields) {
6262
6576
  const result = [];
6263
6577
  // Sort entities alphabetically by name to ensure deterministic ordering
6264
6578
  // This prevents non-deterministic output in CodeGen and other metadata consumers
@@ -6289,6 +6603,13 @@ export class ProviderBase {
6289
6603
  ok.EntityOrganicKeyRelatedEntities = okreByOrganicKeyId.get(NormalizeUUID(ok.ID)) || [];
6290
6604
  }
6291
6605
  }
6606
+ // Link index field rows to their parent indexes (skipped when absent to keep payloads compact)
6607
+ if (entityIndexes && entityIndexes.length > 0 && entityIndexFields && entityIndexFields.length > 0) {
6608
+ const fieldsByIndexId = this.groupByNormalizedUUID(entityIndexFields, f => f.EntityIndexID);
6609
+ for (const idx of entityIndexes) {
6610
+ idx.EntityIndexFields = fieldsByIndexId.get(NormalizeUUID(idx.ID)) || [];
6611
+ }
6612
+ }
6292
6613
  const fieldsByEntityId = this.groupByNormalizedUUID(fields, f => f.EntityID);
6293
6614
  const permissionsByEntityId = this.groupByNormalizedUUID(permissions, p => p.EntityID);
6294
6615
  const relationshipsByEntityId = this.groupByNormalizedUUID(relationships, r => r.EntityID);
@@ -6302,6 +6623,9 @@ export class ProviderBase {
6302
6623
  const uniqueKeysByEntityId = uniqueKeys && uniqueKeys.length > 0
6303
6624
  ? this.groupByNormalizedUUID(uniqueKeys, uk => uk.EntityID)
6304
6625
  : new Map();
6626
+ const indexesByEntityId = entityIndexes && entityIndexes.length > 0
6627
+ ? this.groupByNormalizedUUID(entityIndexes, idx => idx.EntityID)
6628
+ : new Map();
6305
6629
  for (const e of sortedEntities) {
6306
6630
  const entityIdKey = NormalizeUUID(e.ID);
6307
6631
  const entityFields = fieldsByEntityId.get(entityIdKey) || [];
@@ -6319,6 +6643,9 @@ export class ProviderBase {
6319
6643
  if (uniqueKeys) {
6320
6644
  e.EntityUniqueKeys = uniqueKeysByEntityId.get(entityIdKey) || [];
6321
6645
  }
6646
+ if (entityIndexes) {
6647
+ e.EntityIndexes = indexesByEntityId.get(entityIdKey) || [];
6648
+ }
6322
6649
  result.push(new EntityInfo(e, this));
6323
6650
  }
6324
6651
  // Check for schema name collision: if both 'MJ' and 'MJCustom' schemas exist,
@@ -6603,7 +6930,7 @@ export class ProviderBase {
6603
6930
  * {@link preValidateAndRefresh}) already caught it; {@link Config} did not.
6604
6931
  */
6605
6932
  async CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval) {
6606
- if (!this.AllowRefresh)
6933
+ if (!this.AllowRefreshCheck)
6607
6934
  return false;
6608
6935
  if (!bypassMinCheckInterval && this._refreshCheckInFlight) {
6609
6936
  LogStatusEx({ message: `[RefreshCheck] Skipped — a check is already in flight; its caller acts on the answer`, verboseOnly: true });
@@ -7326,6 +7653,13 @@ export class ProviderBase {
7326
7653
  */
7327
7654
  UpdateLocalMetadata(res) {
7328
7655
  this._localMetadata = res;
7656
+ this._entityIndexesMetadataGeneration++;
7657
+ this._entityIndexesLoadPromise = null;
7658
+ this._entityIndexesLastFailedAt = 0;
7659
+ this._entityIndexesLastFailedGeneration = -1;
7660
+ if (res?.AllEntities?.some(e => (e?.Indexes?.length ?? 0) > 0) ?? false) {
7661
+ this._entityIndexesLoadedGeneration = this._entityIndexesMetadataGeneration;
7662
+ }
7329
7663
  this.RebuildEntityMaps();
7330
7664
  }
7331
7665
  /**