@memberjunction/redis-provider 6.2.0-edge.3 → 6.2.0-edge.5
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/README.md +62 -13
- package/dist/RedisLocalStorageProvider.d.ts +288 -29
- package/dist/RedisLocalStorageProvider.d.ts.map +1 -1
- package/dist/RedisLocalStorageProvider.js +652 -84
- package/dist/RedisLocalStorageProvider.js.map +1 -1
- package/dist/SharedCacheClear.d.ts +46 -0
- package/dist/SharedCacheClear.d.ts.map +1 -0
- package/dist/SharedCacheClear.js +93 -0
- package/dist/SharedCacheClear.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import Redis from 'ioredis';
|
|
17
17
|
import { EventEmitter } from 'events';
|
|
18
|
+
import { randomUUID } from 'crypto';
|
|
18
19
|
import { LogStatus, LogError } from '@memberjunction/core';
|
|
19
20
|
import { MJGlobal } from '@memberjunction/global';
|
|
20
21
|
/**
|
|
@@ -30,6 +31,154 @@ const DEFAULT_CATEGORY = 'default';
|
|
|
30
31
|
* recovery behaviour here without an edit to this list.
|
|
31
32
|
*/
|
|
32
33
|
const RECONCILED_CATEGORIES = ['RunViewCache', 'RunQueryCache', 'DatasetCache', 'Metadata', 'default'];
|
|
34
|
+
/**
|
|
35
|
+
* Categories whose expiry differs from the default. The `default` category never expires on its
|
|
36
|
+
* own: it holds keys that vouch for other keys, and a proxy that outlives its subject is worse
|
|
37
|
+
* than one that never expires. See {@link RedisProviderConfig.categoryTTLSeconds}.
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
const DEFAULT_CATEGORY_TTL_SECONDS = { default: 0 };
|
|
41
|
+
/** Expiry applied when the configuration does not set `defaultTTLSeconds`. @internal */
|
|
42
|
+
const DEFAULT_TTL_SECONDS = 3600;
|
|
43
|
+
/** Keys requested per `SCAN` step. @internal */
|
|
44
|
+
const SCAN_BATCH = 500;
|
|
45
|
+
/**
|
|
46
|
+
* Prunes one index group and returns its live members, atomically.
|
|
47
|
+
*
|
|
48
|
+
* Every step — reading the set, testing each member, removing the dead ones, dropping a set that
|
|
49
|
+
* ends up empty — has to happen without another process's `SADD` landing in between. Done as
|
|
50
|
+
* separate round trips (SMEMBERS, a pipeline of EXISTS, then SREM/DEL), a peer adding a key after
|
|
51
|
+
* the read was removed by a DEL that had never seen it, and that slot lost its invalidation hook
|
|
52
|
+
* permanently: no later save could find it through the index, so every server served it stale until
|
|
53
|
+
* it expired.
|
|
54
|
+
*
|
|
55
|
+
* KEYS[1] = the group set, ARGV[1] = the `{prefix}:{category}:` prefix of a member's own key.
|
|
56
|
+
* @internal
|
|
57
|
+
*/
|
|
58
|
+
const PRUNE_GROUP_SCRIPT = `
|
|
59
|
+
local members = redis.call('SMEMBERS', KEYS[1])
|
|
60
|
+
if #members == 0 then
|
|
61
|
+
return {}
|
|
62
|
+
end
|
|
63
|
+
local alive = {}
|
|
64
|
+
local dead = {}
|
|
65
|
+
for i = 1, #members do
|
|
66
|
+
if redis.call('EXISTS', ARGV[1] .. members[i]) == 1 then
|
|
67
|
+
alive[#alive + 1] = members[i]
|
|
68
|
+
else
|
|
69
|
+
dead[#dead + 1] = members[i]
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
if #dead > 0 then
|
|
73
|
+
if #alive == 0 then
|
|
74
|
+
-- Deleting beats emptying: a set made persistent by a member without expiry stays persistent
|
|
75
|
+
-- once that member goes, and a volatile-* maxmemory policy can never evict it.
|
|
76
|
+
redis.call('DEL', KEYS[1])
|
|
77
|
+
else
|
|
78
|
+
redis.call('SREM', KEYS[1], unpack(dead))
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
return alive
|
|
82
|
+
`;
|
|
83
|
+
/**
|
|
84
|
+
* Adds a key to an index-group set and keeps the set alive at least as long as its longest-lived
|
|
85
|
+
* member, atomically.
|
|
86
|
+
*
|
|
87
|
+
* KEYS[1] = the group set, ARGV[1] = the member key, ARGV[2] = the member's TTL in seconds (0 = none).
|
|
88
|
+
*
|
|
89
|
+
* - A member stored without expiry makes the set persistent.
|
|
90
|
+
* - A member with a TTL extends the set's expiry when the set would otherwise expire first.
|
|
91
|
+
* - A set that is persistent and already holds other members keeps no expiry: every TTL write
|
|
92
|
+
* gives the set an expiry, so a persistent set with more than one member holds a persistent
|
|
93
|
+
* member.
|
|
94
|
+
*
|
|
95
|
+
* Only `SADD`/`TTL`/`SCARD`/`EXPIRE`/`PERSIST` — no Redis 7-only flags, so it runs on the 6.x
|
|
96
|
+
* tiers that hosted Redis services still offer.
|
|
97
|
+
* @internal
|
|
98
|
+
*/
|
|
99
|
+
const ADD_TO_GROUP_SCRIPT = `
|
|
100
|
+
redis.call('SADD', KEYS[1], ARGV[1])
|
|
101
|
+
local ttl = tonumber(ARGV[2])
|
|
102
|
+
if ttl <= 0 then
|
|
103
|
+
redis.call('PERSIST', KEYS[1])
|
|
104
|
+
return 0
|
|
105
|
+
end
|
|
106
|
+
local current = redis.call('TTL', KEYS[1])
|
|
107
|
+
if current == -1 and redis.call('SCARD', KEYS[1]) > 1 then
|
|
108
|
+
return 0
|
|
109
|
+
end
|
|
110
|
+
if current < ttl then
|
|
111
|
+
redis.call('EXPIRE', KEYS[1], ttl)
|
|
112
|
+
end
|
|
113
|
+
return 1
|
|
114
|
+
`;
|
|
115
|
+
/** Deletes a lock key only if it still holds the caller's token. @internal */
|
|
116
|
+
const RELEASE_LOCK_SCRIPT = `
|
|
117
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
118
|
+
return redis.call('DEL', KEYS[1])
|
|
119
|
+
end
|
|
120
|
+
return 0
|
|
121
|
+
`;
|
|
122
|
+
/** How long a key lock lives if its holder dies, and how long a caller waits for one. @internal */
|
|
123
|
+
const KEY_LOCK_TTL_MS = 10000;
|
|
124
|
+
const KEY_LOCK_WAIT_MS = 5000;
|
|
125
|
+
const KEY_LOCK_RETRY_MS = 20;
|
|
126
|
+
/** How often a held lock is extended while its work runs. Must be well under the TTL. @internal */
|
|
127
|
+
const KEY_LOCK_RENEW_MS = 3000;
|
|
128
|
+
/**
|
|
129
|
+
* The longest a lock is renewed for. Renewal keeps a slow read-modify-write safe; without a cap it
|
|
130
|
+
* also keeps a HUNG one holding the key forever, which is worse than the expiry it replaced — no
|
|
131
|
+
* other process could ever take that slot again. Past this, renewal stops and the lock expires on
|
|
132
|
+
* its own TTL, as it did before renewal existed.
|
|
133
|
+
* @internal
|
|
134
|
+
*/
|
|
135
|
+
const KEY_LOCK_MAX_HOLD_MS = 60000;
|
|
136
|
+
/** Extends a lock's expiry only if the caller still holds it. @internal */
|
|
137
|
+
const RENEW_LOCK_SCRIPT = `
|
|
138
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
139
|
+
return redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
140
|
+
end
|
|
141
|
+
return 0
|
|
142
|
+
`;
|
|
143
|
+
/**
|
|
144
|
+
* Thrown by {@link RedisLocalStorageProvider.WithKeyLock} when the lock could not be taken in
|
|
145
|
+
* time — distinct from anything `work` itself throws, so a caller can tell "another process is
|
|
146
|
+
* holding this slot" (fall back to invalidating it) from "my own read-modify-write is broken"
|
|
147
|
+
* (a bug, which must not be silently downgraded to an invalidation).
|
|
148
|
+
*/
|
|
149
|
+
export class KeyLockTimeoutError extends Error {
|
|
150
|
+
/**
|
|
151
|
+
* @param LockKey The lock that could not be taken.
|
|
152
|
+
* @param waitedMs How long the attempt waited.
|
|
153
|
+
* @param reason Why, when it was not contention — e.g. Redis being unreachable. Defaults to the
|
|
154
|
+
* contention message. The class (and so its `name`) is kept either way, because the caller's
|
|
155
|
+
* correct response is the same: do not write, invalidate instead.
|
|
156
|
+
*/
|
|
157
|
+
constructor(LockKey, waitedMs, reason) {
|
|
158
|
+
super(reason ?? `timed out after ${waitedMs} ms waiting for another process's lock`);
|
|
159
|
+
this.LockKey = LockKey;
|
|
160
|
+
this.name = 'KeyLockTimeoutError';
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Thrown when a held lock expired before its work finished — the work may have raced another
|
|
165
|
+
* writer, so its result must not be trusted.
|
|
166
|
+
*/
|
|
167
|
+
export class KeyLockLostError extends Error {
|
|
168
|
+
constructor(LockKey) {
|
|
169
|
+
super(`the lock expired before the work completed; another process may have written the same key`);
|
|
170
|
+
this.LockKey = LockKey;
|
|
171
|
+
this.name = 'KeyLockLostError';
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Escapes the glob metacharacters Redis `MATCH` understands, so a literal prefix or category can
|
|
176
|
+
* be embedded in a pattern.
|
|
177
|
+
* @internal
|
|
178
|
+
*/
|
|
179
|
+
function escapeGlob(literal) {
|
|
180
|
+
return literal.replace(/[*?[\]\\]/g, ch => `\\${ch}`);
|
|
181
|
+
}
|
|
33
182
|
/**
|
|
34
183
|
* Redis-backed implementation of the MemberJunction {@link ILocalStorageProvider} interface.
|
|
35
184
|
*
|
|
@@ -46,8 +195,11 @@ const RECONCILED_CATEGORIES = ['RunViewCache', 'RunQueryCache', 'DatasetCache',
|
|
|
46
195
|
* - **category** — maps to the MJ cache category (`RunViewCache`, `Metadata`, `DatasetCache`, etc.)
|
|
47
196
|
* - **key** — the original key from the caller
|
|
48
197
|
*
|
|
49
|
-
*
|
|
50
|
-
* `
|
|
198
|
+
* Keys written with an `IndexGroup` are also recorded in a Redis Set at
|
|
199
|
+
* `{prefix}:__group__:{category}:{group}` (the RunView cache uses the entity name), which
|
|
200
|
+
* `GetIndexGroupKeys()` reads and prunes. `ClearCategory()` and `GetCategoryKeys()` walk the
|
|
201
|
+
* keyspace with `SCAN`; no category-wide set is kept, because expiry never removes set members
|
|
202
|
+
* and such a set grows without bound once keys carry a TTL.
|
|
51
203
|
*
|
|
52
204
|
* ### TTL Support
|
|
53
205
|
*
|
|
@@ -120,6 +272,13 @@ export class RedisLocalStorageProvider {
|
|
|
120
272
|
* other wrote. See {@link ILocalStorageProvider.SupportsCrossProcessPersistence}.
|
|
121
273
|
*/
|
|
122
274
|
this.SupportsCrossProcessPersistence = true;
|
|
275
|
+
/**
|
|
276
|
+
* `true` — every process configured with the same URL and key prefix shares this keyspace.
|
|
277
|
+
* See {@link ILocalStorageProvider.SharedAcrossProcesses}.
|
|
278
|
+
*/
|
|
279
|
+
this.SharedAcrossProcesses = true;
|
|
280
|
+
/** Tokens of the leases this provider holds, so it releases only its own. */
|
|
281
|
+
this._leaseTokens = new Map();
|
|
123
282
|
this._connected = false;
|
|
124
283
|
/**
|
|
125
284
|
* Whether this client has ever been connected. Distinguishes a startup that has not reached
|
|
@@ -156,9 +315,16 @@ export class RedisLocalStorageProvider {
|
|
|
156
315
|
this._channelHandlers = new Map();
|
|
157
316
|
/** Fully-qualified channel name -> the subscribe still in flight, shared by concurrent callers. */
|
|
158
317
|
this._pendingChannelSubscribes = new Map();
|
|
318
|
+
/** The subscriber start-up in flight or completed, shared by every caller of {@link StartListening}. */
|
|
319
|
+
this._listening = null;
|
|
159
320
|
this._config = config;
|
|
160
321
|
this._keyPrefix = config.keyPrefix ?? 'mj';
|
|
161
|
-
this._defaultTTLSeconds = config.defaultTTLSeconds;
|
|
322
|
+
this._defaultTTLSeconds = config.defaultTTLSeconds ?? DEFAULT_TTL_SECONDS;
|
|
323
|
+
// Merged over the built-in map, never replacing it: the `default` category's "no expiry"
|
|
324
|
+
// is an invariant of what that category HOLDS (proxy keys), so a host that only wants, say,
|
|
325
|
+
// a dataset TTL must not silently reinstate the bug fixed. Naming `default`
|
|
326
|
+
// explicitly still overrides it, which is the only way that should be possible.
|
|
327
|
+
this._categoryTTLSeconds = { ...DEFAULT_CATEGORY_TTL_SECONDS, ...(config.categoryTTLSeconds ?? {}) };
|
|
162
328
|
this._enableLogging = config.enableLogging ?? true;
|
|
163
329
|
this._maxRetryDelayMs = config.maxRetryDelayMs ?? 30000;
|
|
164
330
|
this._enablePubSub = config.enablePubSub ?? false;
|
|
@@ -437,6 +603,52 @@ export class RedisLocalStorageProvider {
|
|
|
437
603
|
buildCategorySetKey(category) {
|
|
438
604
|
return `${this._keyPrefix}:__categories__:${category}`;
|
|
439
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* Builds the Redis Set key that indexes the keys written with one
|
|
608
|
+
* {@link LocalStorageWriteOptions.IndexGroup} in a category.
|
|
609
|
+
*
|
|
610
|
+
* Format: `{prefix}:__group__:{category}:{group}`
|
|
611
|
+
* @internal
|
|
612
|
+
*/
|
|
613
|
+
buildGroupSetKey(category, group) {
|
|
614
|
+
return `${this._keyPrefix}:__group__:${category}:${group}`;
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Resolves the TTL for one write: the per-call value when given (a bare number is the legacy
|
|
618
|
+
* `ttlSeconds` argument), then the category's own expiry, then the configured default. `0`
|
|
619
|
+
* means no expiry.
|
|
620
|
+
* @internal
|
|
621
|
+
*/
|
|
622
|
+
resolveWriteOptions(options, category) {
|
|
623
|
+
const explicit = typeof options === 'number' ? options : options?.TTLSeconds;
|
|
624
|
+
const ttlSeconds = explicit ?? this._categoryTTLSeconds[category] ?? this._defaultTTLSeconds;
|
|
625
|
+
const group = typeof options === 'object' ? options.IndexGroup : undefined;
|
|
626
|
+
return { ttlSeconds: ttlSeconds > 0 ? Math.ceil(ttlSeconds) : 0, group };
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Lists every Redis key matching a glob pattern with `SCAN`, which never blocks the server
|
|
630
|
+
* the way `KEYS` does. Used only for category-wide operations, not on the per-save path.
|
|
631
|
+
* @internal
|
|
632
|
+
*/
|
|
633
|
+
async scanKeys(pattern) {
|
|
634
|
+
const found = [];
|
|
635
|
+
let cursor = '0';
|
|
636
|
+
do {
|
|
637
|
+
const [next, batch] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', SCAN_BATCH);
|
|
638
|
+
found.push(...batch);
|
|
639
|
+
cursor = next;
|
|
640
|
+
} while (cursor !== '0');
|
|
641
|
+
return found;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Deletes Redis keys in fixed-size batches so one call never sends an unbounded argument list.
|
|
645
|
+
* @internal
|
|
646
|
+
*/
|
|
647
|
+
async deleteKeys(redisKeys) {
|
|
648
|
+
for (let i = 0; i < redisKeys.length; i += SCAN_BATCH) {
|
|
649
|
+
await this._client.del(...redisKeys.slice(i, i + SCAN_BATCH));
|
|
650
|
+
}
|
|
651
|
+
}
|
|
440
652
|
/**
|
|
441
653
|
* Retrieves a value from Redis by key and optional category.
|
|
442
654
|
*
|
|
@@ -551,29 +763,30 @@ export class RedisLocalStorageProvider {
|
|
|
551
763
|
* lose their prototype on retrieval; functions, Maps, Sets, and Dates have JSON's
|
|
552
764
|
* usual limitations.
|
|
553
765
|
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
* is set, the key persists indefinitely.
|
|
766
|
+
* The key expires after the per-call TTL when one is given, otherwise after the configured
|
|
767
|
+
* `defaultTTLSeconds`. If neither is set (or the value is `0`), the key persists indefinitely.
|
|
557
768
|
*
|
|
558
|
-
*
|
|
559
|
-
*
|
|
769
|
+
* When the options carry an `IndexGroup`, the key is also added to that group's Redis Set so
|
|
770
|
+
* {@link GetIndexGroupKeys} can find it. The set is kept alive at least as long as its
|
|
771
|
+
* longest-lived member. There is no category-wide set: one would grow for ever once keys
|
|
772
|
+
* expire, because expiry never removes set members. Category-wide operations use `SCAN`.
|
|
560
773
|
*
|
|
561
774
|
* @typeParam T - Type of the value being stored. Caller-controlled.
|
|
562
775
|
* @param key - The key to store under
|
|
563
776
|
* @param value - The value to store (will be JSON-serialized internally)
|
|
564
777
|
* @param category - Optional category for key isolation (defaults to `"default"`)
|
|
565
|
-
* @param
|
|
778
|
+
* @param options - Expiry and index group. A bare number is accepted as the TTL in seconds.
|
|
566
779
|
*
|
|
567
780
|
* @example
|
|
568
781
|
* ```typescript
|
|
569
782
|
* // Store with default TTL
|
|
570
783
|
* await provider.SetItem('view:users', { results, maxUpdatedAt }, 'RunViewCache');
|
|
571
784
|
*
|
|
572
|
-
* // Store with explicit 10-minute TTL
|
|
573
|
-
* await provider.SetItem('
|
|
785
|
+
* // Store with explicit 10-minute TTL, indexed under the entity name
|
|
786
|
+
* await provider.SetItem('Users|…', { results }, 'RunViewCache', { TTLSeconds: 600, IndexGroup: 'Users' });
|
|
574
787
|
* ```
|
|
575
788
|
*/
|
|
576
|
-
async SetItem(key, value, category,
|
|
789
|
+
async SetItem(key, value, category, options) {
|
|
577
790
|
if (this.shouldFailFast) {
|
|
578
791
|
this.noteMutationWhileDisconnected();
|
|
579
792
|
return;
|
|
@@ -581,7 +794,6 @@ export class RedisLocalStorageProvider {
|
|
|
581
794
|
try {
|
|
582
795
|
const cat = category ?? DEFAULT_CATEGORY;
|
|
583
796
|
const redisKey = this.buildKey(key, cat);
|
|
584
|
-
const categorySetKey = this.buildCategorySetKey(cat);
|
|
585
797
|
// Serialize once. We need the string for both the Redis SET and (optionally)
|
|
586
798
|
// the pub/sub publishChange payload, so build it up front.
|
|
587
799
|
let serialized;
|
|
@@ -594,18 +806,18 @@ export class RedisLocalStorageProvider {
|
|
|
594
806
|
}
|
|
595
807
|
return;
|
|
596
808
|
}
|
|
597
|
-
const
|
|
598
|
-
// Use pipeline for atomic set + category tracking
|
|
809
|
+
const { ttlSeconds, group } = this.resolveWriteOptions(options, cat);
|
|
599
810
|
const pipeline = this._client.pipeline();
|
|
600
|
-
if (
|
|
601
|
-
pipeline.setex(redisKey,
|
|
811
|
+
if (ttlSeconds > 0) {
|
|
812
|
+
pipeline.setex(redisKey, ttlSeconds, serialized);
|
|
602
813
|
}
|
|
603
814
|
else {
|
|
604
815
|
pipeline.set(redisKey, serialized);
|
|
605
816
|
}
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
817
|
+
if (group) {
|
|
818
|
+
pipeline.eval(ADD_TO_GROUP_SCRIPT, 1, this.buildGroupSetKey(cat, group), key, ttlSeconds);
|
|
819
|
+
}
|
|
820
|
+
this.logPipelineErrors(await pipeline.exec(), `SetItem "${key}"`);
|
|
609
821
|
// Publish cache change event for cross-server invalidation
|
|
610
822
|
this.publishChange(key, cat, 'set', serialized);
|
|
611
823
|
}
|
|
@@ -633,12 +845,9 @@ export class RedisLocalStorageProvider {
|
|
|
633
845
|
}
|
|
634
846
|
try {
|
|
635
847
|
const cat = category ?? DEFAULT_CATEGORY;
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
pipeline.del(redisKey);
|
|
640
|
-
pipeline.srem(categorySetKey, key);
|
|
641
|
-
await pipeline.exec();
|
|
848
|
+
// Index-group membership is not touched here: the caller does not say which group the
|
|
849
|
+
// key was in, and GetIndexGroupKeys drops members whose key no longer exists.
|
|
850
|
+
await this._client.del(this.buildKey(key, cat));
|
|
642
851
|
// Publish cache change event for cross-server invalidation
|
|
643
852
|
this.publishChange(key, cat, 'removed');
|
|
644
853
|
}
|
|
@@ -649,10 +858,11 @@ export class RedisLocalStorageProvider {
|
|
|
649
858
|
}
|
|
650
859
|
}
|
|
651
860
|
/**
|
|
652
|
-
* Clears all keys belonging to a specific category
|
|
861
|
+
* Clears all keys belonging to a specific category, together with the category's index-group
|
|
862
|
+
* sets and the category set older versions of this provider maintained.
|
|
653
863
|
*
|
|
654
|
-
*
|
|
655
|
-
*
|
|
864
|
+
* Keys are found with `SCAN`, so the operation also removes keys a peer wrote and keys whose
|
|
865
|
+
* index entry was lost.
|
|
656
866
|
*
|
|
657
867
|
* @param category - The category to clear. If empty, clears the `"default"` category.
|
|
658
868
|
*
|
|
@@ -663,44 +873,58 @@ export class RedisLocalStorageProvider {
|
|
|
663
873
|
* ```
|
|
664
874
|
*/
|
|
665
875
|
async ClearCategory(category) {
|
|
876
|
+
await this.ClearCategoryChecked(category);
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* {@link ClearCategory}, but reporting what happened instead of swallowing it. An administrator
|
|
880
|
+
* running `mj cache clear` needs to know a category did NOT go: the old path logged (with
|
|
881
|
+
* logging off, by default, in the CLI) and returned normally, so the command printed a key
|
|
882
|
+
* count and "servers will reload" for a clear that never happened.
|
|
883
|
+
*
|
|
884
|
+
* While Redis is unreachable the clear is recorded for the reconnect flush and reported as not
|
|
885
|
+
* done — the flush will clear it, but reporting success now would be exactly the lie this
|
|
886
|
+
* method exists to stop.
|
|
887
|
+
*
|
|
888
|
+
* @returns Ok, plus the error when it failed.
|
|
889
|
+
*/
|
|
890
|
+
async ClearCategoryChecked(category) {
|
|
666
891
|
if (this.shouldFailFast) {
|
|
667
892
|
this.noteMutationWhileDisconnected();
|
|
668
|
-
return;
|
|
893
|
+
return { Ok: false, Error: 'Redis is unreachable; the clear is deferred to the reconnect flush' };
|
|
669
894
|
}
|
|
670
895
|
try {
|
|
671
896
|
const cat = category || DEFAULT_CATEGORY;
|
|
672
|
-
const
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
else {
|
|
686
|
-
// Category set might still exist even if empty
|
|
687
|
-
await this._client.del(categorySetKey);
|
|
688
|
-
}
|
|
897
|
+
const prefix = escapeGlob(this._keyPrefix);
|
|
898
|
+
const escapedCat = escapeGlob(cat);
|
|
899
|
+
// Index groups go FIRST, entries second. A write can land between the two scans, adding
|
|
900
|
+
// its entry and indexing it in a group. Scanning both and deleting together removed that
|
|
901
|
+
// group while the new entry survived — a live slot no index lists, which a save on another
|
|
902
|
+
// server can no longer find, so it is served stale until it expires. In this order the
|
|
903
|
+
// worst a racing write leaves is a group naming an entry that was then deleted, and a read
|
|
904
|
+
// of the group prunes dead members (GetIndexGroupKeys). A missing member heals itself; a
|
|
905
|
+
// missing index does not.
|
|
906
|
+
const groupKeys = await this.scanKeys(`${prefix}:__group__:${escapedCat}:*`);
|
|
907
|
+
await this.deleteKeys([...groupKeys, this.buildCategorySetKey(cat)]);
|
|
908
|
+
const entryKeys = await this.scanKeys(`${prefix}:${escapedCat}:*`);
|
|
909
|
+
await this.deleteKeys(entryKeys);
|
|
689
910
|
// Publish category-level change event
|
|
690
911
|
this.publishChange(cat, cat, 'category_cleared');
|
|
912
|
+
return { Ok: true };
|
|
691
913
|
}
|
|
692
914
|
catch (err) {
|
|
915
|
+
const message = err.message;
|
|
693
916
|
if (this._enableLogging) {
|
|
694
|
-
LogError(`Redis ClearCategory failed for "${category}": ${
|
|
917
|
+
LogError(`Redis ClearCategory failed for "${category}": ${message}`);
|
|
695
918
|
}
|
|
919
|
+
return { Ok: false, Error: message };
|
|
696
920
|
}
|
|
697
921
|
}
|
|
698
922
|
/**
|
|
699
|
-
* Returns all keys belonging to a specific category.
|
|
923
|
+
* Returns all live keys belonging to a specific category.
|
|
700
924
|
*
|
|
701
|
-
*
|
|
702
|
-
*
|
|
703
|
-
*
|
|
925
|
+
* Walks the keyspace with `SCAN`, so the cost grows with the whole keyspace. Meant for
|
|
926
|
+
* administration and diagnostics; per-entity lookups on the save path use
|
|
927
|
+
* {@link GetIndexGroupKeys}.
|
|
704
928
|
*
|
|
705
929
|
* @param category - The category to list keys from
|
|
706
930
|
* @returns Array of original key names (without the Redis prefix/category prefix)
|
|
@@ -717,8 +941,9 @@ export class RedisLocalStorageProvider {
|
|
|
717
941
|
}
|
|
718
942
|
try {
|
|
719
943
|
const cat = category || DEFAULT_CATEGORY;
|
|
720
|
-
const
|
|
721
|
-
|
|
944
|
+
const redisPrefix = this.buildKey('', cat);
|
|
945
|
+
const redisKeys = await this.scanKeys(`${escapeGlob(redisPrefix)}*`);
|
|
946
|
+
return redisKeys.map(k => k.substring(redisPrefix.length));
|
|
722
947
|
}
|
|
723
948
|
catch (err) {
|
|
724
949
|
if (this._enableLogging) {
|
|
@@ -727,6 +952,199 @@ export class RedisLocalStorageProvider {
|
|
|
727
952
|
return [];
|
|
728
953
|
}
|
|
729
954
|
}
|
|
955
|
+
/**
|
|
956
|
+
* Returns the keys written to `category` with `IndexGroup = group` that still exist.
|
|
957
|
+
*
|
|
958
|
+
* Members whose key has expired or been removed are dropped from the group set as a side
|
|
959
|
+
* effect, so the set shrinks back to the live keys whenever it is read. The read and the prune
|
|
960
|
+
* are one Lua script: a peer's `SADD` cannot land between them and be pruned unseen.
|
|
961
|
+
*
|
|
962
|
+
* @param category - The category the keys were written to
|
|
963
|
+
* @param group - The index group (for the RunView cache, the entity name)
|
|
964
|
+
* @returns The live keys, without the Redis prefix/category prefix
|
|
965
|
+
*/
|
|
966
|
+
async GetIndexGroupKeys(category, group) {
|
|
967
|
+
if (this.shouldFailFast) {
|
|
968
|
+
// Only the save/delete path asks this — an entity just changed and its peers' slots need
|
|
969
|
+
// maintaining, which cannot happen now. Answering "none" alone would be wrong: the caller
|
|
970
|
+
// would write nothing, so nothing would record the change, the epoch would not move, and
|
|
971
|
+
// peers would keep those slots after the reconnect. Recording it makes reconciliation bump
|
|
972
|
+
// the epoch so they flush.
|
|
973
|
+
this.noteMutationWhileDisconnected();
|
|
974
|
+
return [];
|
|
975
|
+
}
|
|
976
|
+
try {
|
|
977
|
+
const cat = category || DEFAULT_CATEGORY;
|
|
978
|
+
const groupSetKey = this.buildGroupSetKey(cat, group);
|
|
979
|
+
const alive = await this._client.eval(PRUNE_GROUP_SCRIPT, 1, groupSetKey, this.buildKey('', cat));
|
|
980
|
+
return Array.isArray(alive) ? alive.map(m => String(m)) : [];
|
|
981
|
+
}
|
|
982
|
+
catch (err) {
|
|
983
|
+
if (this._enableLogging) {
|
|
984
|
+
LogError(`Redis GetIndexGroupKeys failed for "${category}"/"${group}": ${err.message}`);
|
|
985
|
+
}
|
|
986
|
+
return [];
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Runs `work` holding an exclusive lock on `key` across every process sharing this keyspace.
|
|
991
|
+
*
|
|
992
|
+
* The lock is `SET {prefix}:__lock__:{category}:{key} <token> NX PX 10000`, retried every 20 ms
|
|
993
|
+
* for up to 5 s, and released only by its holder (compare-and-delete). The 10 s expiry frees a
|
|
994
|
+
* lock whose holder died; `work` is expected to be a short read-modify-write.
|
|
995
|
+
*
|
|
996
|
+
* @throws when the lock is not acquired in time; `work` has not run
|
|
997
|
+
*/
|
|
998
|
+
async WithKeyLock(key, category, work) {
|
|
999
|
+
const lockKey = `${this._keyPrefix}:__lock__:${category || DEFAULT_CATEGORY}:${key}`;
|
|
1000
|
+
if (this.shouldFailFast) {
|
|
1001
|
+
// The SET NX would queue and never settle (see shouldFailFast). The caller's answer to a
|
|
1002
|
+
// lock it cannot take is to invalidate rather than write, which is right here too.
|
|
1003
|
+
throw new KeyLockTimeoutError(lockKey, 0, 'Redis is unreachable, so the lock was not attempted');
|
|
1004
|
+
}
|
|
1005
|
+
const token = randomUUID();
|
|
1006
|
+
await this.acquireLock(lockKey, token);
|
|
1007
|
+
// Work longer than the TTL used to lose the lock silently: it expired, another process took
|
|
1008
|
+
// it, and both wrote — the very lost update this lock exists to prevent. The lock is now
|
|
1009
|
+
// extended while the work runs, and a lock that was lost anyway (a stalled renewal, a
|
|
1010
|
+
// failover) is reported rather than ignored.
|
|
1011
|
+
const renewUntil = Date.now() + KEY_LOCK_MAX_HOLD_MS;
|
|
1012
|
+
// When the lock was last known to be ours. Every successful renewal moves it forward; it is
|
|
1013
|
+
// what the post-work check falls back on when Redis cannot be read at all.
|
|
1014
|
+
let confirmedAt = Date.now();
|
|
1015
|
+
const renewal = setInterval(() => {
|
|
1016
|
+
if (Date.now() >= renewUntil) {
|
|
1017
|
+
clearInterval(renewal);
|
|
1018
|
+
LogError(`Redis key lock "${lockKey}" has been held for ${KEY_LOCK_MAX_HOLD_MS} ms; no longer renewing it, so it expires on its own and other processes can proceed. The work holding it is hung.`);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
this.renewLock(lockKey, token).then(() => { confirmedAt = Date.now(); }).catch(() => undefined);
|
|
1022
|
+
}, KEY_LOCK_RENEW_MS);
|
|
1023
|
+
if (typeof renewal === 'object' && renewal !== null && 'unref' in renewal) {
|
|
1024
|
+
renewal.unref();
|
|
1025
|
+
}
|
|
1026
|
+
try {
|
|
1027
|
+
const result = await work();
|
|
1028
|
+
if (!(await this.stillHoldsLock(lockKey, token, confirmedAt))) {
|
|
1029
|
+
throw new KeyLockLostError(lockKey);
|
|
1030
|
+
}
|
|
1031
|
+
return result;
|
|
1032
|
+
}
|
|
1033
|
+
finally {
|
|
1034
|
+
clearInterval(renewal);
|
|
1035
|
+
await this.releaseLock(lockKey, token);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
/** Extends this holder's lock. @internal */
|
|
1039
|
+
async renewLock(lockKey, token) {
|
|
1040
|
+
await this._client.eval(RENEW_LOCK_SCRIPT, 1, lockKey, token, String(KEY_LOCK_TTL_MS));
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Whether this holder's token is still the one in the lock.
|
|
1044
|
+
*
|
|
1045
|
+
* @param confirmedAt when the lock was last known to be ours (acquisition, or the most recent
|
|
1046
|
+
* renewal that actually landed)
|
|
1047
|
+
*
|
|
1048
|
+
* This used to answer `true` when the read failed, on the reasoning that an unreadable check
|
|
1049
|
+
* should not fail a write. But the failures are correlated: this read and the renewals share
|
|
1050
|
+
* one connection, so a read that throws means the renewals have been throwing too, and the
|
|
1051
|
+
* lock is most likely expired — the one case where "still mine" is both unverifiable and
|
|
1052
|
+
* probably false. The clock is the evidence that remains: a lock cannot outlive its TTL
|
|
1053
|
+
* measured from the last time we know it was ours.
|
|
1054
|
+
* @internal
|
|
1055
|
+
*/
|
|
1056
|
+
async stillHoldsLock(lockKey, token, confirmedAt) {
|
|
1057
|
+
try {
|
|
1058
|
+
return (await this._client.get(lockKey)) === token;
|
|
1059
|
+
}
|
|
1060
|
+
catch {
|
|
1061
|
+
return Date.now() - confirmedAt < KEY_LOCK_TTL_MS;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Claims `{prefix}:__lease__:{name}` for `ttlMs` with `SET NX PX`, so one process in the fleet
|
|
1066
|
+
* runs a periodic job per period. The lease is not released; it expires.
|
|
1067
|
+
*/
|
|
1068
|
+
async TryAcquireLease(name, ttlMs) {
|
|
1069
|
+
if (this.shouldFailFast) {
|
|
1070
|
+
return false; // not acquired: this tick's sweep or warm-up simply does not run here
|
|
1071
|
+
}
|
|
1072
|
+
const token = randomUUID();
|
|
1073
|
+
const claimed = (await this._client.set(this.leaseKey(name), token, 'PX', Math.max(1, Math.floor(ttlMs)), 'NX')) === 'OK';
|
|
1074
|
+
if (claimed) {
|
|
1075
|
+
this._leaseTokens.set(name, token);
|
|
1076
|
+
}
|
|
1077
|
+
return claimed;
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* Extends a lease this provider holds, without being able to extend anyone else's: the script
|
|
1081
|
+
* only acts when the stored token is this provider's. A lease that has already expired and been
|
|
1082
|
+
* taken by another process is NOT stolen back — the caller learns it lost its turn.
|
|
1083
|
+
*
|
|
1084
|
+
* @returns true when this process still holds the lease afterwards.
|
|
1085
|
+
*/
|
|
1086
|
+
async RenewLease(name, ttlMs) {
|
|
1087
|
+
const token = this._leaseTokens.get(name);
|
|
1088
|
+
if (!token) {
|
|
1089
|
+
return false;
|
|
1090
|
+
}
|
|
1091
|
+
if (this.shouldFailFast) {
|
|
1092
|
+
return false; // a lease that cannot be renewed must not be assumed held
|
|
1093
|
+
}
|
|
1094
|
+
const extended = await this._client.eval(RENEW_LOCK_SCRIPT, 1, this.leaseKey(name), token, String(Math.max(1, Math.floor(ttlMs))));
|
|
1095
|
+
return Number(extended) === 1;
|
|
1096
|
+
}
|
|
1097
|
+
/** Ends a lease this provider claimed, if it still holds it (compare-and-delete). */
|
|
1098
|
+
async ReleaseLease(name) {
|
|
1099
|
+
const token = this._leaseTokens.get(name);
|
|
1100
|
+
if (!token) {
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
this._leaseTokens.delete(name);
|
|
1104
|
+
if (this.shouldFailFast) {
|
|
1105
|
+
return; // the lease expires on its own TTL; nothing is lost by not deleting it now
|
|
1106
|
+
}
|
|
1107
|
+
await this.releaseLock(this.leaseKey(name), token);
|
|
1108
|
+
}
|
|
1109
|
+
leaseKey(name) {
|
|
1110
|
+
return `${this._keyPrefix}:__lease__:${name}`;
|
|
1111
|
+
}
|
|
1112
|
+
/** @internal */
|
|
1113
|
+
async acquireLock(lockKey, token) {
|
|
1114
|
+
const deadline = Date.now() + KEY_LOCK_WAIT_MS;
|
|
1115
|
+
for (;;) {
|
|
1116
|
+
if ((await this._client.set(lockKey, token, 'PX', KEY_LOCK_TTL_MS, 'NX')) === 'OK') {
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
if (Date.now() >= deadline) {
|
|
1120
|
+
throw new KeyLockTimeoutError(lockKey, KEY_LOCK_WAIT_MS);
|
|
1121
|
+
}
|
|
1122
|
+
await new Promise(resolve => setTimeout(resolve, KEY_LOCK_RETRY_MS));
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
/** @internal */
|
|
1126
|
+
async releaseLock(lockKey, token) {
|
|
1127
|
+
try {
|
|
1128
|
+
await this._client.eval(RELEASE_LOCK_SCRIPT, 1, lockKey, token);
|
|
1129
|
+
}
|
|
1130
|
+
catch (err) {
|
|
1131
|
+
// The lock expires on its own; a failed release only delays the next writer.
|
|
1132
|
+
if (this._enableLogging) {
|
|
1133
|
+
LogError(`Redis lock release failed for "${lockKey}": ${err.message}`);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/** Logs any per-command failure a pipeline reported; `exec()` itself does not throw for them. @internal */
|
|
1138
|
+
logPipelineErrors(results, context) {
|
|
1139
|
+
if (!this._enableLogging || !results) {
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
for (const [err] of results) {
|
|
1143
|
+
if (err) {
|
|
1144
|
+
LogError(`Redis ${context}: ${err.message}`);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
730
1148
|
/**
|
|
731
1149
|
* Whether the Redis client currently has an active connection.
|
|
732
1150
|
*
|
|
@@ -744,11 +1162,15 @@ export class RedisLocalStorageProvider {
|
|
|
744
1162
|
* category tracking. Prefer the `ILocalStorageProvider` methods for
|
|
745
1163
|
* standard operations.
|
|
746
1164
|
*
|
|
1165
|
+
* For pub/sub, use {@link PublishMessage}, {@link PublishMessageAndWait} and
|
|
1166
|
+
* {@link SubscribeToChannel} instead: they share the provider's subscriber connection and
|
|
1167
|
+
* namespace channels with the key prefix.
|
|
1168
|
+
*
|
|
747
1169
|
* @example
|
|
748
1170
|
* ```typescript
|
|
749
|
-
* // Use for Redis-specific commands
|
|
1171
|
+
* // Use for Redis-specific commands the provider does not wrap, such as streams
|
|
750
1172
|
* const client = provider.Client;
|
|
751
|
-
* await client.
|
|
1173
|
+
* await client.xadd('audit-events', '*', 'type', 'login');
|
|
752
1174
|
* ```
|
|
753
1175
|
*/
|
|
754
1176
|
get Client() {
|
|
@@ -783,9 +1205,11 @@ export class RedisLocalStorageProvider {
|
|
|
783
1205
|
this._subscriber = null;
|
|
784
1206
|
this._subscriberConnected = false;
|
|
785
1207
|
}
|
|
1208
|
+
this._listening = null;
|
|
786
1209
|
// Remove all event listeners
|
|
787
1210
|
this._eventEmitter.removeAllListeners();
|
|
788
1211
|
this._channelHandlers.clear();
|
|
1212
|
+
this._pendingChannelSubscribes.clear();
|
|
789
1213
|
try {
|
|
790
1214
|
await this._client.quit();
|
|
791
1215
|
this._connected = false;
|
|
@@ -900,7 +1324,8 @@ export class RedisLocalStorageProvider {
|
|
|
900
1324
|
* a client in subscribe mode cannot execute other commands).
|
|
901
1325
|
*
|
|
902
1326
|
* Must be called explicitly after construction. No-op if `enablePubSub` is `false`
|
|
903
|
-
* in the config
|
|
1327
|
+
* in the config. Concurrent and repeated calls share one start-up; if it fails, the
|
|
1328
|
+
* subscriber is discarded and the next call starts a fresh one.
|
|
904
1329
|
*
|
|
905
1330
|
* @example
|
|
906
1331
|
* ```typescript
|
|
@@ -923,23 +1348,55 @@ export class RedisLocalStorageProvider {
|
|
|
923
1348
|
}
|
|
924
1349
|
return;
|
|
925
1350
|
}
|
|
926
|
-
if (this.
|
|
927
|
-
|
|
928
|
-
|
|
1351
|
+
if (!this._listening) {
|
|
1352
|
+
const listening = this.openSubscriber();
|
|
1353
|
+
this._listening = listening;
|
|
1354
|
+
listening.catch(() => {
|
|
1355
|
+
if (this._listening === listening) {
|
|
1356
|
+
this._listening = null;
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
929
1359
|
}
|
|
930
|
-
|
|
1360
|
+
return this._listening;
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Creates the subscriber connection and subscribes it to the cache-invalidation channel.
|
|
1364
|
+
*
|
|
1365
|
+
* The message listener is attached before subscribing, so nothing that arrives is missed. On
|
|
1366
|
+
* failure the connection is closed and cleared. A retry does not depend on that —
|
|
1367
|
+
* {@link StartListening} resets its own in-flight promise and opens a fresh subscriber — but the
|
|
1368
|
+
* failed client would otherwise stay open, reconnecting in the background with unlimited retries,
|
|
1369
|
+
* and once it got back in it would resubscribe and deliver every invalidation a second time.
|
|
1370
|
+
*/
|
|
1371
|
+
async openSubscriber() {
|
|
1372
|
+
const subscriber = this.createSubscriberClient();
|
|
1373
|
+
this._subscriber = subscriber;
|
|
931
1374
|
this.setupSubscriberEventHandlers();
|
|
932
|
-
|
|
933
|
-
if (this._enableLogging) {
|
|
934
|
-
LogStatus(`Redis pub/sub: subscribed to channel "${this._pubSubChannel}"`);
|
|
935
|
-
}
|
|
936
|
-
this._subscriber.on('message', (channel, message) => {
|
|
1375
|
+
subscriber.on('message', (channel, message) => {
|
|
937
1376
|
if (channel === this._pubSubChannel) {
|
|
938
1377
|
this.handlePubSubMessage(message);
|
|
939
1378
|
return;
|
|
940
1379
|
}
|
|
941
1380
|
this.dispatchChannelMessage(channel, message);
|
|
942
1381
|
});
|
|
1382
|
+
try {
|
|
1383
|
+
await subscriber.subscribe(this._pubSubChannel);
|
|
1384
|
+
}
|
|
1385
|
+
catch (err) {
|
|
1386
|
+
this.discardSubscriber(subscriber);
|
|
1387
|
+
throw err;
|
|
1388
|
+
}
|
|
1389
|
+
if (this._enableLogging) {
|
|
1390
|
+
LogStatus(`Redis pub/sub: subscribed to channel "${this._pubSubChannel}"`);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
/** Closes a subscriber that failed to start, and clears it if it is still the current one. */
|
|
1394
|
+
discardSubscriber(subscriber) {
|
|
1395
|
+
subscriber.disconnect();
|
|
1396
|
+
if (this._subscriber === subscriber) {
|
|
1397
|
+
this._subscriber = null;
|
|
1398
|
+
this._subscriberConnected = false;
|
|
1399
|
+
}
|
|
943
1400
|
}
|
|
944
1401
|
/**
|
|
945
1402
|
* Creates the subscriber Redis client, mirroring the main client's connection config.
|
|
@@ -1038,6 +1495,13 @@ export class RedisLocalStorageProvider {
|
|
|
1038
1495
|
if (!this._enablePubSub) {
|
|
1039
1496
|
return;
|
|
1040
1497
|
}
|
|
1498
|
+
const mode = action === 'category_cleared' ? 'full' : this.publishModeFor(category);
|
|
1499
|
+
if (mode === 'none') {
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
if (mode === 'notice') {
|
|
1503
|
+
data = undefined;
|
|
1504
|
+
}
|
|
1041
1505
|
const event = {
|
|
1042
1506
|
CacheKey: cacheKey,
|
|
1043
1507
|
Category: category,
|
|
@@ -1047,7 +1511,11 @@ export class RedisLocalStorageProvider {
|
|
|
1047
1511
|
Data: data,
|
|
1048
1512
|
};
|
|
1049
1513
|
// Bump the shared epoch, then publish carrying its new value. The counter lives here
|
|
1050
|
-
// because every mutation
|
|
1514
|
+
// because every PUBLISHED mutation routes through this method. A category whose publish mode
|
|
1515
|
+
// is 'none' returns above without bumping it, and correctly: the epoch tells a reconnecting
|
|
1516
|
+
// process whether it missed an EVENT, and no process ever receives one for such a category,
|
|
1517
|
+
// so there is nothing to miss. A write made while disconnected is recorded separately, before
|
|
1518
|
+
// this method is reached (see noteMutationWhileDisconnected). INCR has to precede PUBLISH so
|
|
1051
1519
|
// the payload can carry the result, which costs a second round trip — off the caller's path,
|
|
1052
1520
|
// since this method is fire-and-forget.
|
|
1053
1521
|
this._client.incr(this.buildEpochKey()).then((epoch) => {
|
|
@@ -1067,47 +1535,101 @@ export class RedisLocalStorageProvider {
|
|
|
1067
1535
|
}
|
|
1068
1536
|
});
|
|
1069
1537
|
}
|
|
1538
|
+
/** The configured publish mode for a category. @internal */
|
|
1539
|
+
publishModeFor(category) {
|
|
1540
|
+
return this._config.publishModes?.[category] ?? this._config.defaultPublishMode ?? 'full';
|
|
1541
|
+
}
|
|
1070
1542
|
/**
|
|
1071
1543
|
* Publishes an arbitrary message on a named channel. Fire-and-forget: the promise is not
|
|
1072
1544
|
* awaited and a failure is logged rather than raised, so a caller on a hot path is never
|
|
1073
|
-
* blocked or broken by the message bus.
|
|
1545
|
+
* blocked or broken by the message bus. Does nothing when pub/sub is disabled.
|
|
1546
|
+
*
|
|
1547
|
+
* Use {@link PublishMessageAndWait} when the caller needs to know whether the message went out.
|
|
1074
1548
|
*
|
|
1075
1549
|
* The channel is namespaced with the provider's key prefix, so several applications can share
|
|
1076
1550
|
* one Redis without hearing each other.
|
|
1077
1551
|
*
|
|
1078
1552
|
* @param channel Logical channel name (unprefixed).
|
|
1079
1553
|
* @param payload Message body. Serialize before calling — this layer is shape-agnostic.
|
|
1554
|
+
* @throws If `channel` is the name reserved for cache invalidation.
|
|
1080
1555
|
*/
|
|
1081
1556
|
PublishMessage(channel, payload) {
|
|
1557
|
+
const fullChannel = this.qualifyChannel(channel);
|
|
1082
1558
|
if (!this._enablePubSub) {
|
|
1083
1559
|
return;
|
|
1084
1560
|
}
|
|
1085
|
-
|
|
1561
|
+
if (this.shouldFailFast) {
|
|
1562
|
+
return; // nobody can hear it; fire-and-forget callers already accept a lost message
|
|
1563
|
+
}
|
|
1086
1564
|
this._client.publish(fullChannel, payload).catch((err) => {
|
|
1087
1565
|
if (this._enableLogging) {
|
|
1088
1566
|
LogError(`Redis pub/sub publish failed on "${fullChannel}": ${err.message}`);
|
|
1089
1567
|
}
|
|
1090
1568
|
});
|
|
1091
1569
|
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Publishes a message on a named channel and waits for Redis to accept it.
|
|
1572
|
+
*
|
|
1573
|
+
* Use this instead of {@link PublishMessage} when the caller must report honestly whether the
|
|
1574
|
+
* message went out — for example, telling a user whether a cancellation reached the server
|
|
1575
|
+
* running their request.
|
|
1576
|
+
*
|
|
1577
|
+
* While the connection is down the publish waits for it to come back rather than failing, so a
|
|
1578
|
+
* caller that needs a deadline should race it against a timeout.
|
|
1579
|
+
*
|
|
1580
|
+
* @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
|
|
1581
|
+
* @param payload Message body. Serialize before calling — this layer is shape-agnostic.
|
|
1582
|
+
* @returns The number of subscribers that received the message, across every process sharing
|
|
1583
|
+
* the Redis — including this one, if it subscribes to the same channel. Zero means the
|
|
1584
|
+
* message was published but nobody was listening.
|
|
1585
|
+
* @throws If pub/sub is disabled, if `channel` is reserved, or if Redis rejects the publish.
|
|
1586
|
+
*/
|
|
1587
|
+
async PublishMessageAndWait(channel, payload) {
|
|
1588
|
+
const fullChannel = this.qualifyChannel(channel);
|
|
1589
|
+
if (!this._enablePubSub) {
|
|
1590
|
+
throw new Error(`Redis pub/sub: cannot publish on "${channel}" — the provider was created without enablePubSub`);
|
|
1591
|
+
}
|
|
1592
|
+
if (this.shouldFailFast) {
|
|
1593
|
+
return 0; // the truthful receiver count while Redis is unreachable
|
|
1594
|
+
}
|
|
1595
|
+
return this._client.publish(fullChannel, payload);
|
|
1596
|
+
}
|
|
1092
1597
|
/**
|
|
1093
1598
|
* Registers a handler for messages on a named channel, starting the subscriber if needed.
|
|
1094
1599
|
*
|
|
1600
|
+
* When pub/sub is disabled this registers nothing and returns an inert unsubscribe; check
|
|
1601
|
+
* {@link IsPubSubEnabled} to tell that apart from a live subscription.
|
|
1602
|
+
*
|
|
1095
1603
|
* No echo suppression happens here — this layer does not know the payload shape. A publisher
|
|
1096
1604
|
* that needs it must stamp its own origin on the message and check it in the handler.
|
|
1097
1605
|
*
|
|
1098
|
-
*
|
|
1606
|
+
* Redis does not replay messages, so anything published while the subscriber is disconnected
|
|
1607
|
+
* is never delivered.
|
|
1608
|
+
*
|
|
1609
|
+
* @param channel Logical channel name (unprefixed), namespaced as in {@link PublishMessage}.
|
|
1610
|
+
* @param handler Called with each message body. May be async.
|
|
1611
|
+
* @returns A function that removes this handler. When the last handler on a channel is
|
|
1612
|
+
* removed, the provider unsubscribes from it in Redis.
|
|
1613
|
+
* @throws If `channel` is reserved, or if Redis rejects the subscribe.
|
|
1099
1614
|
*/
|
|
1100
1615
|
async SubscribeToChannel(channel, handler) {
|
|
1616
|
+
const fullChannel = this.qualifyChannel(channel);
|
|
1101
1617
|
if (!this._enablePubSub) {
|
|
1102
1618
|
return () => undefined;
|
|
1103
1619
|
}
|
|
1620
|
+
if (this.shouldFailFast) {
|
|
1621
|
+
// The SUBSCRIBE would queue and never settle. Fail loudly instead, so the caller can
|
|
1622
|
+
// degrade and say so rather than await forever.
|
|
1623
|
+
throw new Error(`Redis is unreachable; cannot subscribe to "${channel}" until it reconnects`);
|
|
1624
|
+
}
|
|
1104
1625
|
await this.StartListening();
|
|
1105
|
-
const fullChannel = this.qualifyChannel(channel);
|
|
1106
1626
|
const handlers = await this.channelHandlersFor(fullChannel);
|
|
1107
1627
|
handlers.add(handler);
|
|
1108
|
-
return () =>
|
|
1109
|
-
|
|
1110
|
-
|
|
1628
|
+
return () => this.removeChannelHandler(fullChannel, handlers, handler);
|
|
1629
|
+
}
|
|
1630
|
+
/** Whether the provider was created with `enablePubSub`. When false, the channel methods do nothing. */
|
|
1631
|
+
get IsPubSubEnabled() {
|
|
1632
|
+
return this._enablePubSub;
|
|
1111
1633
|
}
|
|
1112
1634
|
/**
|
|
1113
1635
|
* The handler set for a channel, subscribing first when no caller has yet.
|
|
@@ -1140,7 +1662,10 @@ export class RedisLocalStorageProvider {
|
|
|
1140
1662
|
* with nothing surfaced.
|
|
1141
1663
|
*/
|
|
1142
1664
|
async subscribeChannel(fullChannel) {
|
|
1143
|
-
|
|
1665
|
+
if (!this._subscriber) {
|
|
1666
|
+
throw new Error(`Redis pub/sub: cannot subscribe to "${fullChannel}" — the subscriber is not running`);
|
|
1667
|
+
}
|
|
1668
|
+
await this._subscriber.subscribe(fullChannel);
|
|
1144
1669
|
const handlers = new Set();
|
|
1145
1670
|
this._channelHandlers.set(fullChannel, handlers);
|
|
1146
1671
|
if (this._enableLogging) {
|
|
@@ -1148,6 +1673,28 @@ export class RedisLocalStorageProvider {
|
|
|
1148
1673
|
}
|
|
1149
1674
|
return handlers;
|
|
1150
1675
|
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Removes one handler, and unsubscribes the channel in Redis when it was the last.
|
|
1678
|
+
*
|
|
1679
|
+
* Safe to call more than once. A handler set that is no longer the channel's current one
|
|
1680
|
+
* belongs to a subscription already released, so it never triggers a second unsubscribe. A
|
|
1681
|
+
* subscribe that arrives while the unsubscribe is in flight is queued behind it on the same
|
|
1682
|
+
* connection, so the channel ends up subscribed.
|
|
1683
|
+
*/
|
|
1684
|
+
removeChannelHandler(fullChannel, handlers, handler) {
|
|
1685
|
+
if (!handlers.delete(handler) || handlers.size > 0) {
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
if (this._channelHandlers.get(fullChannel) !== handlers) {
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
this._channelHandlers.delete(fullChannel);
|
|
1692
|
+
this._subscriber?.unsubscribe(fullChannel).catch((err) => {
|
|
1693
|
+
if (this._enableLogging) {
|
|
1694
|
+
LogError(`Redis pub/sub unsubscribe failed on "${fullChannel}": ${err.message}`);
|
|
1695
|
+
}
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1151
1698
|
/** Routes an inbound message to the handlers registered for its channel. @internal */
|
|
1152
1699
|
dispatchChannelMessage(channel, message) {
|
|
1153
1700
|
const handlers = this._channelHandlers.get(channel);
|
|
@@ -1155,19 +1702,40 @@ export class RedisLocalStorageProvider {
|
|
|
1155
1702
|
return;
|
|
1156
1703
|
}
|
|
1157
1704
|
for (const handler of handlers) {
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1705
|
+
this.invokeChannelHandler(channel, handler, message);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
/**
|
|
1709
|
+
* Runs one handler, containing a throw or a rejected promise so the other handlers still run.
|
|
1710
|
+
*
|
|
1711
|
+
* Failures are logged even when `enableLogging` is off: that setting quiets connection noise,
|
|
1712
|
+
* and a failing handler is a defect in the consumer that would otherwise vanish.
|
|
1713
|
+
*/
|
|
1714
|
+
invokeChannelHandler(channel, handler, message) {
|
|
1715
|
+
const report = (err) => {
|
|
1716
|
+
LogError(`Redis pub/sub handler for "${channel}" failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1717
|
+
};
|
|
1718
|
+
try {
|
|
1719
|
+
const result = handler(message);
|
|
1720
|
+
if (result instanceof Promise) {
|
|
1721
|
+
result.catch(report);
|
|
1165
1722
|
}
|
|
1166
1723
|
}
|
|
1724
|
+
catch (err) {
|
|
1725
|
+
report(err);
|
|
1726
|
+
}
|
|
1167
1727
|
}
|
|
1168
|
-
/**
|
|
1728
|
+
/**
|
|
1729
|
+
* Namespaces a channel with the provider's key prefix.
|
|
1730
|
+
* @throws If the result is the channel reserved for cache invalidation, where a message would
|
|
1731
|
+
* be read as a cache change by every server.
|
|
1732
|
+
*/
|
|
1169
1733
|
qualifyChannel(channel) {
|
|
1170
|
-
|
|
1734
|
+
const fullChannel = `${this._keyPrefix}:${channel}`;
|
|
1735
|
+
if (fullChannel === this._pubSubChannel) {
|
|
1736
|
+
throw new Error(`Redis pub/sub: channel "${channel}" is reserved for cache invalidation`);
|
|
1737
|
+
}
|
|
1738
|
+
return fullChannel;
|
|
1171
1739
|
}
|
|
1172
1740
|
/**
|
|
1173
1741
|
* Registers a callback for cache change events from other servers.
|