@open-mercato/cache-provider-redis-legacy 0.0.0-stage → 0.11.1-develop.8687.1.adb16f62b3
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/.turbo/turbo-build.log +2 -0
- package/build.mjs +10 -0
- package/dist/index.js +444 -0
- package/dist/index.js.map +7 -0
- package/package.json +40 -3
- package/src/index.ts +615 -0
- package/tsconfig.json +10 -0
- package/watch.mjs +6 -0
- package/README.md +0 -3
package/build.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { dirname } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { buildPackage } from '../../scripts/build-package.mjs'
|
|
4
|
+
|
|
5
|
+
const packageDir = dirname(fileURLToPath(import.meta.url))
|
|
6
|
+
|
|
7
|
+
await buildPackage(packageDir, {
|
|
8
|
+
name: 'cache-provider-redis-legacy',
|
|
9
|
+
entryPoints: 'src/**/*.ts',
|
|
10
|
+
})
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
import { CacheDependencyUnavailableError } from "@open-mercato/cache-provider-kit/errors";
|
|
2
|
+
import { getRedisUrlOrThrow, REDIS_WIRE_PROTOCOL } from "@open-mercato/cache-provider-kit/redisConnection";
|
|
3
|
+
import { matchCacheKeyPattern } from "@open-mercato/cache-provider-kit/patterns";
|
|
4
|
+
import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from "@open-mercato/cache-provider-kit/codec";
|
|
5
|
+
const REAP_ORPHANED_TAG_MEMBERS = `
|
|
6
|
+
local removed = 0
|
|
7
|
+
for i = 2, #KEYS do
|
|
8
|
+
if redis.call('EXISTS', KEYS[i]) == 0 then
|
|
9
|
+
removed = removed + redis.call('SREM', KEYS[1], ARGV[i - 1])
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
return removed
|
|
13
|
+
`;
|
|
14
|
+
const REAP_STALE_TAG_MEMBERS = `
|
|
15
|
+
local removed = 0
|
|
16
|
+
for i = 2, #KEYS do
|
|
17
|
+
local current = redis.call('GET', KEYS[i])
|
|
18
|
+
if not current or current == ARGV[(i - 2) * 2 + 2] then
|
|
19
|
+
removed = removed + redis.call('SREM', KEYS[1], ARGV[(i - 2) * 2 + 1])
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
return removed
|
|
23
|
+
`;
|
|
24
|
+
const REAP_CHUNK_SIZE = 256;
|
|
25
|
+
let redisModulePromise = null;
|
|
26
|
+
const redisRegistry = /* @__PURE__ */ new Map();
|
|
27
|
+
function resolveRequire() {
|
|
28
|
+
const nonWebpack = globalThis.__non_webpack_require__;
|
|
29
|
+
if (typeof nonWebpack === "function") return nonWebpack;
|
|
30
|
+
if (typeof require === "function") return require;
|
|
31
|
+
if (typeof module !== "undefined" && typeof module.require === "function") {
|
|
32
|
+
return module.require.bind(module);
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const maybeRequire = Function('return typeof require !== "undefined" ? require : undefined')();
|
|
36
|
+
if (typeof maybeRequire === "function") return maybeRequire;
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
function loadRedisModuleViaRequire() {
|
|
42
|
+
const resolver = resolveRequire();
|
|
43
|
+
if (!resolver) return null;
|
|
44
|
+
try {
|
|
45
|
+
return resolver("ioredis");
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function pickRedisConstructor(mod) {
|
|
51
|
+
const queue = [
|
|
52
|
+
mod?.default,
|
|
53
|
+
mod?.Redis,
|
|
54
|
+
mod
|
|
55
|
+
];
|
|
56
|
+
const seen = /* @__PURE__ */ new Set();
|
|
57
|
+
while (queue.length) {
|
|
58
|
+
const current = queue.shift();
|
|
59
|
+
if (!current || seen.has(current)) continue;
|
|
60
|
+
seen.add(current);
|
|
61
|
+
if (typeof current === "function") return current;
|
|
62
|
+
if (typeof current === "object") {
|
|
63
|
+
queue.push(current.default);
|
|
64
|
+
queue.push(current.Redis);
|
|
65
|
+
queue.push(current.module?.exports);
|
|
66
|
+
queue.push(current.exports);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
async function loadRedisModule() {
|
|
72
|
+
if (!redisModulePromise) {
|
|
73
|
+
redisModulePromise = (async () => {
|
|
74
|
+
const required = loadRedisModuleViaRequire() ?? await import("ioredis");
|
|
75
|
+
return required;
|
|
76
|
+
})().catch((error) => {
|
|
77
|
+
redisModulePromise = null;
|
|
78
|
+
throw new CacheDependencyUnavailableError("redis", "ioredis", error);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return redisModulePromise;
|
|
82
|
+
}
|
|
83
|
+
function retainRedisEntry(key) {
|
|
84
|
+
let entry = redisRegistry.get(key);
|
|
85
|
+
if (!entry) {
|
|
86
|
+
entry = { refs: 0 };
|
|
87
|
+
redisRegistry.set(key, entry);
|
|
88
|
+
}
|
|
89
|
+
entry.refs += 1;
|
|
90
|
+
return entry;
|
|
91
|
+
}
|
|
92
|
+
async function acquireRedisClient(key, entry) {
|
|
93
|
+
if (entry.client) return entry.client;
|
|
94
|
+
if (entry.creating) return entry.creating;
|
|
95
|
+
entry.creating = loadRedisModule().then((mod) => {
|
|
96
|
+
const ctor = pickRedisConstructor(mod);
|
|
97
|
+
if (!ctor) {
|
|
98
|
+
throw new CacheDependencyUnavailableError("redis", "ioredis", new Error("No usable Redis constructor"));
|
|
99
|
+
}
|
|
100
|
+
const client = new ctor(key, { protocol: REDIS_WIRE_PROTOCOL });
|
|
101
|
+
entry.client = client;
|
|
102
|
+
entry.creating = void 0;
|
|
103
|
+
client.once?.("end", () => {
|
|
104
|
+
if (redisRegistry.get(key) === entry && entry.refs === 0) {
|
|
105
|
+
redisRegistry.delete(key);
|
|
106
|
+
} else if (redisRegistry.get(key) === entry) {
|
|
107
|
+
entry.client = void 0;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
return client;
|
|
111
|
+
}).catch((error) => {
|
|
112
|
+
entry.creating = void 0;
|
|
113
|
+
throw error;
|
|
114
|
+
});
|
|
115
|
+
return entry.creating;
|
|
116
|
+
}
|
|
117
|
+
async function releaseRedisEntry(key, entry) {
|
|
118
|
+
entry.refs = Math.max(0, entry.refs - 1);
|
|
119
|
+
if (entry.refs > 0) return;
|
|
120
|
+
redisRegistry.delete(key);
|
|
121
|
+
if (entry.client) {
|
|
122
|
+
try {
|
|
123
|
+
await entry.client.quit();
|
|
124
|
+
} catch {
|
|
125
|
+
} finally {
|
|
126
|
+
entry.client = void 0;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function createRedisStrategy(redisUrl, options) {
|
|
131
|
+
const defaultTtl = options?.defaultTtl;
|
|
132
|
+
const codec = resolveCacheCodecConfig(options);
|
|
133
|
+
const keyPrefix = "cache:";
|
|
134
|
+
const tagPrefix = "tag:";
|
|
135
|
+
const connectionUrl = redisUrl || getRedisUrlOrThrow("CACHE");
|
|
136
|
+
const registryEntry = retainRedisEntry(connectionUrl);
|
|
137
|
+
let redis = registryEntry.client ?? null;
|
|
138
|
+
async function getRedisClient() {
|
|
139
|
+
if (redis) return redis;
|
|
140
|
+
redis = await acquireRedisClient(connectionUrl, registryEntry);
|
|
141
|
+
return redis;
|
|
142
|
+
}
|
|
143
|
+
function getCacheKey(key) {
|
|
144
|
+
return `${keyPrefix}${key}`;
|
|
145
|
+
}
|
|
146
|
+
function getTagKey(tag) {
|
|
147
|
+
return `${tagPrefix}${tag}`;
|
|
148
|
+
}
|
|
149
|
+
async function scanKeys(pattern) {
|
|
150
|
+
const client = await getRedisClient();
|
|
151
|
+
const keys2 = /* @__PURE__ */ new Set();
|
|
152
|
+
let cursor = "0";
|
|
153
|
+
do {
|
|
154
|
+
const [next, page] = await client.scan(cursor, "MATCH", pattern, "COUNT", 256);
|
|
155
|
+
cursor = next;
|
|
156
|
+
for (const key of page) keys2.add(key);
|
|
157
|
+
} while (cursor !== "0");
|
|
158
|
+
return [...keys2];
|
|
159
|
+
}
|
|
160
|
+
function isExpired(entry) {
|
|
161
|
+
if (entry.expiresAt === null) return false;
|
|
162
|
+
return Date.now() > entry.expiresAt;
|
|
163
|
+
}
|
|
164
|
+
const get = async (key, options2) => {
|
|
165
|
+
const client = await getRedisClient();
|
|
166
|
+
const cacheKey = getCacheKey(key);
|
|
167
|
+
const data = await client.getBuffer(cacheKey);
|
|
168
|
+
if (!data) return null;
|
|
169
|
+
try {
|
|
170
|
+
const entry = JSON.parse(decodeCacheText(data));
|
|
171
|
+
if (isExpired(entry)) {
|
|
172
|
+
if (options2?.returnExpired) {
|
|
173
|
+
return entry.value;
|
|
174
|
+
}
|
|
175
|
+
await deleteKey(key);
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
return entry.value;
|
|
179
|
+
} catch {
|
|
180
|
+
await client.del(cacheKey);
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const set = async (key, value, options2) => {
|
|
185
|
+
const client = await getRedisClient();
|
|
186
|
+
const cacheKey = getCacheKey(key);
|
|
187
|
+
const ttl = options2?.ttl ?? defaultTtl;
|
|
188
|
+
const tags = options2?.tags || [];
|
|
189
|
+
const expiresAt = ttl ? Date.now() + ttl : null;
|
|
190
|
+
const entry = {
|
|
191
|
+
key,
|
|
192
|
+
value,
|
|
193
|
+
tags,
|
|
194
|
+
expiresAt,
|
|
195
|
+
createdAt: Date.now()
|
|
196
|
+
};
|
|
197
|
+
const pipeline = client.multi();
|
|
198
|
+
const serialized = encodeCacheText(JSON.stringify(entry), codec);
|
|
199
|
+
if (ttl) {
|
|
200
|
+
pipeline.setex(cacheKey, Math.ceil(ttl / 1e3), serialized);
|
|
201
|
+
} else {
|
|
202
|
+
pipeline.set(cacheKey, serialized);
|
|
203
|
+
}
|
|
204
|
+
for (const tag of tags) {
|
|
205
|
+
pipeline.sadd(getTagKey(tag), key);
|
|
206
|
+
}
|
|
207
|
+
await executePipeline(pipeline);
|
|
208
|
+
};
|
|
209
|
+
const has = async (key) => {
|
|
210
|
+
const client = await getRedisClient();
|
|
211
|
+
const cacheKey = getCacheKey(key);
|
|
212
|
+
const exists = await client.exists(cacheKey);
|
|
213
|
+
if (!exists) return false;
|
|
214
|
+
const data = await client.getBuffer(cacheKey);
|
|
215
|
+
if (!data) return false;
|
|
216
|
+
try {
|
|
217
|
+
const entry = JSON.parse(decodeCacheText(data));
|
|
218
|
+
if (isExpired(entry)) {
|
|
219
|
+
await deleteKey(key);
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
return true;
|
|
223
|
+
} catch {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const deleteKey = async (key) => {
|
|
228
|
+
const client = await getRedisClient();
|
|
229
|
+
const cacheKey = getCacheKey(key);
|
|
230
|
+
const data = await client.getBuffer(cacheKey);
|
|
231
|
+
if (!data) return false;
|
|
232
|
+
try {
|
|
233
|
+
const entry = JSON.parse(decodeCacheText(data));
|
|
234
|
+
const pipeline = client.pipeline();
|
|
235
|
+
for (const tag of entry.tags) {
|
|
236
|
+
pipeline.srem(getTagKey(tag), key);
|
|
237
|
+
}
|
|
238
|
+
pipeline.del(cacheKey);
|
|
239
|
+
await pipeline.exec();
|
|
240
|
+
return true;
|
|
241
|
+
} catch {
|
|
242
|
+
await client.del(cacheKey);
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const batchSize = 256;
|
|
247
|
+
async function executePipeline(pipeline) {
|
|
248
|
+
const result = await pipeline.exec();
|
|
249
|
+
if (!result) throw new Error("[internal] Redis pipeline aborted");
|
|
250
|
+
for (const [error] of result) if (error) throw error;
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
async function readBuffers(client, keys2) {
|
|
254
|
+
const values = await client.mgetBuffer(...keys2);
|
|
255
|
+
if (values.length !== keys2.length || values.some((value) => value !== null && !Buffer.isBuffer(value))) {
|
|
256
|
+
throw new Error("[internal] Unexpected binary Redis batch reply");
|
|
257
|
+
}
|
|
258
|
+
const missingKeys = keys2.filter((_, index) => values[index] === null);
|
|
259
|
+
if (missingKeys.length > 0) {
|
|
260
|
+
const validation = client.pipeline();
|
|
261
|
+
for (const key of missingKeys) validation.getBuffer(key);
|
|
262
|
+
await executePipeline(validation);
|
|
263
|
+
}
|
|
264
|
+
return values;
|
|
265
|
+
}
|
|
266
|
+
async function removeEntries(client, members, data, requestedTags, tagsByMember) {
|
|
267
|
+
const valueKeys = [];
|
|
268
|
+
const groups = /* @__PURE__ */ new Map();
|
|
269
|
+
const orphans = /* @__PURE__ */ new Map();
|
|
270
|
+
const stale = /* @__PURE__ */ new Map();
|
|
271
|
+
for (let index = 0; index < members.length; index++) {
|
|
272
|
+
const buffer = data[index];
|
|
273
|
+
const member = members[index];
|
|
274
|
+
const memberTags = tagsByMember.get(member) ?? [];
|
|
275
|
+
if (!buffer) {
|
|
276
|
+
for (const tagKey of memberTags) {
|
|
277
|
+
const list = orphans.get(tagKey) ?? [];
|
|
278
|
+
list.push(member);
|
|
279
|
+
orphans.set(tagKey, list);
|
|
280
|
+
}
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
let entryTags;
|
|
284
|
+
try {
|
|
285
|
+
const entry = JSON.parse(decodeCacheText(buffer));
|
|
286
|
+
if (Array.isArray(entry.tags) && entry.tags.every((tag) => typeof tag === "string")) {
|
|
287
|
+
entryTags = new Set(entry.tags);
|
|
288
|
+
}
|
|
289
|
+
} catch {
|
|
290
|
+
}
|
|
291
|
+
if (entryTags) {
|
|
292
|
+
for (const tagKey of memberTags) {
|
|
293
|
+
if (entryTags.has(tagKey.slice(tagPrefix.length))) continue;
|
|
294
|
+
const list = stale.get(tagKey) ?? [];
|
|
295
|
+
list.push({ member, buffer });
|
|
296
|
+
stale.set(tagKey, list);
|
|
297
|
+
}
|
|
298
|
+
if (![...entryTags].some((tag) => requestedTags.has(tag))) continue;
|
|
299
|
+
for (const tag of entryTags) {
|
|
300
|
+
const tagKey = getTagKey(tag);
|
|
301
|
+
const list = groups.get(tagKey) ?? [];
|
|
302
|
+
list.push(member);
|
|
303
|
+
groups.set(tagKey, list);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
valueKeys.push(getCacheKey(member));
|
|
307
|
+
}
|
|
308
|
+
if (!valueKeys.length && !orphans.size && !stale.size) return 0;
|
|
309
|
+
const pipeline = client.pipeline();
|
|
310
|
+
for (const [tagKey, list] of groups) pipeline.srem(tagKey, ...list);
|
|
311
|
+
if (valueKeys.length) pipeline.del(...valueKeys);
|
|
312
|
+
for (const [tagKey, list] of orphans) {
|
|
313
|
+
for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
|
|
314
|
+
const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE);
|
|
315
|
+
const keys2 = [tagKey, ...chunk.map(getCacheKey)];
|
|
316
|
+
pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys2.length, ...keys2, ...chunk);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
for (const [tagKey, list] of stale) {
|
|
320
|
+
for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
|
|
321
|
+
const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE);
|
|
322
|
+
const keys2 = [tagKey, ...chunk.map(({ member }) => getCacheKey(member))];
|
|
323
|
+
pipeline.eval(REAP_STALE_TAG_MEMBERS, keys2.length, ...keys2, ...chunk.flatMap(({ member, buffer }) => [member, buffer]));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
await executePipeline(pipeline);
|
|
327
|
+
return valueKeys.length;
|
|
328
|
+
}
|
|
329
|
+
const deleteByTags = async (tags) => {
|
|
330
|
+
const client = await getRedisClient();
|
|
331
|
+
const requestedTags = new Set(tags);
|
|
332
|
+
const keysToDelete = /* @__PURE__ */ new Set();
|
|
333
|
+
const tagsByMember = /* @__PURE__ */ new Map();
|
|
334
|
+
const tagPipeline = client.pipeline();
|
|
335
|
+
const uniqueTags = [...requestedTags];
|
|
336
|
+
for (const tag of uniqueTags) tagPipeline.smembers(getTagKey(tag));
|
|
337
|
+
const tagReplies = uniqueTags.length ? await executePipeline(tagPipeline) : [];
|
|
338
|
+
for (let index = 0; index < uniqueTags.length; index++) {
|
|
339
|
+
const keys2 = tagReplies[index][1];
|
|
340
|
+
const tagKey = getTagKey(uniqueTags[index]);
|
|
341
|
+
for (const key of keys2) {
|
|
342
|
+
keysToDelete.add(key);
|
|
343
|
+
const memberTags = tagsByMember.get(key) ?? [];
|
|
344
|
+
memberTags.push(tagKey);
|
|
345
|
+
tagsByMember.set(key, memberTags);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
let deleted = 0;
|
|
349
|
+
const members = [...keysToDelete];
|
|
350
|
+
for (let offset = 0; offset < members.length; offset += batchSize) {
|
|
351
|
+
const chunk = members.slice(offset, offset + batchSize);
|
|
352
|
+
const data = await readBuffers(client, chunk.map(getCacheKey));
|
|
353
|
+
deleted += await removeEntries(client, chunk, data, requestedTags, tagsByMember);
|
|
354
|
+
}
|
|
355
|
+
return deleted;
|
|
356
|
+
};
|
|
357
|
+
const clear = async () => {
|
|
358
|
+
const client = await getRedisClient();
|
|
359
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`);
|
|
360
|
+
const tagKeys = await scanKeys(`${tagPrefix}*`);
|
|
361
|
+
if (cacheKeys.length === 0 && tagKeys.length === 0) return 0;
|
|
362
|
+
const physicalKeys = [...cacheKeys, ...tagKeys];
|
|
363
|
+
for (let offset = 0; offset < physicalKeys.length; offset += batchSize) {
|
|
364
|
+
const chunk = physicalKeys.slice(offset, offset + batchSize);
|
|
365
|
+
const pipeline = client.pipeline();
|
|
366
|
+
for (const key of chunk) pipeline.del(key);
|
|
367
|
+
await executePipeline(pipeline);
|
|
368
|
+
}
|
|
369
|
+
return cacheKeys.length;
|
|
370
|
+
};
|
|
371
|
+
const keys = async (pattern) => {
|
|
372
|
+
const client = await getRedisClient();
|
|
373
|
+
const searchPattern = pattern ? `${keyPrefix}${pattern}` : `${keyPrefix}*`;
|
|
374
|
+
const cacheKeys = await scanKeys(searchPattern);
|
|
375
|
+
const result = cacheKeys.map((key) => key.substring(keyPrefix.length));
|
|
376
|
+
if (!pattern) return result;
|
|
377
|
+
return result.filter((key) => matchCacheKeyPattern(key, pattern));
|
|
378
|
+
};
|
|
379
|
+
const stats = async () => {
|
|
380
|
+
const client = await getRedisClient();
|
|
381
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`);
|
|
382
|
+
let expired = 0;
|
|
383
|
+
for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
|
|
384
|
+
const data = await readBuffers(client, cacheKeys.slice(offset, offset + batchSize));
|
|
385
|
+
for (const buffer of data) {
|
|
386
|
+
if (!buffer) continue;
|
|
387
|
+
try {
|
|
388
|
+
if (isExpired(JSON.parse(decodeCacheText(buffer)))) expired++;
|
|
389
|
+
} catch {
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return { size: cacheKeys.length, expired };
|
|
394
|
+
};
|
|
395
|
+
const cleanup = async () => {
|
|
396
|
+
const client = await getRedisClient();
|
|
397
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`);
|
|
398
|
+
let removed = 0;
|
|
399
|
+
for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
|
|
400
|
+
const chunk = cacheKeys.slice(offset, offset + batchSize);
|
|
401
|
+
const data = await readBuffers(client, chunk);
|
|
402
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
403
|
+
const buffer = data[index];
|
|
404
|
+
if (!buffer) continue;
|
|
405
|
+
try {
|
|
406
|
+
if (isExpired(JSON.parse(decodeCacheText(buffer)))) {
|
|
407
|
+
await deleteKey(chunk[index].substring(keyPrefix.length));
|
|
408
|
+
removed++;
|
|
409
|
+
}
|
|
410
|
+
} catch {
|
|
411
|
+
await client.del(chunk[index]);
|
|
412
|
+
removed++;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return removed;
|
|
417
|
+
};
|
|
418
|
+
const close = async () => {
|
|
419
|
+
await releaseRedisEntry(connectionUrl, registryEntry);
|
|
420
|
+
redis = null;
|
|
421
|
+
};
|
|
422
|
+
const healthcheck = async () => {
|
|
423
|
+
const client = await getRedisClient();
|
|
424
|
+
await client.ping();
|
|
425
|
+
};
|
|
426
|
+
return {
|
|
427
|
+
get,
|
|
428
|
+
set,
|
|
429
|
+
has,
|
|
430
|
+
delete: deleteKey,
|
|
431
|
+
deleteByTags,
|
|
432
|
+
clear,
|
|
433
|
+
keys,
|
|
434
|
+
stats,
|
|
435
|
+
healthcheck,
|
|
436
|
+
cleanup,
|
|
437
|
+
close
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
export {
|
|
441
|
+
createRedisStrategy,
|
|
442
|
+
pickRedisConstructor
|
|
443
|
+
};
|
|
444
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'\nimport { CacheDependencyUnavailableError } from '@open-mercato/cache-provider-kit/errors'\nimport { getRedisUrlOrThrow, REDIS_WIRE_PROTOCOL } from '@open-mercato/cache-provider-kit/redisConnection'\nimport type { RedisProtocolVersion } from '@open-mercato/cache-provider-kit/redisConnection'\nimport { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'\nimport { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '@open-mercato/cache-provider-kit/codec'\nimport type { CacheCodecOptions } from '@open-mercato/cache-provider-kit/codec'\n\ntype RedisPipeline = {\n getBuffer(key: string): RedisPipeline\n smembers(key: string): RedisPipeline\n set(key: string, value: string | Buffer): RedisPipeline\n setex(key: string, ttlSeconds: number, value: string | Buffer): RedisPipeline\n sadd(key: string, value: string): RedisPipeline\n srem(key: string, ...members: string[]): RedisPipeline\n del(...keys: string[]): RedisPipeline\n eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): RedisPipeline\n exec(): Promise<unknown>\n}\n\ntype RedisClient = {\n ping(): Promise<string>\n get(key: string): Promise<string | null>\n getBuffer(key: string): Promise<Buffer | null>\n set(key: string, value: string | Buffer): Promise<unknown>\n setex(key: string, ttlSeconds: number, value: string | Buffer): Promise<unknown>\n del(...keys: string[]): Promise<number>\n exists(key: string): Promise<number>\n scan(cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', limit: number): Promise<[string, string[]]>\n smembers(key: string): Promise<string[]>\n mgetBuffer(...keys: string[]): Promise<(Buffer | null)[]>\n srem(key: string, ...members: string[]): Promise<number>\n eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): Promise<unknown>\n pipeline(): RedisPipeline\n multi(): RedisPipeline\n quit(): Promise<void>\n once?(event: 'end', listener: () => void): void\n}\n\ntype RedisConstructor = new (url?: string, options?: { protocol?: RedisProtocolVersion }) => RedisClient\ntype PossibleRedisModule = unknown\n\ntype RequireFn = (id: string) => unknown\n\n/**\n * Reaps orphaned members from ONE tag set atomically.\n *\n * `KEYS[1]` is the tag key and `KEYS[2..]` are the candidate value keys, with\n * `ARGV[1..]` the member names aligned to them. Every key the script touches is\n * declared in `KEYS` so it stays valid against a slot-aware deployment.\n *\n * The `EXISTS` check and the `SREM` run in one atomic step, which is the whole\n * point: a member may only be dropped while its value key is genuinely absent.\n * A concurrent `set()` either lands first (`EXISTS` is 1, so the member is left\n * alone) or lands after (its own `sadd` re-adds the member). Either ordering\n * leaves a live key indexed.\n *\n * Deliberately single-tag. Pairing every orphan with every requested tag would\n * make the work quadratic in the tag count \u2014 and because a script blocks the\n * server for its whole run, that lands as a stall rather than as throughput.\n * Callers reap per tag using the membership each `smembers` actually returned.\n */\nconst REAP_ORPHANED_TAG_MEMBERS = `\nlocal removed = 0\nfor i = 2, #KEYS do\n if redis.call('EXISTS', KEYS[i]) == 0 then\n removed = removed + redis.call('SREM', KEYS[1], ARGV[i - 1])\n end\nend\nreturn removed\n`\n\n// The application decoded these observed buffers and found that their current\n// tags exclude this index. Compare bytes atomically before removing membership:\n// a concurrent retag may have made the index valid again. Compression stays opaque.\n// ARGV contains (member, observed buffer) pairs aligned with KEYS[2..].\nconst REAP_STALE_TAG_MEMBERS = `\nlocal removed = 0\nfor i = 2, #KEYS do\n local current = redis.call('GET', KEYS[i])\n if not current or current == ARGV[(i - 2) * 2 + 2] then\n removed = removed + redis.call('SREM', KEYS[1], ARGV[(i - 2) * 2 + 1])\n end\nend\nreturn removed\n`\n\n/** Bounds members per script; payload bytes and execution time remain workload dependent. */\nconst REAP_CHUNK_SIZE = 256\n\n/**\n * Redis cache strategy with tag support\n * Persistent across process restarts, can be shared across multiple instances\n *\n * Uses Redis data structures:\n * - Hash for storing cache entries: cache:{key} -> {value, tags, expiresAt, createdAt}\n * - Sets for tag index: tag:{tag} -> Set of keys\n */\nlet redisModulePromise: Promise<PossibleRedisModule> | null = null\ntype RedisRegistryEntry = { client?: RedisClient; creating?: Promise<RedisClient>; refs: number }\nconst redisRegistry = new Map<string, RedisRegistryEntry>()\n\nfunction resolveRequire(): RequireFn | null {\n const nonWebpack = (globalThis as { __non_webpack_require__?: unknown }).__non_webpack_require__\n if (typeof nonWebpack === 'function') return nonWebpack as RequireFn\n if (typeof require === 'function') return require as RequireFn\n if (typeof module !== 'undefined' && typeof module.require === 'function') {\n return module.require.bind(module)\n }\n try {\n const maybeRequire = Function('return typeof require !== \"undefined\" ? require : undefined')()\n if (typeof maybeRequire === 'function') return maybeRequire as RequireFn\n } catch {\n // ignore\n }\n return null\n}\n\nfunction loadRedisModuleViaRequire(): PossibleRedisModule | null {\n const resolver = resolveRequire()\n if (!resolver) return null\n try {\n return resolver('ioredis') as PossibleRedisModule\n } catch {\n return null\n }\n}\n\nexport function pickRedisConstructor(mod: PossibleRedisModule): RedisConstructor | null {\n // `mod` goes last: a bundler-wrapped ESM namespace for a CJS module (e.g.\n // Turbopack's `createNS`) can itself be a callable-but-not-constructible\n // wrapper around the real class, while `.default`/`.Redis` still point at\n // the real class. Checking them first costs nothing for a plain CJS\n // `require()` or a real Node ESM namespace, where they already agree with\n // `mod`.\n const queue: unknown[] = [\n (mod as { default?: unknown } | null | undefined)?.default,\n (mod as { Redis?: unknown } | null | undefined)?.Redis,\n mod,\n ]\n const seen = new Set<unknown>()\n while (queue.length) {\n const current = queue.shift()\n if (!current || seen.has(current)) continue\n seen.add(current)\n if (typeof current === 'function') return current as RedisConstructor\n if (typeof current === 'object') {\n queue.push((current as { default?: unknown }).default)\n queue.push((current as { Redis?: unknown }).Redis)\n queue.push((current as { module?: { exports?: unknown } }).module?.exports)\n queue.push((current as { exports?: unknown }).exports)\n }\n }\n return null\n}\n\nasync function loadRedisModule(): Promise<PossibleRedisModule> {\n if (!redisModulePromise) {\n redisModulePromise = (async () => {\n const required = loadRedisModuleViaRequire() ?? (await import('ioredis'))\n return required as PossibleRedisModule\n })().catch((error) => {\n redisModulePromise = null\n throw new CacheDependencyUnavailableError('redis', 'ioredis', error)\n })\n }\n return redisModulePromise\n}\n\nfunction retainRedisEntry(key: string): RedisRegistryEntry {\n let entry = redisRegistry.get(key)\n if (!entry) {\n entry = { refs: 0 }\n redisRegistry.set(key, entry)\n }\n entry.refs += 1\n return entry\n}\n\nasync function acquireRedisClient(key: string, entry: RedisRegistryEntry): Promise<RedisClient> {\n if (entry.client) return entry.client\n if (entry.creating) return entry.creating\n entry.creating = loadRedisModule()\n .then((mod) => {\n const ctor = pickRedisConstructor(mod)\n if (!ctor) {\n throw new CacheDependencyUnavailableError('redis', 'ioredis', new Error('No usable Redis constructor'))\n }\n const client = new ctor(key, { protocol: REDIS_WIRE_PROTOCOL })\n entry.client = client\n entry.creating = undefined\n client.once?.('end', () => {\n if (redisRegistry.get(key) === entry && entry.refs === 0) {\n redisRegistry.delete(key)\n } else if (redisRegistry.get(key) === entry) {\n entry.client = undefined\n }\n })\n return client\n })\n .catch((error) => {\n entry.creating = undefined\n throw error\n })\n return entry.creating\n}\n\nasync function releaseRedisEntry(key: string, entry: RedisRegistryEntry): Promise<void> {\n entry.refs = Math.max(0, entry.refs - 1)\n if (entry.refs > 0) return\n redisRegistry.delete(key)\n if (entry.client) {\n try {\n await entry.client.quit()\n } catch {\n // ignore shutdown errors\n } finally {\n entry.client = undefined\n }\n }\n}\n\nexport function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?: number } & CacheCodecOptions): CacheStrategy {\n const defaultTtl = options?.defaultTtl\n const codec = resolveCacheCodecConfig(options)\n const keyPrefix = 'cache:'\n const tagPrefix = 'tag:'\n const connectionUrl = redisUrl || getRedisUrlOrThrow('CACHE')\n const registryEntry = retainRedisEntry(connectionUrl)\n let redis: RedisClient | null = registryEntry.client ?? null\n\n async function getRedisClient(): Promise<RedisClient> {\n if (redis) return redis\n\n redis = await acquireRedisClient(connectionUrl, registryEntry)\n return redis\n }\n\n function getCacheKey(key: string): string {\n return `${keyPrefix}${key}`\n }\n\n function getTagKey(tag: string): string {\n return `${tagPrefix}${tag}`\n }\n\n // SCAN may return duplicate keys and empty pages before the cursor reaches 0.\n // COUNT is a work hint, not a strict page-size or latency bound.\n async function scanKeys(pattern: string): Promise<string[]> {\n const client = await getRedisClient()\n const keys = new Set<string>()\n let cursor = '0'\n do {\n const [next, page] = await client.scan(cursor, 'MATCH', pattern, 'COUNT', 256)\n cursor = next\n for (const key of page) keys.add(key)\n } while (cursor !== '0')\n return [...keys]\n }\n\n function isExpired(entry: CacheEntry): boolean {\n if (entry.expiresAt === null) return false\n return Date.now() > entry.expiresAt\n }\n\n const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {\n const client = await getRedisClient()\n const cacheKey = getCacheKey(key)\n const data = await client.getBuffer(cacheKey)\n\n if (!data) return null\n\n try {\n const entry: CacheEntry = JSON.parse(decodeCacheText(data))\n\n if (isExpired(entry)) {\n if (options?.returnExpired) {\n return entry.value\n }\n // Clean up expired entry\n await deleteKey(key)\n return null\n }\n\n return entry.value\n } catch {\n // Invalid JSON, remove it\n await client.del(cacheKey)\n return null\n }\n }\n\n const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {\n const client = await getRedisClient()\n const cacheKey = getCacheKey(key)\n\n const ttl = options?.ttl ?? defaultTtl\n const tags = options?.tags || []\n const expiresAt = ttl ? Date.now() + ttl : null\n\n const entry: CacheEntry = {\n key,\n value,\n tags,\n expiresAt,\n createdAt: Date.now(),\n }\n\n // Old memberships are reconciled by deleteByTags using current entry tags.\n // ioredis sends MULTI, the commands and EXEC together, without a pre-read.\n const pipeline = client.multi()\n\n // Store the entry\n const serialized = encodeCacheText(JSON.stringify(entry), codec)\n if (ttl) {\n pipeline.setex(cacheKey, Math.ceil(ttl / 1000), serialized)\n } else {\n pipeline.set(cacheKey, serialized)\n }\n\n // Add to tag index\n for (const tag of tags) {\n pipeline.sadd(getTagKey(tag), key)\n }\n\n await executePipeline(pipeline)\n }\n\n const has = async (key: string): Promise<boolean> => {\n const client = await getRedisClient()\n const cacheKey = getCacheKey(key)\n const exists = await client.exists(cacheKey)\n\n if (!exists) return false\n\n // Check if expired\n const data = await client.getBuffer(cacheKey)\n if (!data) return false\n\n try {\n const entry: CacheEntry = JSON.parse(decodeCacheText(data))\n if (isExpired(entry)) {\n await deleteKey(key)\n return false\n }\n return true\n } catch {\n return false\n }\n }\n\n const deleteKey = async (key: string): Promise<boolean> => {\n const client = await getRedisClient()\n const cacheKey = getCacheKey(key)\n\n // Get entry to remove from tag index\n const data = await client.getBuffer(cacheKey)\n if (!data) return false\n\n try {\n const entry: CacheEntry = JSON.parse(decodeCacheText(data))\n const pipeline = client.pipeline()\n\n // Remove from tag index\n for (const tag of entry.tags) {\n pipeline.srem(getTagKey(tag), key)\n }\n\n // Delete the cache entry\n pipeline.del(cacheKey)\n\n await pipeline.exec()\n return true\n } catch {\n // Just delete the key if we can't parse it\n await client.del(cacheKey)\n return true\n }\n }\n\n\n // Experimental entry-count bound; reply bytes and tag fanout remain workload dependent.\n const batchSize = 256\n\n async function executePipeline(pipeline: RedisPipeline): Promise<[Error | null, unknown][]> {\n const result = await pipeline.exec() as [Error | null, unknown][] | null\n if (!result) throw new Error('[internal] Redis pipeline aborted')\n for (const [error] of result) if (error) throw error\n return result\n }\n\n async function readBuffers(client: RedisClient, keys: string[]): Promise<(Buffer | null)[]> {\n const values = await client.mgetBuffer(...keys)\n if (values.length !== keys.length || values.some((value) => value !== null && !Buffer.isBuffer(value))) {\n throw new Error('[internal] Unexpected binary Redis batch reply')\n }\n const missingKeys = keys.filter((_, index) => values[index] === null)\n if (missingKeys.length > 0) {\n // Detect WRONGTYPE without consuming a value rebuilt after the original MISS.\n const validation = client.pipeline()\n for (const key of missingKeys) validation.getBuffer(key)\n await executePipeline(validation)\n }\n return values as (Buffer | null)[]\n }\n\n async function removeEntries(\n client: RedisClient,\n members: string[],\n data: (Buffer | null)[],\n requestedTags: Set<string>,\n tagsByMember: Map<string, string[]>,\n ): Promise<number> {\n const valueKeys: string[] = []\n const groups = new Map<string, string[]>()\n const orphans = new Map<string, string[]>()\n const stale = new Map<string, { member: string; buffer: Buffer }[]>()\n for (let index = 0; index < members.length; index++) {\n const buffer = data[index]\n const member = members[index]\n const memberTags = tagsByMember.get(member) ?? []\n if (!buffer) {\n for (const tagKey of memberTags) {\n const list = orphans.get(tagKey) ?? []\n list.push(member)\n orphans.set(tagKey, list)\n }\n continue\n }\n\n let entryTags: Set<string> | undefined\n try {\n const entry: CacheEntry = JSON.parse(decodeCacheText(buffer))\n if (Array.isArray(entry.tags) && entry.tags.every((tag) => typeof tag === 'string')) {\n entryTags = new Set(entry.tags)\n }\n } catch { /* Corrupt entries are deleted, as with deleteKey(). */ }\n if (entryTags) {\n for (const tagKey of memberTags) {\n if (entryTags.has(tagKey.slice(tagPrefix.length))) continue\n const list = stale.get(tagKey) ?? []\n list.push({ member, buffer })\n stale.set(tagKey, list)\n }\n if (![...entryTags].some((tag) => requestedTags.has(tag))) continue\n for (const tag of entryTags) {\n const tagKey = getTagKey(tag)\n const list = groups.get(tagKey) ?? []\n list.push(member)\n groups.set(tagKey, list)\n }\n }\n valueKeys.push(getCacheKey(member))\n }\n if (!valueKeys.length && !orphans.size && !stale.size) return 0\n const pipeline = client.pipeline()\n for (const [tagKey, list] of groups) pipeline.srem(tagKey, ...list)\n if (valueKeys.length) pipeline.del(...valueKeys)\n for (const [tagKey, list] of orphans) {\n for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {\n const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)\n const keys = [tagKey, ...chunk.map(getCacheKey)]\n pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)\n }\n }\n for (const [tagKey, list] of stale) {\n for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {\n const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)\n const keys = [tagKey, ...chunk.map(({ member }) => getCacheKey(member))]\n pipeline.eval(REAP_STALE_TAG_MEMBERS, keys.length, ...keys, ...chunk.flatMap(({ member, buffer }) => [member, buffer]))\n }\n }\n await executePipeline(pipeline)\n return valueKeys.length\n }\n\n const deleteByTags = async (tags: string[]): Promise<number> => {\n const client = await getRedisClient()\n const requestedTags = new Set(tags)\n const keysToDelete = new Set<string>()\n // Keep only actual memberships. Each read batch reconciles its indexes so\n // observed value buffers are released before reading the next batch.\n const tagsByMember = new Map<string, string[]>()\n\n // Collect all keys that have any of the specified tags\n const tagPipeline = client.pipeline()\n const uniqueTags = [...requestedTags]\n for (const tag of uniqueTags) tagPipeline.smembers(getTagKey(tag))\n const tagReplies = uniqueTags.length ? await executePipeline(tagPipeline) : []\n for (let index = 0; index < uniqueTags.length; index++) {\n const keys = tagReplies[index][1] as string[]\n const tagKey = getTagKey(uniqueTags[index])\n for (const key of keys) {\n keysToDelete.add(key)\n const memberTags = tagsByMember.get(key) ?? []\n memberTags.push(tagKey)\n tagsByMember.set(key, memberTags)\n }\n }\n\n // Delete all collected keys\n let deleted = 0\n const members = [...keysToDelete]\n for (let offset = 0; offset < members.length; offset += batchSize) {\n const chunk = members.slice(offset, offset + batchSize)\n const data = await readBuffers(client, chunk.map(getCacheKey))\n deleted += await removeEntries(client, chunk, data, requestedTags, tagsByMember)\n }\n\n return deleted\n }\n\n const clear = async (): Promise<number> => {\n const client = await getRedisClient()\n\n // Get all cache keys\n const cacheKeys = await scanKeys(`${keyPrefix}*`)\n const tagKeys = await scanKeys(`${tagPrefix}*`)\n\n if (cacheKeys.length === 0 && tagKeys.length === 0) return 0\n\n const physicalKeys = [...cacheKeys, ...tagKeys]\n for (let offset = 0; offset < physicalKeys.length; offset += batchSize) {\n const chunk = physicalKeys.slice(offset, offset + batchSize)\n const pipeline = client.pipeline()\n for (const key of chunk) pipeline.del(key)\n await executePipeline(pipeline)\n }\n return cacheKeys.length\n }\n\n const keys = async (pattern?: string): Promise<string[]> => {\n const client = await getRedisClient()\n const searchPattern = pattern\n ? `${keyPrefix}${pattern}`\n : `${keyPrefix}*`\n\n const cacheKeys = await scanKeys(searchPattern)\n\n // Remove prefix from keys\n const result = cacheKeys.map((key: string) => key.substring(keyPrefix.length))\n\n if (!pattern) return result\n\n // Apply pattern matching (Redis KEYS command uses glob pattern, but we want our pattern)\n return result.filter((key: string) => matchCacheKeyPattern(key, pattern))\n }\n\n const stats = async (): Promise<{ size: number; expired: number }> => {\n const client = await getRedisClient()\n const cacheKeys = await scanKeys(`${keyPrefix}*`)\n\n let expired = 0\n for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {\n const data = await readBuffers(client, cacheKeys.slice(offset, offset + batchSize))\n for (const buffer of data) {\n if (!buffer) continue\n try { if (isExpired(JSON.parse(decodeCacheText(buffer)))) expired++ }\n catch { /* stats ignores corrupt entries, as before. */ }\n }\n }\n\n return { size: cacheKeys.length, expired }\n }\n\n const cleanup = async (): Promise<number> => {\n const client = await getRedisClient()\n const cacheKeys = await scanKeys(`${keyPrefix}*`)\n\n let removed = 0\n for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {\n const chunk = cacheKeys.slice(offset, offset + batchSize)\n const data = await readBuffers(client, chunk)\n for (let index = 0; index < chunk.length; index++) {\n const buffer = data[index]\n if (!buffer) continue\n try {\n if (isExpired(JSON.parse(decodeCacheText(buffer)))) {\n await deleteKey(chunk[index].substring(keyPrefix.length))\n removed++\n }\n } catch {\n await client.del(chunk[index])\n removed++\n }\n }\n }\n\n return removed\n }\n\n const close = async (): Promise<void> => {\n await releaseRedisEntry(connectionUrl, registryEntry)\n redis = null\n }\n\n const healthcheck = async (): Promise<void> => {\n const client = await getRedisClient()\n await client.ping()\n }\n\n return {\n get,\n set,\n has,\n delete: deleteKey,\n deleteByTags,\n clear,\n keys,\n stats,\n healthcheck,\n cleanup,\n close,\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,uCAAuC;AAChD,SAAS,oBAAoB,2BAA2B;AAExD,SAAS,4BAA4B;AACrC,SAAS,iBAAiB,iBAAiB,+BAA+B;AAyD1E,MAAM,4BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAclC,MAAM,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAY/B,MAAM,kBAAkB;AAUxB,IAAI,qBAA0D;AAE9D,MAAM,gBAAgB,oBAAI,IAAgC;AAE1D,SAAS,iBAAmC;AAC1C,QAAM,aAAc,WAAqD;AACzE,MAAI,OAAO,eAAe,WAAY,QAAO;AAC7C,MAAI,OAAO,YAAY,WAAY,QAAO;AAC1C,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,YAAY,YAAY;AACzE,WAAO,OAAO,QAAQ,KAAK,MAAM;AAAA,EACnC;AACA,MAAI;AACF,UAAM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,UAAU,KAAK,MAAM,gBAAgB,MAAM,CAAC,CAAC,GAAG;AAClD,kBAAM,UAAU,MAAM,KAAK,EAAE,UAAU,UAAU,MAAM,CAAC;AACxD;AAAA,UACF;AAAA,QACF,QAAQ;AACN,gBAAM,OAAO,IAAI,MAAM,KAAK,CAAC;AAC7B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,YAA2B;AACvC,UAAM,kBAAkB,eAAe,aAAa;AACpD,YAAQ;AAAA,EACV;AAEA,QAAM,cAAc,YAA2B;AAC7C,UAAM,SAAS,MAAM,eAAe;AACpC,UAAM,OAAO,KAAK;AAAA,EACpB;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["keys", "options"]
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/cache-provider-redis-legacy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.11.1-develop.8687.1.adb16f62b3",
|
|
4
|
+
"description": "Stock redis cache factory for Open Mercato",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "node build.mjs",
|
|
16
|
+
"watch": "node watch.mjs",
|
|
17
|
+
"typecheck": "tsc --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@types/node": "^26.4.0",
|
|
21
|
+
"typescript": "7.0.2"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "https://github.com/open-mercato/open-mercato",
|
|
29
|
+
"directory": "packages/cache-provider-redis-legacy"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@open-mercato/cache-provider-kit": "0.11.1-develop.8687.1.adb16f62b3"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"ioredis": "^5.0.0 || ^6.0.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"ioredis": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"stableVersion": "0.11.0"
|
|
6
43
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import type { CacheStrategy, CacheEntry, CacheGetOptions, CacheSetOptions, CacheValue } from '@open-mercato/cache-provider-kit'
|
|
2
|
+
import { CacheDependencyUnavailableError } from '@open-mercato/cache-provider-kit/errors'
|
|
3
|
+
import { getRedisUrlOrThrow, REDIS_WIRE_PROTOCOL } from '@open-mercato/cache-provider-kit/redisConnection'
|
|
4
|
+
import type { RedisProtocolVersion } from '@open-mercato/cache-provider-kit/redisConnection'
|
|
5
|
+
import { matchCacheKeyPattern } from '@open-mercato/cache-provider-kit/patterns'
|
|
6
|
+
import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from '@open-mercato/cache-provider-kit/codec'
|
|
7
|
+
import type { CacheCodecOptions } from '@open-mercato/cache-provider-kit/codec'
|
|
8
|
+
|
|
9
|
+
type RedisPipeline = {
|
|
10
|
+
getBuffer(key: string): RedisPipeline
|
|
11
|
+
smembers(key: string): RedisPipeline
|
|
12
|
+
set(key: string, value: string | Buffer): RedisPipeline
|
|
13
|
+
setex(key: string, ttlSeconds: number, value: string | Buffer): RedisPipeline
|
|
14
|
+
sadd(key: string, value: string): RedisPipeline
|
|
15
|
+
srem(key: string, ...members: string[]): RedisPipeline
|
|
16
|
+
del(...keys: string[]): RedisPipeline
|
|
17
|
+
eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): RedisPipeline
|
|
18
|
+
exec(): Promise<unknown>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type RedisClient = {
|
|
22
|
+
ping(): Promise<string>
|
|
23
|
+
get(key: string): Promise<string | null>
|
|
24
|
+
getBuffer(key: string): Promise<Buffer | null>
|
|
25
|
+
set(key: string, value: string | Buffer): Promise<unknown>
|
|
26
|
+
setex(key: string, ttlSeconds: number, value: string | Buffer): Promise<unknown>
|
|
27
|
+
del(...keys: string[]): Promise<number>
|
|
28
|
+
exists(key: string): Promise<number>
|
|
29
|
+
scan(cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', limit: number): Promise<[string, string[]]>
|
|
30
|
+
smembers(key: string): Promise<string[]>
|
|
31
|
+
mgetBuffer(...keys: string[]): Promise<(Buffer | null)[]>
|
|
32
|
+
srem(key: string, ...members: string[]): Promise<number>
|
|
33
|
+
eval(script: string, numKeys: number, ...args: (string | number | Buffer)[]): Promise<unknown>
|
|
34
|
+
pipeline(): RedisPipeline
|
|
35
|
+
multi(): RedisPipeline
|
|
36
|
+
quit(): Promise<void>
|
|
37
|
+
once?(event: 'end', listener: () => void): void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type RedisConstructor = new (url?: string, options?: { protocol?: RedisProtocolVersion }) => RedisClient
|
|
41
|
+
type PossibleRedisModule = unknown
|
|
42
|
+
|
|
43
|
+
type RequireFn = (id: string) => unknown
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Reaps orphaned members from ONE tag set atomically.
|
|
47
|
+
*
|
|
48
|
+
* `KEYS[1]` is the tag key and `KEYS[2..]` are the candidate value keys, with
|
|
49
|
+
* `ARGV[1..]` the member names aligned to them. Every key the script touches is
|
|
50
|
+
* declared in `KEYS` so it stays valid against a slot-aware deployment.
|
|
51
|
+
*
|
|
52
|
+
* The `EXISTS` check and the `SREM` run in one atomic step, which is the whole
|
|
53
|
+
* point: a member may only be dropped while its value key is genuinely absent.
|
|
54
|
+
* A concurrent `set()` either lands first (`EXISTS` is 1, so the member is left
|
|
55
|
+
* alone) or lands after (its own `sadd` re-adds the member). Either ordering
|
|
56
|
+
* leaves a live key indexed.
|
|
57
|
+
*
|
|
58
|
+
* Deliberately single-tag. Pairing every orphan with every requested tag would
|
|
59
|
+
* make the work quadratic in the tag count — and because a script blocks the
|
|
60
|
+
* server for its whole run, that lands as a stall rather than as throughput.
|
|
61
|
+
* Callers reap per tag using the membership each `smembers` actually returned.
|
|
62
|
+
*/
|
|
63
|
+
const REAP_ORPHANED_TAG_MEMBERS = `
|
|
64
|
+
local removed = 0
|
|
65
|
+
for i = 2, #KEYS do
|
|
66
|
+
if redis.call('EXISTS', KEYS[i]) == 0 then
|
|
67
|
+
removed = removed + redis.call('SREM', KEYS[1], ARGV[i - 1])
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
return removed
|
|
71
|
+
`
|
|
72
|
+
|
|
73
|
+
// The application decoded these observed buffers and found that their current
|
|
74
|
+
// tags exclude this index. Compare bytes atomically before removing membership:
|
|
75
|
+
// a concurrent retag may have made the index valid again. Compression stays opaque.
|
|
76
|
+
// ARGV contains (member, observed buffer) pairs aligned with KEYS[2..].
|
|
77
|
+
const REAP_STALE_TAG_MEMBERS = `
|
|
78
|
+
local removed = 0
|
|
79
|
+
for i = 2, #KEYS do
|
|
80
|
+
local current = redis.call('GET', KEYS[i])
|
|
81
|
+
if not current or current == ARGV[(i - 2) * 2 + 2] then
|
|
82
|
+
removed = removed + redis.call('SREM', KEYS[1], ARGV[(i - 2) * 2 + 1])
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
return removed
|
|
86
|
+
`
|
|
87
|
+
|
|
88
|
+
/** Bounds members per script; payload bytes and execution time remain workload dependent. */
|
|
89
|
+
const REAP_CHUNK_SIZE = 256
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Redis cache strategy with tag support
|
|
93
|
+
* Persistent across process restarts, can be shared across multiple instances
|
|
94
|
+
*
|
|
95
|
+
* Uses Redis data structures:
|
|
96
|
+
* - Hash for storing cache entries: cache:{key} -> {value, tags, expiresAt, createdAt}
|
|
97
|
+
* - Sets for tag index: tag:{tag} -> Set of keys
|
|
98
|
+
*/
|
|
99
|
+
let redisModulePromise: Promise<PossibleRedisModule> | null = null
|
|
100
|
+
type RedisRegistryEntry = { client?: RedisClient; creating?: Promise<RedisClient>; refs: number }
|
|
101
|
+
const redisRegistry = new Map<string, RedisRegistryEntry>()
|
|
102
|
+
|
|
103
|
+
function resolveRequire(): RequireFn | null {
|
|
104
|
+
const nonWebpack = (globalThis as { __non_webpack_require__?: unknown }).__non_webpack_require__
|
|
105
|
+
if (typeof nonWebpack === 'function') return nonWebpack as RequireFn
|
|
106
|
+
if (typeof require === 'function') return require as RequireFn
|
|
107
|
+
if (typeof module !== 'undefined' && typeof module.require === 'function') {
|
|
108
|
+
return module.require.bind(module)
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
const maybeRequire = Function('return typeof require !== "undefined" ? require : undefined')()
|
|
112
|
+
if (typeof maybeRequire === 'function') return maybeRequire as RequireFn
|
|
113
|
+
} catch {
|
|
114
|
+
// ignore
|
|
115
|
+
}
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function loadRedisModuleViaRequire(): PossibleRedisModule | null {
|
|
120
|
+
const resolver = resolveRequire()
|
|
121
|
+
if (!resolver) return null
|
|
122
|
+
try {
|
|
123
|
+
return resolver('ioredis') as PossibleRedisModule
|
|
124
|
+
} catch {
|
|
125
|
+
return null
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function pickRedisConstructor(mod: PossibleRedisModule): RedisConstructor | null {
|
|
130
|
+
// `mod` goes last: a bundler-wrapped ESM namespace for a CJS module (e.g.
|
|
131
|
+
// Turbopack's `createNS`) can itself be a callable-but-not-constructible
|
|
132
|
+
// wrapper around the real class, while `.default`/`.Redis` still point at
|
|
133
|
+
// the real class. Checking them first costs nothing for a plain CJS
|
|
134
|
+
// `require()` or a real Node ESM namespace, where they already agree with
|
|
135
|
+
// `mod`.
|
|
136
|
+
const queue: unknown[] = [
|
|
137
|
+
(mod as { default?: unknown } | null | undefined)?.default,
|
|
138
|
+
(mod as { Redis?: unknown } | null | undefined)?.Redis,
|
|
139
|
+
mod,
|
|
140
|
+
]
|
|
141
|
+
const seen = new Set<unknown>()
|
|
142
|
+
while (queue.length) {
|
|
143
|
+
const current = queue.shift()
|
|
144
|
+
if (!current || seen.has(current)) continue
|
|
145
|
+
seen.add(current)
|
|
146
|
+
if (typeof current === 'function') return current as RedisConstructor
|
|
147
|
+
if (typeof current === 'object') {
|
|
148
|
+
queue.push((current as { default?: unknown }).default)
|
|
149
|
+
queue.push((current as { Redis?: unknown }).Redis)
|
|
150
|
+
queue.push((current as { module?: { exports?: unknown } }).module?.exports)
|
|
151
|
+
queue.push((current as { exports?: unknown }).exports)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function loadRedisModule(): Promise<PossibleRedisModule> {
|
|
158
|
+
if (!redisModulePromise) {
|
|
159
|
+
redisModulePromise = (async () => {
|
|
160
|
+
const required = loadRedisModuleViaRequire() ?? (await import('ioredis'))
|
|
161
|
+
return required as PossibleRedisModule
|
|
162
|
+
})().catch((error) => {
|
|
163
|
+
redisModulePromise = null
|
|
164
|
+
throw new CacheDependencyUnavailableError('redis', 'ioredis', error)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
return redisModulePromise
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function retainRedisEntry(key: string): RedisRegistryEntry {
|
|
171
|
+
let entry = redisRegistry.get(key)
|
|
172
|
+
if (!entry) {
|
|
173
|
+
entry = { refs: 0 }
|
|
174
|
+
redisRegistry.set(key, entry)
|
|
175
|
+
}
|
|
176
|
+
entry.refs += 1
|
|
177
|
+
return entry
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function acquireRedisClient(key: string, entry: RedisRegistryEntry): Promise<RedisClient> {
|
|
181
|
+
if (entry.client) return entry.client
|
|
182
|
+
if (entry.creating) return entry.creating
|
|
183
|
+
entry.creating = loadRedisModule()
|
|
184
|
+
.then((mod) => {
|
|
185
|
+
const ctor = pickRedisConstructor(mod)
|
|
186
|
+
if (!ctor) {
|
|
187
|
+
throw new CacheDependencyUnavailableError('redis', 'ioredis', new Error('No usable Redis constructor'))
|
|
188
|
+
}
|
|
189
|
+
const client = new ctor(key, { protocol: REDIS_WIRE_PROTOCOL })
|
|
190
|
+
entry.client = client
|
|
191
|
+
entry.creating = undefined
|
|
192
|
+
client.once?.('end', () => {
|
|
193
|
+
if (redisRegistry.get(key) === entry && entry.refs === 0) {
|
|
194
|
+
redisRegistry.delete(key)
|
|
195
|
+
} else if (redisRegistry.get(key) === entry) {
|
|
196
|
+
entry.client = undefined
|
|
197
|
+
}
|
|
198
|
+
})
|
|
199
|
+
return client
|
|
200
|
+
})
|
|
201
|
+
.catch((error) => {
|
|
202
|
+
entry.creating = undefined
|
|
203
|
+
throw error
|
|
204
|
+
})
|
|
205
|
+
return entry.creating
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function releaseRedisEntry(key: string, entry: RedisRegistryEntry): Promise<void> {
|
|
209
|
+
entry.refs = Math.max(0, entry.refs - 1)
|
|
210
|
+
if (entry.refs > 0) return
|
|
211
|
+
redisRegistry.delete(key)
|
|
212
|
+
if (entry.client) {
|
|
213
|
+
try {
|
|
214
|
+
await entry.client.quit()
|
|
215
|
+
} catch {
|
|
216
|
+
// ignore shutdown errors
|
|
217
|
+
} finally {
|
|
218
|
+
entry.client = undefined
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function createRedisStrategy(redisUrl?: string, options?: { defaultTtl?: number } & CacheCodecOptions): CacheStrategy {
|
|
224
|
+
const defaultTtl = options?.defaultTtl
|
|
225
|
+
const codec = resolveCacheCodecConfig(options)
|
|
226
|
+
const keyPrefix = 'cache:'
|
|
227
|
+
const tagPrefix = 'tag:'
|
|
228
|
+
const connectionUrl = redisUrl || getRedisUrlOrThrow('CACHE')
|
|
229
|
+
const registryEntry = retainRedisEntry(connectionUrl)
|
|
230
|
+
let redis: RedisClient | null = registryEntry.client ?? null
|
|
231
|
+
|
|
232
|
+
async function getRedisClient(): Promise<RedisClient> {
|
|
233
|
+
if (redis) return redis
|
|
234
|
+
|
|
235
|
+
redis = await acquireRedisClient(connectionUrl, registryEntry)
|
|
236
|
+
return redis
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function getCacheKey(key: string): string {
|
|
240
|
+
return `${keyPrefix}${key}`
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function getTagKey(tag: string): string {
|
|
244
|
+
return `${tagPrefix}${tag}`
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// SCAN may return duplicate keys and empty pages before the cursor reaches 0.
|
|
248
|
+
// COUNT is a work hint, not a strict page-size or latency bound.
|
|
249
|
+
async function scanKeys(pattern: string): Promise<string[]> {
|
|
250
|
+
const client = await getRedisClient()
|
|
251
|
+
const keys = new Set<string>()
|
|
252
|
+
let cursor = '0'
|
|
253
|
+
do {
|
|
254
|
+
const [next, page] = await client.scan(cursor, 'MATCH', pattern, 'COUNT', 256)
|
|
255
|
+
cursor = next
|
|
256
|
+
for (const key of page) keys.add(key)
|
|
257
|
+
} while (cursor !== '0')
|
|
258
|
+
return [...keys]
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function isExpired(entry: CacheEntry): boolean {
|
|
262
|
+
if (entry.expiresAt === null) return false
|
|
263
|
+
return Date.now() > entry.expiresAt
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const get = async (key: string, options?: CacheGetOptions): Promise<CacheValue | null> => {
|
|
267
|
+
const client = await getRedisClient()
|
|
268
|
+
const cacheKey = getCacheKey(key)
|
|
269
|
+
const data = await client.getBuffer(cacheKey)
|
|
270
|
+
|
|
271
|
+
if (!data) return null
|
|
272
|
+
|
|
273
|
+
try {
|
|
274
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
275
|
+
|
|
276
|
+
if (isExpired(entry)) {
|
|
277
|
+
if (options?.returnExpired) {
|
|
278
|
+
return entry.value
|
|
279
|
+
}
|
|
280
|
+
// Clean up expired entry
|
|
281
|
+
await deleteKey(key)
|
|
282
|
+
return null
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return entry.value
|
|
286
|
+
} catch {
|
|
287
|
+
// Invalid JSON, remove it
|
|
288
|
+
await client.del(cacheKey)
|
|
289
|
+
return null
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const set = async (key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> => {
|
|
294
|
+
const client = await getRedisClient()
|
|
295
|
+
const cacheKey = getCacheKey(key)
|
|
296
|
+
|
|
297
|
+
const ttl = options?.ttl ?? defaultTtl
|
|
298
|
+
const tags = options?.tags || []
|
|
299
|
+
const expiresAt = ttl ? Date.now() + ttl : null
|
|
300
|
+
|
|
301
|
+
const entry: CacheEntry = {
|
|
302
|
+
key,
|
|
303
|
+
value,
|
|
304
|
+
tags,
|
|
305
|
+
expiresAt,
|
|
306
|
+
createdAt: Date.now(),
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Old memberships are reconciled by deleteByTags using current entry tags.
|
|
310
|
+
// ioredis sends MULTI, the commands and EXEC together, without a pre-read.
|
|
311
|
+
const pipeline = client.multi()
|
|
312
|
+
|
|
313
|
+
// Store the entry
|
|
314
|
+
const serialized = encodeCacheText(JSON.stringify(entry), codec)
|
|
315
|
+
if (ttl) {
|
|
316
|
+
pipeline.setex(cacheKey, Math.ceil(ttl / 1000), serialized)
|
|
317
|
+
} else {
|
|
318
|
+
pipeline.set(cacheKey, serialized)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Add to tag index
|
|
322
|
+
for (const tag of tags) {
|
|
323
|
+
pipeline.sadd(getTagKey(tag), key)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
await executePipeline(pipeline)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const has = async (key: string): Promise<boolean> => {
|
|
330
|
+
const client = await getRedisClient()
|
|
331
|
+
const cacheKey = getCacheKey(key)
|
|
332
|
+
const exists = await client.exists(cacheKey)
|
|
333
|
+
|
|
334
|
+
if (!exists) return false
|
|
335
|
+
|
|
336
|
+
// Check if expired
|
|
337
|
+
const data = await client.getBuffer(cacheKey)
|
|
338
|
+
if (!data) return false
|
|
339
|
+
|
|
340
|
+
try {
|
|
341
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
342
|
+
if (isExpired(entry)) {
|
|
343
|
+
await deleteKey(key)
|
|
344
|
+
return false
|
|
345
|
+
}
|
|
346
|
+
return true
|
|
347
|
+
} catch {
|
|
348
|
+
return false
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const deleteKey = async (key: string): Promise<boolean> => {
|
|
353
|
+
const client = await getRedisClient()
|
|
354
|
+
const cacheKey = getCacheKey(key)
|
|
355
|
+
|
|
356
|
+
// Get entry to remove from tag index
|
|
357
|
+
const data = await client.getBuffer(cacheKey)
|
|
358
|
+
if (!data) return false
|
|
359
|
+
|
|
360
|
+
try {
|
|
361
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(data))
|
|
362
|
+
const pipeline = client.pipeline()
|
|
363
|
+
|
|
364
|
+
// Remove from tag index
|
|
365
|
+
for (const tag of entry.tags) {
|
|
366
|
+
pipeline.srem(getTagKey(tag), key)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Delete the cache entry
|
|
370
|
+
pipeline.del(cacheKey)
|
|
371
|
+
|
|
372
|
+
await pipeline.exec()
|
|
373
|
+
return true
|
|
374
|
+
} catch {
|
|
375
|
+
// Just delete the key if we can't parse it
|
|
376
|
+
await client.del(cacheKey)
|
|
377
|
+
return true
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
// Experimental entry-count bound; reply bytes and tag fanout remain workload dependent.
|
|
383
|
+
const batchSize = 256
|
|
384
|
+
|
|
385
|
+
async function executePipeline(pipeline: RedisPipeline): Promise<[Error | null, unknown][]> {
|
|
386
|
+
const result = await pipeline.exec() as [Error | null, unknown][] | null
|
|
387
|
+
if (!result) throw new Error('[internal] Redis pipeline aborted')
|
|
388
|
+
for (const [error] of result) if (error) throw error
|
|
389
|
+
return result
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function readBuffers(client: RedisClient, keys: string[]): Promise<(Buffer | null)[]> {
|
|
393
|
+
const values = await client.mgetBuffer(...keys)
|
|
394
|
+
if (values.length !== keys.length || values.some((value) => value !== null && !Buffer.isBuffer(value))) {
|
|
395
|
+
throw new Error('[internal] Unexpected binary Redis batch reply')
|
|
396
|
+
}
|
|
397
|
+
const missingKeys = keys.filter((_, index) => values[index] === null)
|
|
398
|
+
if (missingKeys.length > 0) {
|
|
399
|
+
// Detect WRONGTYPE without consuming a value rebuilt after the original MISS.
|
|
400
|
+
const validation = client.pipeline()
|
|
401
|
+
for (const key of missingKeys) validation.getBuffer(key)
|
|
402
|
+
await executePipeline(validation)
|
|
403
|
+
}
|
|
404
|
+
return values as (Buffer | null)[]
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function removeEntries(
|
|
408
|
+
client: RedisClient,
|
|
409
|
+
members: string[],
|
|
410
|
+
data: (Buffer | null)[],
|
|
411
|
+
requestedTags: Set<string>,
|
|
412
|
+
tagsByMember: Map<string, string[]>,
|
|
413
|
+
): Promise<number> {
|
|
414
|
+
const valueKeys: string[] = []
|
|
415
|
+
const groups = new Map<string, string[]>()
|
|
416
|
+
const orphans = new Map<string, string[]>()
|
|
417
|
+
const stale = new Map<string, { member: string; buffer: Buffer }[]>()
|
|
418
|
+
for (let index = 0; index < members.length; index++) {
|
|
419
|
+
const buffer = data[index]
|
|
420
|
+
const member = members[index]
|
|
421
|
+
const memberTags = tagsByMember.get(member) ?? []
|
|
422
|
+
if (!buffer) {
|
|
423
|
+
for (const tagKey of memberTags) {
|
|
424
|
+
const list = orphans.get(tagKey) ?? []
|
|
425
|
+
list.push(member)
|
|
426
|
+
orphans.set(tagKey, list)
|
|
427
|
+
}
|
|
428
|
+
continue
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
let entryTags: Set<string> | undefined
|
|
432
|
+
try {
|
|
433
|
+
const entry: CacheEntry = JSON.parse(decodeCacheText(buffer))
|
|
434
|
+
if (Array.isArray(entry.tags) && entry.tags.every((tag) => typeof tag === 'string')) {
|
|
435
|
+
entryTags = new Set(entry.tags)
|
|
436
|
+
}
|
|
437
|
+
} catch { /* Corrupt entries are deleted, as with deleteKey(). */ }
|
|
438
|
+
if (entryTags) {
|
|
439
|
+
for (const tagKey of memberTags) {
|
|
440
|
+
if (entryTags.has(tagKey.slice(tagPrefix.length))) continue
|
|
441
|
+
const list = stale.get(tagKey) ?? []
|
|
442
|
+
list.push({ member, buffer })
|
|
443
|
+
stale.set(tagKey, list)
|
|
444
|
+
}
|
|
445
|
+
if (![...entryTags].some((tag) => requestedTags.has(tag))) continue
|
|
446
|
+
for (const tag of entryTags) {
|
|
447
|
+
const tagKey = getTagKey(tag)
|
|
448
|
+
const list = groups.get(tagKey) ?? []
|
|
449
|
+
list.push(member)
|
|
450
|
+
groups.set(tagKey, list)
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
valueKeys.push(getCacheKey(member))
|
|
454
|
+
}
|
|
455
|
+
if (!valueKeys.length && !orphans.size && !stale.size) return 0
|
|
456
|
+
const pipeline = client.pipeline()
|
|
457
|
+
for (const [tagKey, list] of groups) pipeline.srem(tagKey, ...list)
|
|
458
|
+
if (valueKeys.length) pipeline.del(...valueKeys)
|
|
459
|
+
for (const [tagKey, list] of orphans) {
|
|
460
|
+
for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
|
|
461
|
+
const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)
|
|
462
|
+
const keys = [tagKey, ...chunk.map(getCacheKey)]
|
|
463
|
+
pipeline.eval(REAP_ORPHANED_TAG_MEMBERS, keys.length, ...keys, ...chunk)
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
for (const [tagKey, list] of stale) {
|
|
467
|
+
for (let offset = 0; offset < list.length; offset += REAP_CHUNK_SIZE) {
|
|
468
|
+
const chunk = list.slice(offset, offset + REAP_CHUNK_SIZE)
|
|
469
|
+
const keys = [tagKey, ...chunk.map(({ member }) => getCacheKey(member))]
|
|
470
|
+
pipeline.eval(REAP_STALE_TAG_MEMBERS, keys.length, ...keys, ...chunk.flatMap(({ member, buffer }) => [member, buffer]))
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
await executePipeline(pipeline)
|
|
474
|
+
return valueKeys.length
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const deleteByTags = async (tags: string[]): Promise<number> => {
|
|
478
|
+
const client = await getRedisClient()
|
|
479
|
+
const requestedTags = new Set(tags)
|
|
480
|
+
const keysToDelete = new Set<string>()
|
|
481
|
+
// Keep only actual memberships. Each read batch reconciles its indexes so
|
|
482
|
+
// observed value buffers are released before reading the next batch.
|
|
483
|
+
const tagsByMember = new Map<string, string[]>()
|
|
484
|
+
|
|
485
|
+
// Collect all keys that have any of the specified tags
|
|
486
|
+
const tagPipeline = client.pipeline()
|
|
487
|
+
const uniqueTags = [...requestedTags]
|
|
488
|
+
for (const tag of uniqueTags) tagPipeline.smembers(getTagKey(tag))
|
|
489
|
+
const tagReplies = uniqueTags.length ? await executePipeline(tagPipeline) : []
|
|
490
|
+
for (let index = 0; index < uniqueTags.length; index++) {
|
|
491
|
+
const keys = tagReplies[index][1] as string[]
|
|
492
|
+
const tagKey = getTagKey(uniqueTags[index])
|
|
493
|
+
for (const key of keys) {
|
|
494
|
+
keysToDelete.add(key)
|
|
495
|
+
const memberTags = tagsByMember.get(key) ?? []
|
|
496
|
+
memberTags.push(tagKey)
|
|
497
|
+
tagsByMember.set(key, memberTags)
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Delete all collected keys
|
|
502
|
+
let deleted = 0
|
|
503
|
+
const members = [...keysToDelete]
|
|
504
|
+
for (let offset = 0; offset < members.length; offset += batchSize) {
|
|
505
|
+
const chunk = members.slice(offset, offset + batchSize)
|
|
506
|
+
const data = await readBuffers(client, chunk.map(getCacheKey))
|
|
507
|
+
deleted += await removeEntries(client, chunk, data, requestedTags, tagsByMember)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
return deleted
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const clear = async (): Promise<number> => {
|
|
514
|
+
const client = await getRedisClient()
|
|
515
|
+
|
|
516
|
+
// Get all cache keys
|
|
517
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
518
|
+
const tagKeys = await scanKeys(`${tagPrefix}*`)
|
|
519
|
+
|
|
520
|
+
if (cacheKeys.length === 0 && tagKeys.length === 0) return 0
|
|
521
|
+
|
|
522
|
+
const physicalKeys = [...cacheKeys, ...tagKeys]
|
|
523
|
+
for (let offset = 0; offset < physicalKeys.length; offset += batchSize) {
|
|
524
|
+
const chunk = physicalKeys.slice(offset, offset + batchSize)
|
|
525
|
+
const pipeline = client.pipeline()
|
|
526
|
+
for (const key of chunk) pipeline.del(key)
|
|
527
|
+
await executePipeline(pipeline)
|
|
528
|
+
}
|
|
529
|
+
return cacheKeys.length
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const keys = async (pattern?: string): Promise<string[]> => {
|
|
533
|
+
const client = await getRedisClient()
|
|
534
|
+
const searchPattern = pattern
|
|
535
|
+
? `${keyPrefix}${pattern}`
|
|
536
|
+
: `${keyPrefix}*`
|
|
537
|
+
|
|
538
|
+
const cacheKeys = await scanKeys(searchPattern)
|
|
539
|
+
|
|
540
|
+
// Remove prefix from keys
|
|
541
|
+
const result = cacheKeys.map((key: string) => key.substring(keyPrefix.length))
|
|
542
|
+
|
|
543
|
+
if (!pattern) return result
|
|
544
|
+
|
|
545
|
+
// Apply pattern matching (Redis KEYS command uses glob pattern, but we want our pattern)
|
|
546
|
+
return result.filter((key: string) => matchCacheKeyPattern(key, pattern))
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const stats = async (): Promise<{ size: number; expired: number }> => {
|
|
550
|
+
const client = await getRedisClient()
|
|
551
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
552
|
+
|
|
553
|
+
let expired = 0
|
|
554
|
+
for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
|
|
555
|
+
const data = await readBuffers(client, cacheKeys.slice(offset, offset + batchSize))
|
|
556
|
+
for (const buffer of data) {
|
|
557
|
+
if (!buffer) continue
|
|
558
|
+
try { if (isExpired(JSON.parse(decodeCacheText(buffer)))) expired++ }
|
|
559
|
+
catch { /* stats ignores corrupt entries, as before. */ }
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
return { size: cacheKeys.length, expired }
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const cleanup = async (): Promise<number> => {
|
|
567
|
+
const client = await getRedisClient()
|
|
568
|
+
const cacheKeys = await scanKeys(`${keyPrefix}*`)
|
|
569
|
+
|
|
570
|
+
let removed = 0
|
|
571
|
+
for (let offset = 0; offset < cacheKeys.length; offset += batchSize) {
|
|
572
|
+
const chunk = cacheKeys.slice(offset, offset + batchSize)
|
|
573
|
+
const data = await readBuffers(client, chunk)
|
|
574
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
575
|
+
const buffer = data[index]
|
|
576
|
+
if (!buffer) continue
|
|
577
|
+
try {
|
|
578
|
+
if (isExpired(JSON.parse(decodeCacheText(buffer)))) {
|
|
579
|
+
await deleteKey(chunk[index].substring(keyPrefix.length))
|
|
580
|
+
removed++
|
|
581
|
+
}
|
|
582
|
+
} catch {
|
|
583
|
+
await client.del(chunk[index])
|
|
584
|
+
removed++
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
return removed
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const close = async (): Promise<void> => {
|
|
593
|
+
await releaseRedisEntry(connectionUrl, registryEntry)
|
|
594
|
+
redis = null
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const healthcheck = async (): Promise<void> => {
|
|
598
|
+
const client = await getRedisClient()
|
|
599
|
+
await client.ping()
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
return {
|
|
603
|
+
get,
|
|
604
|
+
set,
|
|
605
|
+
has,
|
|
606
|
+
delete: deleteKey,
|
|
607
|
+
deleteByTags,
|
|
608
|
+
clear,
|
|
609
|
+
keys,
|
|
610
|
+
stats,
|
|
611
|
+
healthcheck,
|
|
612
|
+
cleanup,
|
|
613
|
+
close,
|
|
614
|
+
}
|
|
615
|
+
}
|
package/tsconfig.json
ADDED
package/watch.mjs
ADDED
package/README.md
DELETED