@memberjunction/redis-provider 6.3.0-edge.0 → 6.3.0-edge.2

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
@@ -186,6 +186,107 @@ export class KeyLockLostError extends Error {
186
186
  this.name = 'KeyLockLostError';
187
187
  }
188
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
+ `;
189
290
  /**
190
291
  * Escapes the glob metacharacters Redis `MATCH` understands, so a literal prefix or category can
191
292
  * be embedded in a pattern.
@@ -735,8 +836,14 @@ export class RedisLocalStorageProvider {
735
836
  if (this.shouldFailFast) {
736
837
  return null; // a miss: the caller refetches from the source of truth
737
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
+ }
738
845
  try {
739
- const redisKey = this.buildKey(key, category ?? DEFAULT_CATEGORY);
846
+ const redisKey = this.buildKey(key, cat);
740
847
  const raw = await this.withReadTimeout('GET', this._client.get(redisKey));
741
848
  if (raw === null)
742
849
  return null;
@@ -860,8 +967,15 @@ export class RedisLocalStorageProvider {
860
967
  this.noteMutationWhileDisconnected();
861
968
  return;
862
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
+ }
863
978
  try {
864
- const cat = category ?? DEFAULT_CATEGORY;
865
979
  const redisKey = this.buildKey(key, cat);
866
980
  // Serialize once. We need the string for both the Redis SET and (optionally)
867
981
  // the pub/sub publishChange payload, so build it up front.
@@ -1412,6 +1526,468 @@ export class RedisLocalStorageProvider {
1412
1526
  return false;
1413
1527
  }
1414
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
+ }
1415
1991
  // ========================================================================
1416
1992
  // PUB/SUB — Cross-Server Cache Invalidation
1417
1993
  // ========================================================================