@memberjunction/redis-provider 6.2.0-edge.2 → 6.2.0-edge.4

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 CHANGED
@@ -52,7 +52,7 @@ The `RedisProviderConfig` object supports the following options:
52
52
  | `url` | `string` | — | Redis connection URL (`redis://` or `rediss://` for TLS). Mutually exclusive with `options`. |
53
53
  | `options` | `RedisOptions` | — | Full [`ioredis` options](https://github.com/redis/ioredis#connect-to-redis) object. Mutually exclusive with `url`. |
54
54
  | `keyPrefix` | `string` | `'mj'` | Prefix for all Redis keys. Useful for isolating MJ data in a shared Redis instance. |
55
- | `defaultTTLSeconds` | `number` | `undefined` | Default time-to-live for all cached entries. `undefined` means keys persist until explicitly removed. |
55
+ | `defaultTTLSeconds` | `number` | `3600` | Default time-to-live for all cached entries. `0` means keys persist until explicitly removed. |
56
56
  | `maxRetries` | `number` | `10` | Maximum reconnection attempts with exponential backoff before giving up. |
57
57
  | `enableLogging` | `boolean` | `true` | Whether to log connection events via MJ's `LogStatus`/`LogError`. |
58
58
 
@@ -170,20 +170,37 @@ mj:DatasetCache:MyDataset_items
170
170
  mj:default:some-arbitrary-key
171
171
  ```
172
172
 
173
- ### Category Tracking
173
+ ### Index Groups
174
174
 
175
- Each category has an associated Redis Set at `{prefix}:__categories__:{category}` that tracks all member keys. This enables efficient:
175
+ A write can name an index group (`SetItem(key, value, category, { IndexGroup })`). The key is then
176
+ recorded in a Redis Set at `{prefix}:__group__:{category}:{group}`. `LocalCacheManager` passes the
177
+ entity name for every RunView cache entry, so any server can find the entries any other server wrote
178
+ for an entity:
176
179
 
177
- - **`ClearCategory()`** — Deletes all keys in a category in a single pipeline
178
- - **`GetCategoryKeys()`** — Lists all keys without scanning the entire keyspace
180
+ - **`GetIndexGroupKeys(category, group)`** — returns the group's keys that still exist, and removes
181
+ the ones that have expired from the set.
182
+ - The set is kept alive at least as long as its longest-lived member (an atomic Lua script that uses
183
+ only Redis 6-compatible commands).
184
+
185
+ There is no category-wide set. Expiry never removes set members, so such a set grows without bound
186
+ once keys carry a TTL. Category-wide operations use `SCAN` instead:
187
+
188
+ - **`ClearCategory()`** — deletes every key in the category, its index-group sets, and the
189
+ `{prefix}:__categories__:{category}` set that earlier versions of this provider maintained
190
+ - **`GetCategoryKeys()`** — lists every live key in the category (cost grows with the keyspace; meant
191
+ for administration)
179
192
 
180
193
  ### TTL (Time-to-Live)
181
194
 
182
195
  Redis has native key expiration, so TTL is handled efficiently at the server level:
183
196
 
184
- 1. **Config default** — `defaultTTLSeconds` applies to every `SetItem()` call
185
- 2. **Per-call override** — `SetItem(key, value, category, ttlSeconds)` overrides the default
186
- 3. **No TTL** — If neither is set, keys persist until explicitly removed or `ClearCategory()` is called
197
+ 1. **Config default** — `defaultTTLSeconds` applies to every `SetItem()` call. It defaults to **3600 (one hour)**.
198
+ 2. **Per-call override** — `SetItem(key, value, category, { TTLSeconds })` (or a bare number) overrides the default
199
+ 3. **No TTL** — `0`, either as the default or per call, stores the key without expiry
200
+
201
+ Event-driven invalidation stays the primary freshness mechanism. The TTL bounds how long an entry written by
202
+ something that never publishes (direct SQL, another application) can be served, and gives a `volatile-*`
203
+ eviction policy something to evict — Redis never evicts a key without an expiry under those policies.
187
204
 
188
205
  ### Error Handling
189
206
 
@@ -215,10 +232,11 @@ The interface is **generic-typed** — `T` flows from caller through to retrieve
215
232
  |--------|-------------|
216
233
  | `GetItem<T>(key, category?)` | Retrieves a cached value. **JSON-deserializes internally** — returns the typed object. Returns `null` on miss, corrupt entry, or Redis unavailability. |
217
234
  | `GetItems<T>(keys, category?)` | **Batched read via Redis `MGET`** — one command, one network round-trip, N values. Returns `Map<string, T \| null>`. Missing/corrupt entries map to `null` per-key without failing the batch. ~N× faster than individual `GetItem` calls which each pay full RTT. |
218
- | `SetItem<T>(key, value, category?, ttlSeconds?)` | Stores a value with optional TTL. **JSON-serializes internally** — pass plain objects/arrays/primitives. Uses pipeline for atomic set + category tracking. |
219
- | `Remove(key, category?)` | Deletes a key and removes it from category tracking. |
220
- | `ClearCategory(category)` | Deletes all keys in a category using the tracking Set. |
221
- | `GetCategoryKeys(category)` | Returns all key names in a category. |
235
+ | `SetItem<T>(key, value, category?, options?)` | Stores a value. `options` is `{ TTLSeconds?, IndexGroup? }` or a bare TTL number. **JSON-serializes internally** — pass plain objects/arrays/primitives. One pipeline for the write and the index-group update. |
236
+ | `Remove(key, category?)` | Deletes a key. Index-group membership is pruned the next time the group is read. |
237
+ | `ClearCategory(category)` | Deletes all keys in a category (found with `SCAN`) and the category's index-group sets. |
238
+ | `GetCategoryKeys(category)` | Returns all live key names in a category (`SCAN`). |
239
+ | `GetIndexGroupKeys(category, group)` | Returns the live keys written with that index group, pruning expired members. |
222
240
 
223
241
  **Internal serialization**: Redis stores strings, so `SetItem` calls `JSON.stringify(value)` and `GetItem` calls `JSON.parse(raw)` automatically. Callers see a typed object interface — no manual `JSON.parse`/`JSON.stringify` needed.
224
242
 
@@ -263,7 +281,38 @@ if (session) {
263
281
  | Property | Type | Description |
264
282
  |----------|------|-------------|
265
283
  | `IsConnected` | `boolean` | Whether the client has an active connection (transient — auto-reconnects). |
266
- | `Client` | `Redis` | The underlying `ioredis` client for advanced operations (pub/sub, streams, etc.). |
284
+ | `IsPubSubEnabled` | `boolean` | Whether the provider was created with `enablePubSub`. When `false`, the channel methods below do nothing. |
285
+ | `Client` | `Redis` | The underlying `ioredis` client, for commands the provider does not wrap (streams, etc.). Use the channel methods below for pub/sub. |
286
+
287
+ #### Named Channels (Application Pub/Sub)
288
+
289
+ Besides cache invalidation, the provider carries messages on channels you name. They use the provider's existing publisher and subscriber connections, so an application needs no Redis clients of its own.
290
+
291
+ | Method | Description |
292
+ |--------|-------------|
293
+ | `PublishMessage(channel, payload)` | Fire-and-forget. A failure is logged, never raised. |
294
+ | `PublishMessageAndWait(channel, payload)` | Resolves to the number of subscribers that received the message (`0` = nobody listening). Rejects if pub/sub is disabled or Redis rejects the publish. While disconnected it waits for the connection, so race it against a timeout if you need a deadline. |
295
+ | `SubscribeToChannel(channel, handler)` | Registers a handler (sync or async) and returns an unsubscribe function. Removing a channel's last handler unsubscribes it in Redis. |
296
+
297
+ ```typescript
298
+ const redis = new RedisLocalStorageProvider({ url: process.env.REDIS_URL, keyPrefix: 'myapp', enablePubSub: true });
299
+ await redis.StartListening();
300
+
301
+ // Every replica listens; the one that owns the request acts on it.
302
+ const stop = await redis.SubscribeToChannel('abort', (raw) => {
303
+ const { requestId, origin } = JSON.parse(raw) as { requestId: string; origin: string };
304
+ if (origin !== replicaId) abortLocally(requestId);
305
+ });
306
+
307
+ // Any replica can ask, and learns whether anyone heard it.
308
+ const receivers = await redis.PublishMessageAndWait('abort', JSON.stringify({ requestId, origin: replicaId }));
309
+ ```
310
+
311
+ Things to know:
312
+
313
+ - **Channels are prefixed.** `'abort'` becomes `myapp:abort`, so applications sharing one Redis under different key prefixes do not hear each other. The name `__pubsub__` is reserved for cache invalidation and is refused.
314
+ - **No echo suppression.** A process subscribed to a channel receives its own messages. Stamp an origin on the payload and check it, as above.
315
+ - **No replay.** Messages published while a subscriber is disconnected are never delivered to it.
267
316
 
268
317
  ## Testing
269
318