@memberjunction/redis-provider 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.
@@ -17,7 +17,7 @@ import Redis from 'ioredis';
17
17
  import { EventEmitter } from 'events';
18
18
  import { randomUUID } from 'crypto';
19
19
  import { LogStatus, LogError } from '@memberjunction/core';
20
- import { MJGlobal } from '@memberjunction/global';
20
+ import { MJGlobal, NormalizeUUID } from '@memberjunction/global';
21
21
  /**
22
22
  * Default category used when none is specified in storage operations.
23
23
  * @internal
@@ -40,6 +40,21 @@ const RECONCILED_CATEGORIES = ['RunViewCache', 'RunQueryCache', 'DatasetCache',
40
40
  const DEFAULT_CATEGORY_TTL_SECONDS = { default: 0 };
41
41
  /** Expiry applied when the configuration does not set `defaultTTLSeconds`. @internal */
42
42
  const DEFAULT_TTL_SECONDS = 3600;
43
+ /** Read timeout applied when the configuration does not set `readTimeoutMs`. @internal */
44
+ const DEFAULT_READ_TIMEOUT_MS = 2000;
45
+ /** At most one read-timeout log line per this window; the rest are counted into the next line. @internal */
46
+ const READ_TIMEOUT_LOG_WINDOW_MS = 10000;
47
+ /**
48
+ * A cache read that did not finish within {@link RedisProviderConfig.readTimeoutMs}.
49
+ * Caught inside the provider and answered as a miss; never thrown to callers.
50
+ * @internal
51
+ */
52
+ class RedisReadTimeoutError extends Error {
53
+ constructor(operation, timeoutMs) {
54
+ super(`Redis ${operation} did not finish within ${timeoutMs} ms`);
55
+ this.name = 'RedisReadTimeoutError';
56
+ }
57
+ }
43
58
  /** Keys requested per `SCAN` step. @internal */
44
59
  const SCAN_BATCH = 500;
45
60
  /**
@@ -171,6 +186,107 @@ export class KeyLockLostError extends Error {
171
186
  this.name = 'KeyLockLostError';
172
187
  }
173
188
  }
189
+ /**
190
+ * Ensures a cluster-wide epoch UUID exists, returning the stored or newly created UUID.
191
+ * @internal
192
+ */
193
+ const ENSURE_CLUSTER_EPOCH_SCRIPT = `
194
+ local v = redis.call('GET', KEYS[1])
195
+ if not v then
196
+ redis.call('SET', KEYS[1], ARGV[1])
197
+ return ARGV[1]
198
+ end
199
+ return v
200
+ `;
201
+ /**
202
+ * Atomically increments sequence key and appends an entry to a Redis stream with sequence ID.
203
+ * @internal
204
+ */
205
+ const APPEND_SEQUENCED_STREAM_SCRIPT = `
206
+ local seq = redis.call('INCR', KEYS[1])
207
+ redis.call('XADD', KEYS[2], 'MAXLEN', '~', ARGV[1], tostring(seq) .. '-0', 'seq', tostring(seq), 'payload', ARGV[2])
208
+ return seq
209
+ `;
210
+ /**
211
+ * Reads a RunView slot, inspecting whether it is stored as string or hash and returning its content.
212
+ * @internal
213
+ */
214
+ const GET_RUNVIEW_SLOT_SCRIPT = `
215
+ local t = redis.call('TYPE', KEYS[1])
216
+ local typeStr = type(t) == 'table' and t.ok or t
217
+ if typeStr == 'string' then
218
+ local val = redis.call('GET', KEYS[1])
219
+ return { 's', val }
220
+ elseif typeStr == 'hash' then
221
+ local val = redis.call('HGETALL', KEYS[1])
222
+ return { 'h', val }
223
+ else
224
+ return nil
225
+ end
226
+ `;
227
+ /**
228
+ * Atomically applies row delta (upserts and deletes) to a RunView HASH cache slot.
229
+ * @internal
230
+ */
231
+ const APPLY_RUNVIEW_ROW_DELTA_SCRIPT = `
232
+ local fullKey = KEYS[1]
233
+ if redis.call('HEXISTS', fullKey, '__meta__') == 0 then
234
+ return 0
235
+ end
236
+ local metaRaw = redis.call('HGET', fullKey, '__meta__')
237
+ if not metaRaw then
238
+ return 0
239
+ end
240
+ local meta = cjson.decode(metaRaw)
241
+ local p = cjson.decode(ARGV[1])
242
+ local ttl = tonumber(ARGV[2])
243
+
244
+ if p.metaUpdates then
245
+ if p.metaUpdates.maxUpdatedAt then meta.maxUpdatedAt = p.metaUpdates.maxUpdatedAt end
246
+ if p.metaUpdates.lastVerifiedAt then meta.lastVerifiedAt = p.metaUpdates.lastVerifiedAt end
247
+ if p.metaUpdates.totalRowCount then meta.totalRowCount = p.metaUpdates.totalRowCount end
248
+ if p.metaUpdates.schemaHash then meta.schemaHash = p.metaUpdates.schemaHash end
249
+ end
250
+
251
+ if not meta.rowOrder then
252
+ meta.rowOrder = {}
253
+ end
254
+
255
+ if p.delKeys and #p.delKeys > 0 then
256
+ for i = 1, #p.delKeys do
257
+ local k = p.delKeys[i]
258
+ redis.call('HDEL', fullKey, k)
259
+ local newOrder = {}
260
+ for j = 1, #meta.rowOrder do
261
+ if meta.rowOrder[j] ~= k then
262
+ newOrder[#newOrder + 1] = meta.rowOrder[j]
263
+ end
264
+ end
265
+ meta.rowOrder = newOrder
266
+ end
267
+ end
268
+
269
+ if p.upserts and #p.upserts > 0 then
270
+ for i = 1, #p.upserts do
271
+ local item = p.upserts[i]
272
+ local k = item.k
273
+ local v = item.v
274
+ local exists = redis.call('HEXISTS', fullKey, k)
275
+ if exists == 0 then
276
+ meta.rowOrder[#meta.rowOrder + 1] = k
277
+ end
278
+ redis.call('HSET', fullKey, k, v)
279
+ end
280
+ end
281
+
282
+ redis.call('HSET', fullKey, '__meta__', cjson.encode(meta))
283
+
284
+ if ttl and ttl > 0 then
285
+ redis.call('EXPIRE', fullKey, ttl)
286
+ end
287
+
288
+ return 1
289
+ `;
174
290
  /**
175
291
  * Escapes the glob metacharacters Redis `MATCH` understands, so a literal prefix or category can
176
292
  * be embedded in a pattern.
@@ -317,6 +433,9 @@ export class RedisLocalStorageProvider {
317
433
  this._pendingChannelSubscribes = new Map();
318
434
  /** The subscriber start-up in flight or completed, shared by every caller of {@link StartListening}. */
319
435
  this._listening = null;
436
+ /** When the last read-timeout line was logged, and how many timeouts since then went unlogged. */
437
+ this._readTimeoutLoggedAt = 0;
438
+ this._readTimeoutsSuppressed = 0;
320
439
  this._config = config;
321
440
  this._keyPrefix = config.keyPrefix ?? 'mj';
322
441
  this._defaultTTLSeconds = config.defaultTTLSeconds ?? DEFAULT_TTL_SECONDS;
@@ -327,6 +446,7 @@ export class RedisLocalStorageProvider {
327
446
  this._categoryTTLSeconds = { ...DEFAULT_CATEGORY_TTL_SECONDS, ...(config.categoryTTLSeconds ?? {}) };
328
447
  this._enableLogging = config.enableLogging ?? true;
329
448
  this._maxRetryDelayMs = config.maxRetryDelayMs ?? 30000;
449
+ this._readTimeoutMs = config.readTimeoutMs ?? DEFAULT_READ_TIMEOUT_MS;
330
450
  this._enablePubSub = config.enablePubSub ?? false;
331
451
  this._pubSubChannel = `${this._keyPrefix}:__pubsub__`;
332
452
  const maxRetries = config.maxRetries; // undefined = retry forever, with a capped delay
@@ -335,6 +455,7 @@ export class RedisLocalStorageProvider {
335
455
  maxRetriesPerRequest: null,
336
456
  retryStrategy: (times) => this.retryStrategy(times, maxRetries),
337
457
  lazyConnect: false,
458
+ ...config.options,
338
459
  });
339
460
  }
340
461
  else {
@@ -460,6 +581,48 @@ export class RedisLocalStorageProvider {
460
581
  get shouldFailFast() {
461
582
  return this._hasEverConnected && !this._connected;
462
583
  }
584
+ /**
585
+ * Races a read command against {@link RedisProviderConfig.readTimeoutMs}. On timeout it rejects
586
+ * with {@link RedisReadTimeoutError}; the command itself is left to finish or fail on its own.
587
+ * @internal
588
+ */
589
+ async withReadTimeout(operation, command) {
590
+ const timeoutMs = this._readTimeoutMs;
591
+ if (!(timeoutMs > 0)) {
592
+ return command;
593
+ }
594
+ let timer;
595
+ const timeout = new Promise((_resolve, reject) => {
596
+ timer = setTimeout(() => reject(new RedisReadTimeoutError(operation, timeoutMs)), timeoutMs);
597
+ });
598
+ // A command that fails after losing the race has nobody awaiting it.
599
+ command.catch(() => undefined);
600
+ try {
601
+ return await Promise.race([command, timeout]);
602
+ }
603
+ finally {
604
+ clearTimeout(timer);
605
+ }
606
+ }
607
+ /**
608
+ * Logs a read timeout at most once per {@link READ_TIMEOUT_LOG_WINDOW_MS}, counting the ones in
609
+ * between, so a saturated Redis does not also flood the log.
610
+ * @internal
611
+ */
612
+ noteReadTimeout(err) {
613
+ const now = Date.now();
614
+ if (now - this._readTimeoutLoggedAt < READ_TIMEOUT_LOG_WINDOW_MS) {
615
+ this._readTimeoutsSuppressed++;
616
+ return;
617
+ }
618
+ const suppressed = this._readTimeoutsSuppressed;
619
+ this._readTimeoutLoggedAt = now;
620
+ this._readTimeoutsSuppressed = 0;
621
+ if (this._enableLogging) {
622
+ const more = suppressed > 0 ? ` (${suppressed} more since the last report)` : '';
623
+ LogError(`${err.message}; answered as a cache miss${more}. Redis is connected but slow to answer.`);
624
+ }
625
+ }
463
626
  /**
464
627
  * Records the highest epoch this process has observed, from either direction — a mutation it
465
628
  * published, or an event it received. Monotonic: a late-arriving lower value is ignored.
@@ -673,9 +836,15 @@ export class RedisLocalStorageProvider {
673
836
  if (this.shouldFailFast) {
674
837
  return null; // a miss: the caller refetches from the source of truth
675
838
  }
839
+ const cat = category ?? DEFAULT_CATEGORY;
840
+ if (this._config.useHashForRunViewSlots === true &&
841
+ cat === 'RunViewCache' &&
842
+ typeof this._client.hset === 'function') {
843
+ return this.getRunViewHashItem(key);
844
+ }
676
845
  try {
677
- const redisKey = this.buildKey(key, category ?? DEFAULT_CATEGORY);
678
- const raw = await this._client.get(redisKey);
846
+ const redisKey = this.buildKey(key, cat);
847
+ const raw = await this.withReadTimeout('GET', this._client.get(redisKey));
679
848
  if (raw === null)
680
849
  return null;
681
850
  try {
@@ -690,6 +859,10 @@ export class RedisLocalStorageProvider {
690
859
  }
691
860
  }
692
861
  catch (err) {
862
+ if (err instanceof RedisReadTimeoutError) {
863
+ this.noteReadTimeout(err);
864
+ return null;
865
+ }
693
866
  if (this._enableLogging) {
694
867
  LogError(`Redis GetItem failed for key "${key}": ${err.message}`);
695
868
  }
@@ -725,7 +898,7 @@ export class RedisLocalStorageProvider {
725
898
  const redisKeys = uniqueKeys.map(k => this.buildKey(k, cat));
726
899
  // MGET returns an array of strings/nulls in the same order as the inputs.
727
900
  // ioredis variadic call: pass keys as separate args.
728
- const raws = await this._client.mget(...redisKeys);
901
+ const raws = await this.withReadTimeout('MGET', this._client.mget(...redisKeys));
729
902
  for (let i = 0; i < uniqueKeys.length; i++) {
730
903
  const raw = raws[i];
731
904
  if (raw === null) {
@@ -745,7 +918,10 @@ export class RedisLocalStorageProvider {
745
918
  return out;
746
919
  }
747
920
  catch (err) {
748
- if (this._enableLogging) {
921
+ if (err instanceof RedisReadTimeoutError) {
922
+ this.noteReadTimeout(err);
923
+ }
924
+ else if (this._enableLogging) {
749
925
  LogError(`Redis GetItems failed for ${keys.length} keys: ${err.message}`);
750
926
  }
751
927
  // On error, return null entries for every requested key — callers see them as cache misses.
@@ -791,8 +967,15 @@ export class RedisLocalStorageProvider {
791
967
  this.noteMutationWhileDisconnected();
792
968
  return;
793
969
  }
970
+ const cat = category ?? DEFAULT_CATEGORY;
971
+ if (this._config.useHashForRunViewSlots === true &&
972
+ cat === 'RunViewCache' &&
973
+ typeof this._client.hset === 'function' &&
974
+ this.canStoreAsRunViewHash(value, options)) {
975
+ await this.setRunViewHashItem(key, value, options);
976
+ return;
977
+ }
794
978
  try {
795
- const cat = category ?? DEFAULT_CATEGORY;
796
979
  const redisKey = this.buildKey(key, cat);
797
980
  // Serialize once. We need the string for both the Redis SET and (optionally)
798
981
  // the pub/sub publishChange payload, so build it up front.
@@ -950,10 +1133,14 @@ export class RedisLocalStorageProvider {
950
1133
  try {
951
1134
  const cat = category || DEFAULT_CATEGORY;
952
1135
  const redisPrefix = this.buildKey('', cat);
953
- const redisKeys = await this.scanKeys(`${escapeGlob(redisPrefix)}*`);
1136
+ const redisKeys = await this.withReadTimeout('SCAN', this.scanKeys(`${escapeGlob(redisPrefix)}*`));
954
1137
  return redisKeys.map(k => k.substring(redisPrefix.length));
955
1138
  }
956
1139
  catch (err) {
1140
+ if (err instanceof RedisReadTimeoutError) {
1141
+ this.noteReadTimeout(err);
1142
+ return [];
1143
+ }
957
1144
  if (this._enableLogging) {
958
1145
  LogError(`Redis GetCategoryKeys failed for "${category}": ${err.message}`);
959
1146
  }
@@ -981,13 +1168,29 @@ export class RedisLocalStorageProvider {
981
1168
  this.noteMutationWhileDisconnected();
982
1169
  return [];
983
1170
  }
1171
+ const cat = category || DEFAULT_CATEGORY;
1172
+ let command;
984
1173
  try {
985
- const cat = category || DEFAULT_CATEGORY;
986
1174
  const groupSetKey = this.buildGroupSetKey(cat, group);
987
- const alive = await this._client.eval(PRUNE_GROUP_SCRIPT, 1, groupSetKey, this.buildKey('', cat));
1175
+ command = this._client.eval(PRUNE_GROUP_SCRIPT, 1, groupSetKey, this.buildKey('', cat));
1176
+ const alive = await this.withReadTimeout('index group read', command);
988
1177
  return Array.isArray(alive) ? alive.map(m => String(m)) : [];
989
1178
  }
990
1179
  catch (err) {
1180
+ if (err instanceof RedisReadTimeoutError) {
1181
+ // Only the save/delete path asks this, and peers do not clean up their own slots, so
1182
+ // answering "none" alone would leave peer slots stale until the TTL. The caller is
1183
+ // answered now; the slots are removed once Redis answers, and reload from the database.
1184
+ this.noteReadTimeout(err);
1185
+ command?.then((alive) => {
1186
+ if (Array.isArray(alive)) {
1187
+ for (const key of alive) {
1188
+ void this.Remove(String(key), cat);
1189
+ }
1190
+ }
1191
+ }, () => undefined);
1192
+ return [];
1193
+ }
991
1194
  if (this._enableLogging) {
992
1195
  LogError(`Redis GetIndexGroupKeys failed for "${category}"/"${group}": ${err.message}`);
993
1196
  }
@@ -1323,6 +1526,468 @@ export class RedisLocalStorageProvider {
1323
1526
  return false;
1324
1527
  }
1325
1528
  }
1529
+ /**
1530
+ * Gets the key prefix used for this Redis keyspace (without trailing colon).
1531
+ */
1532
+ get KeyPrefix() {
1533
+ return this._keyPrefix;
1534
+ }
1535
+ /**
1536
+ * Exposes the underlying Redis client for direct command execution.
1537
+ */
1538
+ get RawClient() {
1539
+ return this._client;
1540
+ }
1541
+ /**
1542
+ * Ensures a cluster-wide epoch UUID exists in Redis across all replicas sharing this keyspace.
1543
+ */
1544
+ async EnsureClusterEpochId(epochKeySuffix) {
1545
+ const epochKey = `${this._keyPrefix}:${epochKeySuffix ?? '__invalidation_epoch__'}`;
1546
+ if (this.shouldFailFast) {
1547
+ return randomUUID();
1548
+ }
1549
+ const newUuid = randomUUID();
1550
+ try {
1551
+ const res = await this._client.eval(ENSURE_CLUSTER_EPOCH_SCRIPT, 1, epochKey, newUuid);
1552
+ if (typeof res === 'string' && res.length > 0) {
1553
+ return res;
1554
+ }
1555
+ }
1556
+ catch {
1557
+ // Graceful fallback to SET NX + GET if eval fails or is not supported
1558
+ try {
1559
+ await this._client.set(epochKey, newUuid, 'NX');
1560
+ const existing = await this._client.get(epochKey);
1561
+ if (existing)
1562
+ return existing;
1563
+ }
1564
+ catch {
1565
+ // ignore
1566
+ }
1567
+ }
1568
+ return newUuid;
1569
+ }
1570
+ /**
1571
+ * Atomically increments sequence key and appends an entry to a Redis stream with sequence ID.
1572
+ */
1573
+ async AppendSequencedStreamEntry(seqKeySuffix, streamKeySuffix, maxLen, payloadJson) {
1574
+ const seqKey = `${this._keyPrefix}:${seqKeySuffix}`;
1575
+ const streamKey = `${this._keyPrefix}:${streamKeySuffix}`;
1576
+ try {
1577
+ const res = await this._client.eval(APPEND_SEQUENCED_STREAM_SCRIPT, 2, seqKey, streamKey, String(maxLen), payloadJson);
1578
+ if (typeof res === 'number') {
1579
+ return res;
1580
+ }
1581
+ if (typeof res === 'string') {
1582
+ const parsed = parseInt(res, 10);
1583
+ if (!isNaN(parsed))
1584
+ return parsed;
1585
+ }
1586
+ }
1587
+ catch {
1588
+ // Fallback if eval fails
1589
+ }
1590
+ const seq = await this._client.incr(seqKey);
1591
+ const clientWithStreams = this._client;
1592
+ if (typeof clientWithStreams.xadd === 'function') {
1593
+ await clientWithStreams.xadd(streamKey, 'MAXLEN', '~', maxLen, `${seq}-0`, 'seq', String(seq), 'payload', payloadJson);
1594
+ }
1595
+ return Number(seq);
1596
+ }
1597
+ /**
1598
+ * Reads sequenced stream entries since a given sequence ID.
1599
+ */
1600
+ async ReadSequencedStreamSince(streamKeySuffix, sinceSequence, maxCount) {
1601
+ const streamKey = `${this._keyPrefix}:${streamKeySuffix}`;
1602
+ const count = maxCount ?? 5000;
1603
+ const clientWithStreams = this._client;
1604
+ if (typeof clientWithStreams.xrange !== 'function') {
1605
+ return { CurrentSequence: sinceSequence, Entries: [] };
1606
+ }
1607
+ try {
1608
+ let currentSequence = sinceSequence;
1609
+ if (typeof clientWithStreams.xrevrange === 'function') {
1610
+ const tail = await clientWithStreams.xrevrange(streamKey, '+', '-', 'COUNT', 1);
1611
+ if (Array.isArray(tail) && tail.length > 0) {
1612
+ const tailTuple = tail[0];
1613
+ const tailSeq = this.parseStreamEntrySeq(tailTuple);
1614
+ if (tailSeq !== null) {
1615
+ currentSequence = Math.max(currentSequence, tailSeq);
1616
+ }
1617
+ }
1618
+ }
1619
+ const startId = `${sinceSequence + 1}-0`;
1620
+ const rawEntries = await clientWithStreams.xrange(streamKey, startId, '+', 'COUNT', count);
1621
+ const entries = [];
1622
+ if (Array.isArray(rawEntries)) {
1623
+ for (const item of rawEntries) {
1624
+ const tuple = item;
1625
+ const seq = this.parseStreamEntrySeq(tuple);
1626
+ const payload = this.parseStreamEntryPayload(tuple);
1627
+ if (seq !== null) {
1628
+ entries.push({ Sequence: seq, PayloadJson: payload });
1629
+ currentSequence = Math.max(currentSequence, seq);
1630
+ }
1631
+ }
1632
+ }
1633
+ return { CurrentSequence: currentSequence, Entries: entries };
1634
+ }
1635
+ catch (err) {
1636
+ if (this._enableLogging) {
1637
+ LogError(`Redis ReadSequencedStreamSince failed for stream "${streamKey}": ${err.message}`);
1638
+ }
1639
+ return { CurrentSequence: sinceSequence, Entries: [] };
1640
+ }
1641
+ }
1642
+ parseStreamEntrySeq(tuple) {
1643
+ if (!tuple)
1644
+ return null;
1645
+ const [id, rawFields] = tuple;
1646
+ if (Array.isArray(rawFields)) {
1647
+ for (let i = 0; i < rawFields.length; i += 2) {
1648
+ if (rawFields[i] === 'seq') {
1649
+ const parsed = parseInt(String(rawFields[i + 1]), 10);
1650
+ if (!isNaN(parsed))
1651
+ return parsed;
1652
+ }
1653
+ }
1654
+ }
1655
+ else if (typeof rawFields === 'object' && rawFields !== null) {
1656
+ const record = rawFields;
1657
+ if (record.seq !== undefined) {
1658
+ const parsed = parseInt(String(record.seq), 10);
1659
+ if (!isNaN(parsed))
1660
+ return parsed;
1661
+ }
1662
+ }
1663
+ if (typeof id === 'string') {
1664
+ const dashIdx = id.indexOf('-');
1665
+ const idPrefix = dashIdx >= 0 ? id.substring(0, dashIdx) : id;
1666
+ const parsed = parseInt(idPrefix, 10);
1667
+ if (!isNaN(parsed))
1668
+ return parsed;
1669
+ }
1670
+ return null;
1671
+ }
1672
+ parseStreamEntryPayload(tuple) {
1673
+ if (!tuple)
1674
+ return '';
1675
+ const [, rawFields] = tuple;
1676
+ if (Array.isArray(rawFields)) {
1677
+ for (let i = 0; i < rawFields.length; i += 2) {
1678
+ if (rawFields[i] === 'payload') {
1679
+ return String(rawFields[i + 1]);
1680
+ }
1681
+ }
1682
+ }
1683
+ else if (typeof rawFields === 'object' && rawFields !== null) {
1684
+ const record = rawFields;
1685
+ if (record.payload !== undefined) {
1686
+ return String(record.payload);
1687
+ }
1688
+ }
1689
+ return '';
1690
+ }
1691
+ /**
1692
+ * Applies a row delta (upserts and deletes) to a RunView HASH slot atomically in Redis.
1693
+ */
1694
+ async ApplyRunViewRowDelta(fingerprint, deltaPayloadJson, _updatedSlotValue, options) {
1695
+ if (!this._config.useHashForRunViewSlots || typeof this._client.hset !== 'function') {
1696
+ return false;
1697
+ }
1698
+ if (this.shouldFailFast) {
1699
+ return false;
1700
+ }
1701
+ let delta;
1702
+ try {
1703
+ delta = JSON.parse(deltaPayloadJson);
1704
+ }
1705
+ catch {
1706
+ return false;
1707
+ }
1708
+ const pkFields = delta.primaryKeyFields;
1709
+ if (!Array.isArray(pkFields) || pkFields.length === 0) {
1710
+ return false;
1711
+ }
1712
+ const delKeys = [];
1713
+ if (Array.isArray(delta.deletedPrimaryKeys)) {
1714
+ for (const pkRec of delta.deletedPrimaryKeys) {
1715
+ const comp = pkFields.map(f => NormalizeUUID(String(pkRec[f]))).join('\u001f');
1716
+ delKeys.push(`r:${comp}`);
1717
+ }
1718
+ }
1719
+ const upserts = [];
1720
+ if (Array.isArray(delta.upsertedRows)) {
1721
+ for (const row of delta.upsertedRows) {
1722
+ const comp = pkFields.map(f => NormalizeUUID(String(row[f]))).join('\u001f');
1723
+ upserts.push({ k: `r:${comp}`, v: JSON.stringify(row) });
1724
+ }
1725
+ }
1726
+ const metaUpdates = {
1727
+ maxUpdatedAt: delta.maxUpdatedAt,
1728
+ lastVerifiedAt: Date.now(),
1729
+ totalRowCount: delta.totalRowCount,
1730
+ };
1731
+ if (delta.schemaHash !== undefined) {
1732
+ metaUpdates.schemaHash = delta.schemaHash;
1733
+ }
1734
+ const { ttlSeconds, group } = this.resolveWriteOptions(options, 'RunViewCache');
1735
+ const luaPayload = JSON.stringify({
1736
+ delKeys,
1737
+ upserts,
1738
+ metaUpdates,
1739
+ });
1740
+ const cat = 'RunViewCache';
1741
+ const redisKey = this.buildKey(fingerprint, cat);
1742
+ try {
1743
+ const res = await this._client.eval(APPLY_RUNVIEW_ROW_DELTA_SCRIPT, 1, redisKey, luaPayload, String(ttlSeconds));
1744
+ if (Number(res) === 1) {
1745
+ if (group) {
1746
+ await this._client.eval(ADD_TO_GROUP_SCRIPT, 1, this.buildGroupSetKey(cat, group), fingerprint, ttlSeconds);
1747
+ }
1748
+ this.publishChange(fingerprint, cat, 'row_delta', deltaPayloadJson);
1749
+ return true;
1750
+ }
1751
+ return false;
1752
+ }
1753
+ catch (err) {
1754
+ if (this._enableLogging) {
1755
+ LogError(`Redis ApplyRunViewRowDelta failed for "${fingerprint}": ${err.message}`);
1756
+ }
1757
+ return false;
1758
+ }
1759
+ }
1760
+ canStoreAsRunViewHash(value, options) {
1761
+ if (typeof value !== 'object' || value === null) {
1762
+ return false;
1763
+ }
1764
+ const envelope = value;
1765
+ if (!Array.isArray(envelope.results)) {
1766
+ return false;
1767
+ }
1768
+ const results = envelope.results;
1769
+ const writeOpts = typeof options === 'object' && options !== null ? options : undefined;
1770
+ let pkFields = writeOpts?.PrimaryKeyFields && writeOpts.PrimaryKeyFields.length > 0 ? writeOpts.PrimaryKeyFields : undefined;
1771
+ if (!pkFields) {
1772
+ if (results.length > 0) {
1773
+ const allHaveId = results.every(r => typeof r === 'object' && r !== null && r['ID'] !== undefined && r['ID'] !== null);
1774
+ if (allHaveId) {
1775
+ pkFields = ['ID'];
1776
+ }
1777
+ }
1778
+ }
1779
+ if (!pkFields || pkFields.length === 0) {
1780
+ return false;
1781
+ }
1782
+ return results.every(row => {
1783
+ if (typeof row !== 'object' || row === null)
1784
+ return false;
1785
+ const rec = row;
1786
+ return pkFields.every(f => rec[f] !== undefined && rec[f] !== null);
1787
+ });
1788
+ }
1789
+ async setRunViewHashItem(key, value, options) {
1790
+ try {
1791
+ const cat = 'RunViewCache';
1792
+ const redisKey = this.buildKey(key, cat);
1793
+ const envelope = value;
1794
+ const results = envelope.results;
1795
+ const writeOpts = typeof options === 'object' && options !== null ? options : undefined;
1796
+ const pkFields = writeOpts?.PrimaryKeyFields && writeOpts.PrimaryKeyFields.length > 0 ? writeOpts.PrimaryKeyFields : ['ID'];
1797
+ const rowOrder = [];
1798
+ const rowFieldPairs = [];
1799
+ for (const row of results) {
1800
+ const compositePk = pkFields.map(f => NormalizeUUID(String(row[f]))).join('\u001f');
1801
+ const rowKey = `r:${compositePk}`;
1802
+ rowOrder.push(rowKey);
1803
+ rowFieldPairs.push(rowKey, JSON.stringify(row));
1804
+ }
1805
+ const meta = {
1806
+ v: 1,
1807
+ primaryKeyFields: pkFields,
1808
+ rowOrder,
1809
+ maxUpdatedAt: envelope.maxUpdatedAt ?? '',
1810
+ };
1811
+ if (envelope.cachedAt !== undefined)
1812
+ meta.cachedAt = envelope.cachedAt;
1813
+ if (envelope.lastVerifiedAt !== undefined)
1814
+ meta.lastVerifiedAt = envelope.lastVerifiedAt;
1815
+ if (envelope.totalRowCount !== undefined)
1816
+ meta.totalRowCount = envelope.totalRowCount;
1817
+ if (envelope.schemaHash !== undefined)
1818
+ meta.schemaHash = envelope.schemaHash;
1819
+ if (envelope.schemaStamp !== undefined)
1820
+ meta.schemaStamp = envelope.schemaStamp;
1821
+ if (envelope.providerInternalScaffolding !== undefined)
1822
+ meta.providerInternalScaffolding = envelope.providerInternalScaffolding;
1823
+ if (envelope.aggregates !== undefined)
1824
+ meta.aggregates = envelope.aggregates;
1825
+ else if (envelope.aggregateResults !== undefined)
1826
+ meta.aggregates = envelope.aggregateResults;
1827
+ const metaJson = JSON.stringify(meta);
1828
+ const { ttlSeconds, group } = this.resolveWriteOptions(options, cat);
1829
+ const pipeline = this._client.pipeline();
1830
+ const pipeWithHash = pipeline;
1831
+ pipeWithHash.del(redisKey);
1832
+ const CHUNK_SIZE = 1000 * 2;
1833
+ if (rowFieldPairs.length === 0) {
1834
+ pipeWithHash.hset(redisKey, '__meta__', metaJson);
1835
+ }
1836
+ else {
1837
+ const firstChunk = rowFieldPairs.slice(0, CHUNK_SIZE);
1838
+ pipeWithHash.hset(redisKey, '__meta__', metaJson, ...firstChunk);
1839
+ for (let i = CHUNK_SIZE; i < rowFieldPairs.length; i += CHUNK_SIZE) {
1840
+ const nextChunk = rowFieldPairs.slice(i, i + CHUNK_SIZE);
1841
+ pipeWithHash.hset(redisKey, ...nextChunk);
1842
+ }
1843
+ }
1844
+ if (ttlSeconds > 0) {
1845
+ pipeWithHash.expire(redisKey, ttlSeconds);
1846
+ }
1847
+ if (group) {
1848
+ pipeWithHash.eval(ADD_TO_GROUP_SCRIPT, 1, this.buildGroupSetKey(cat, group), key, ttlSeconds);
1849
+ }
1850
+ this.logPipelineErrors(await pipeline.exec(), `SetItem (Hash) "${key}"`);
1851
+ const rowDeltaPayload = writeOpts?.pubSubAction === 'row_delta' && typeof writeOpts.pubSubData === 'string' ? writeOpts.pubSubData : null;
1852
+ const pubAction = rowDeltaPayload !== null ? 'row_delta' : 'set';
1853
+ const pubPayload = rowDeltaPayload ?? JSON.stringify(value);
1854
+ this.publishChange(key, cat, pubAction, pubPayload);
1855
+ }
1856
+ catch (err) {
1857
+ if (this._enableLogging) {
1858
+ LogError(`Redis SetItem (Hash) failed for key "${key}": ${err.message}`);
1859
+ }
1860
+ }
1861
+ }
1862
+ async getRunViewHashItem(key) {
1863
+ const cat = 'RunViewCache';
1864
+ const redisKey = this.buildKey(key, cat);
1865
+ try {
1866
+ const raw = await this.withReadTimeout('GetItem(Hash)', this._client.eval(GET_RUNVIEW_SLOT_SCRIPT, 1, redisKey));
1867
+ if (raw === null || raw === undefined) {
1868
+ return null;
1869
+ }
1870
+ if (Array.isArray(raw) && raw.length >= 2) {
1871
+ const typeFlag = raw[0];
1872
+ const content = raw[1];
1873
+ if (typeFlag === 's' && typeof content === 'string') {
1874
+ try {
1875
+ return JSON.parse(content);
1876
+ }
1877
+ catch {
1878
+ return null;
1879
+ }
1880
+ }
1881
+ if (typeFlag === 'h') {
1882
+ return this.reconstructRunViewFromHash(content);
1883
+ }
1884
+ }
1885
+ const strVal = await this._client.get(redisKey);
1886
+ if (strVal !== null) {
1887
+ return JSON.parse(strVal);
1888
+ }
1889
+ return null;
1890
+ }
1891
+ catch (err) {
1892
+ if (err instanceof RedisReadTimeoutError) {
1893
+ this.noteReadTimeout(err);
1894
+ return null;
1895
+ }
1896
+ try {
1897
+ const strVal = await this._client.get(redisKey);
1898
+ if (strVal !== null) {
1899
+ return JSON.parse(strVal);
1900
+ }
1901
+ const clientWithHash = this._client;
1902
+ if (typeof clientWithHash.hgetall === 'function') {
1903
+ const hashData = await clientWithHash.hgetall(redisKey);
1904
+ if (hashData) {
1905
+ return this.reconstructRunViewFromHash(hashData);
1906
+ }
1907
+ }
1908
+ }
1909
+ catch {
1910
+ // ignore fallback error
1911
+ }
1912
+ if (this._enableLogging) {
1913
+ LogError(`Redis GetItem (Hash) failed for key "${key}": ${err.message}`);
1914
+ }
1915
+ return null;
1916
+ }
1917
+ }
1918
+ reconstructRunViewFromHash(hashData) {
1919
+ if (!hashData)
1920
+ return null;
1921
+ const hashRecord = new Map();
1922
+ if (Array.isArray(hashData)) {
1923
+ for (let i = 0; i < hashData.length; i += 2) {
1924
+ hashRecord.set(String(hashData[i]), String(hashData[i + 1]));
1925
+ }
1926
+ }
1927
+ else if (typeof hashData === 'object') {
1928
+ for (const [k, v] of Object.entries(hashData)) {
1929
+ hashRecord.set(k, String(v));
1930
+ }
1931
+ }
1932
+ const metaStr = hashRecord.get('__meta__');
1933
+ if (!metaStr) {
1934
+ return null;
1935
+ }
1936
+ let meta;
1937
+ try {
1938
+ meta = JSON.parse(metaStr);
1939
+ }
1940
+ catch {
1941
+ return null;
1942
+ }
1943
+ const results = [];
1944
+ const visited = new Set();
1945
+ if (Array.isArray(meta.rowOrder)) {
1946
+ for (const rKey of meta.rowOrder) {
1947
+ visited.add(rKey);
1948
+ const rowStr = hashRecord.get(rKey);
1949
+ if (rowStr !== undefined) {
1950
+ try {
1951
+ results.push(JSON.parse(rowStr));
1952
+ }
1953
+ catch {
1954
+ // ignore corrupt row
1955
+ }
1956
+ }
1957
+ }
1958
+ }
1959
+ for (const [k, v] of hashRecord.entries()) {
1960
+ if (k.startsWith('r:') && !visited.has(k)) {
1961
+ try {
1962
+ results.push(JSON.parse(v));
1963
+ }
1964
+ catch {
1965
+ // ignore corrupt row
1966
+ }
1967
+ }
1968
+ }
1969
+ const reconstructed = {
1970
+ results,
1971
+ maxUpdatedAt: meta.maxUpdatedAt ?? '',
1972
+ };
1973
+ if (meta.totalRowCount !== undefined)
1974
+ reconstructed.totalRowCount = meta.totalRowCount;
1975
+ if (meta.schemaHash !== undefined)
1976
+ reconstructed.schemaHash = meta.schemaHash;
1977
+ if (meta.schemaStamp !== undefined)
1978
+ reconstructed.schemaStamp = meta.schemaStamp;
1979
+ if (meta.providerInternalScaffolding !== undefined)
1980
+ reconstructed.providerInternalScaffolding = meta.providerInternalScaffolding;
1981
+ if (meta.cachedAt !== undefined)
1982
+ reconstructed.cachedAt = meta.cachedAt;
1983
+ if (meta.lastVerifiedAt !== undefined)
1984
+ reconstructed.lastVerifiedAt = meta.lastVerifiedAt;
1985
+ if (meta.aggregates !== undefined)
1986
+ reconstructed.aggregateResults = meta.aggregates;
1987
+ else if (meta.aggregateResults !== undefined)
1988
+ reconstructed.aggregateResults = meta.aggregateResults;
1989
+ return reconstructed;
1990
+ }
1326
1991
  // ========================================================================
1327
1992
  // PUB/SUB — Cross-Server Cache Invalidation
1328
1993
  // ========================================================================
@@ -1417,6 +2082,7 @@ export class RedisLocalStorageProvider {
1417
2082
  maxRetriesPerRequest: null,
1418
2083
  retryStrategy: (times) => this.retryStrategy(times, maxRetries),
1419
2084
  lazyConnect: false,
2085
+ ...this._config.options,
1420
2086
  });
1421
2087
  }
1422
2088
  return new Redis({