@h-ai/cache 1.0.0-beta.30 → 1.0.0-beta.32
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.en.md +11 -326
- package/README.ja.md +10 -323
- package/README.md +10 -334
- package/dist/index.d.ts +23 -19
- package/dist/index.js +626 -370
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import process from 'process';
|
|
3
3
|
import { core, err, ok } from '@h-ai/core';
|
|
4
|
-
import Redis from 'ioredis';
|
|
5
4
|
import { Buffer } from 'buffer';
|
|
5
|
+
import { setMaxListeners } from 'events';
|
|
6
|
+
import Redis from 'ioredis';
|
|
6
7
|
import { createHash } from 'crypto';
|
|
7
8
|
|
|
8
9
|
// src/cache-config.ts
|
|
@@ -34,14 +35,14 @@ var RedisConfigSchema = z.object({
|
|
|
34
35
|
password: z.string().optional(),
|
|
35
36
|
/** 数据库编号(0~15);默认 0 */
|
|
36
37
|
db: z.number().int().min(0).max(15).default(0),
|
|
37
|
-
/**
|
|
38
|
+
/** 集群节点列表;列表非空时以集群模式连接 */
|
|
38
39
|
cluster: z.array(RedisClusterNodeSchema).optional(),
|
|
39
40
|
/** 哨兵配置;配置后以哨兵模式连接 */
|
|
40
41
|
sentinel: RedisSentinelConfigSchema.optional(),
|
|
41
42
|
// 通用选项
|
|
42
43
|
/** 连接超时时间(毫秒);默认 10000 */
|
|
43
44
|
connectTimeout: z.number().int().min(0).default(1e4),
|
|
44
|
-
/**
|
|
45
|
+
/** 普通命令执行超时(毫秒);默认 5000。阻塞弹出使用调用指定的 Redis 等待时间。 */
|
|
45
46
|
commandTimeout: z.number().int().min(0).default(5e3),
|
|
46
47
|
/** 键前缀(自动加在所有键前) */
|
|
47
48
|
keyPrefix: z.string().optional(),
|
|
@@ -51,7 +52,7 @@ var RedisConfigSchema = z.object({
|
|
|
51
52
|
maxRetries: z.number().int().min(0).default(3),
|
|
52
53
|
/** 重试间隔基数(毫秒);实际间隔 = retryDelay × 重试次数;默认 50 */
|
|
53
54
|
retryDelay: z.number().int().min(0).default(50),
|
|
54
|
-
/**
|
|
55
|
+
/** 非 Cluster 连接启用时发送 Redis READONLY;Cluster 按节点角色处理。写入权限由 Redis ACL 控制;默认 false。 */
|
|
55
56
|
readOnly: z.boolean().default(false)
|
|
56
57
|
});
|
|
57
58
|
var CacheConfigSchema = z.discriminatedUnion("type", [
|
|
@@ -77,6 +78,10 @@ var en_US_default = {
|
|
|
77
78
|
cache_crossSlot: "This operation requires keys in the same Redis Cluster slot; use a shared hash tag",
|
|
78
79
|
cache_sharedBackendRequired: "Production mode requires a shared backend; local files and memory backends are for development or explicit end-to-end tests.",
|
|
79
80
|
cache_invalidSetOptions: "Invalid SET options: use one positive safe-integer expiry, do not combine it with keepTtl, and choose at most one of nx/xx",
|
|
81
|
+
cache_invalidLockTtl: "Invalid lock TTL. Use a positive whole number of seconds that yields a safe expiration timestamp.",
|
|
82
|
+
cache_invalidLockOwnerOptions: "Pass only the owner token when reentering a lock. Call extend to renew the lease.",
|
|
83
|
+
cache_lockOperationInterrupted: "The cache connection closed and interrupted the lock operation.",
|
|
84
|
+
cache_blockingPopCanceled: "The cache connection closed and canceled the pending queue pop.",
|
|
80
85
|
cache_setUnexpectedReply: "Redis returned an unexpected SET result",
|
|
81
86
|
cache_serializationFailed: "The cache value could not be serialized as JSON"
|
|
82
87
|
};
|
|
@@ -99,6 +104,10 @@ var ja_JP_default = {
|
|
|
99
104
|
cache_crossSlot: "\u3053\u306E\u64CD\u4F5C\u306E\u30AD\u30FC\u306F\u540C\u3058 Redis Cluster \u30B9\u30ED\u30C3\u30C8\u306B\u914D\u7F6E\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\u5171\u901A\u306E\u30CF\u30C3\u30B7\u30E5\u30BF\u30B0\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044",
|
|
100
105
|
cache_sharedBackendRequired: "\u672C\u756A\u74B0\u5883\u306B\u306F\u5171\u6709\u30D0\u30C3\u30AF\u30A8\u30F3\u30C9\u304C\u5FC5\u8981\u3067\u3059\u3002\u30ED\u30FC\u30AB\u30EB\u30D5\u30A1\u30A4\u30EB\u3068\u30E1\u30E2\u30EA\u30FC\u30D0\u30C3\u30AF\u30A8\u30F3\u30C9\u306F\u958B\u767A\u74B0\u5883\u307E\u305F\u306F\u660E\u793A\u7684\u306A E2E \u30C6\u30B9\u30C8\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002",
|
|
101
106
|
cache_invalidSetOptions: "SET \u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u7121\u52B9\u3067\u3059\u3002\u6709\u52B9\u671F\u9650\u306B\u306F\u6B63\u306E\u5B89\u5168\u306A\u6574\u6570\u30921\u7A2E\u985E\u3060\u3051\u6307\u5B9A\u3057\u3001keepTtl \u3068\u4F75\u7528\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\u3002nx \u3068 xx \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093",
|
|
107
|
+
cache_invalidLockTtl: "\u30ED\u30C3\u30AF\u306E\u6709\u52B9\u671F\u9593\u304C\u7121\u52B9\u3067\u3059\u3002\u6709\u52B9\u671F\u9650\u3092\u6B63\u78BA\u306B\u8868\u73FE\u3067\u304D\u308B\u6B63\u306E\u6574\u6570\u79D2\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
|
|
108
|
+
cache_invalidLockOwnerOptions: "\u30ED\u30C3\u30AF\u306B\u518D\u5165\u3059\u308B\u5834\u5408\u306F\u6240\u6709\u8005\u30C8\u30FC\u30AF\u30F3\u306E\u307F\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u6709\u52B9\u671F\u9593\u3092\u5EF6\u9577\u3059\u308B\u306B\u306F extend \u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
|
|
109
|
+
cache_lockOperationInterrupted: "\u30AD\u30E3\u30C3\u30B7\u30E5\u63A5\u7D9A\u304C\u9589\u3058\u3089\u308C\u305F\u305F\u3081\u3001\u30ED\u30C3\u30AF\u64CD\u4F5C\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F\u3002",
|
|
110
|
+
cache_blockingPopCanceled: "\u30AD\u30E3\u30C3\u30B7\u30E5\u63A5\u7D9A\u304C\u9589\u3058\u3089\u308C\u305F\u305F\u3081\u3001\u30AD\u30E5\u30FC\u304B\u3089\u306E\u53D6\u5F97\u3092\u30AD\u30E3\u30F3\u30BB\u30EB\u3057\u307E\u3057\u305F\u3002",
|
|
102
111
|
cache_setUnexpectedReply: "Redis \u304C\u4E88\u671F\u3057\u306A\u3044 SET \u306E\u7D50\u679C\u3092\u8FD4\u3057\u307E\u3057\u305F",
|
|
103
112
|
cache_serializationFailed: "\u30AD\u30E3\u30C3\u30B7\u30E5\u5024\u3092 JSON \u306B\u30B7\u30EA\u30A2\u30E9\u30A4\u30BA\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"
|
|
104
113
|
};
|
|
@@ -121,6 +130,10 @@ var zh_CN_default = {
|
|
|
121
130
|
cache_crossSlot: "\u6B64\u64CD\u4F5C\u8981\u6C42\u6240\u6709\u952E\u4F4D\u4E8E\u540C\u4E00Redis Cluster slot\uFF0C\u8BF7\u4F7F\u7528\u5171\u540Chash tag",
|
|
122
131
|
cache_sharedBackendRequired: "\u751F\u4EA7\u6A21\u5F0F\u9700\u8981\u8DE8\u8282\u70B9\u5171\u4EAB\u540E\u7AEF\uFF1B\u672C\u673A\u6587\u4EF6\u6216\u5185\u5B58\u540E\u7AEF\u4EC5\u7528\u4E8E\u5F00\u53D1\u548C\u663E\u5F0F\u7AEF\u5230\u7AEF\u6D4B\u8BD5\u3002",
|
|
123
132
|
cache_invalidSetOptions: "SET \u9009\u9879\u65E0\u6548\uFF1A\u671F\u9650\u987B\u4E3A\u6B63\u5B89\u5168\u6574\u6570\u4E14\u53EA\u80FD\u9009\u4E00\u79CD\uFF0C\u4E0D\u80FD\u4E0E keepTtl \u540C\u65F6\u4F7F\u7528\uFF0Cnx/xx \u4E0D\u80FD\u540C\u65F6\u542F\u7528",
|
|
133
|
+
cache_invalidLockTtl: "\u9501\u671F\u9650\u65E0\u6548\uFF0C\u8BF7\u7528\u53EF\u8868\u793A\u4E3A\u5230\u671F\u65F6\u95F4\u7684\u6B63\u6574\u6570\u79D2\u6570",
|
|
134
|
+
cache_invalidLockOwnerOptions: "\u91CD\u5165\u9501\u65F6\u8BF7\u53EA\u4F20\u5165\u6301\u6709\u8005\u51ED\u636E\u3002\u9700\u8981\u7EED\u671F\u65F6\u8BF7\u8C03\u7528 extend\u3002",
|
|
135
|
+
cache_lockOperationInterrupted: "\u7F13\u5B58\u8FDE\u63A5\u5DF2\u5173\u95ED\uFF0C\u9501\u64CD\u4F5C\u4E2D\u65AD",
|
|
136
|
+
cache_blockingPopCanceled: "\u7F13\u5B58\u8FDE\u63A5\u5DF2\u5173\u95ED\uFF0C\u7B49\u5F85\u53D6\u51FA\u961F\u5217\u5143\u7D20\u7684\u64CD\u4F5C\u5DF2\u53D6\u6D88",
|
|
124
137
|
cache_setUnexpectedReply: "Redis \u8FD4\u56DE\u4E86\u975E\u9884\u671F\u7684 SET \u7ED3\u679C",
|
|
125
138
|
cache_serializationFailed: "\u7F13\u5B58\u503C\u65E0\u6CD5\u5E8F\u5217\u5316\u4E3A JSON"
|
|
126
139
|
};
|
|
@@ -147,6 +160,12 @@ var CacheErrorInfo = {
|
|
|
147
160
|
INVALID_SET_OPTIONS: "016:400"
|
|
148
161
|
};
|
|
149
162
|
var HaiCacheError = core.error.buildHaiErrorsDef("cache", CacheErrorInfo);
|
|
163
|
+
function isValidLockTtl(ttl) {
|
|
164
|
+
return Number.isSafeInteger(ttl) && ttl > 0 && Number.isSafeInteger(Date.now() + ttl * 1e3);
|
|
165
|
+
}
|
|
166
|
+
function isValidLockOwner(owner) {
|
|
167
|
+
return typeof owner === "string" && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(owner);
|
|
168
|
+
}
|
|
150
169
|
function validateSetOptions(options) {
|
|
151
170
|
const invalid = () => err(HaiCacheError.INVALID_SET_OPTIONS, cacheM("cache_invalidSetOptions"));
|
|
152
171
|
if (options !== void 0 && (options === null || typeof options !== "object" || Array.isArray(options)))
|
|
@@ -182,15 +201,77 @@ function validateSetOptions(options) {
|
|
|
182
201
|
return ok(result);
|
|
183
202
|
}
|
|
184
203
|
|
|
185
|
-
// src/providers/cache-
|
|
186
|
-
|
|
187
|
-
|
|
204
|
+
// src/providers/cache-value.ts
|
|
205
|
+
var CacheSerializationError = class extends Error {
|
|
206
|
+
};
|
|
207
|
+
function serializeCacheValue(value) {
|
|
208
|
+
let snapshot;
|
|
209
|
+
try {
|
|
210
|
+
snapshot = JSON.stringify(value);
|
|
211
|
+
} catch (cause) {
|
|
212
|
+
throw new CacheSerializationError("Cache value could not be serialized as JSON", { cause });
|
|
213
|
+
}
|
|
214
|
+
if (snapshot === void 0)
|
|
215
|
+
throw new CacheSerializationError("Cache value has no JSON representation");
|
|
216
|
+
return snapshot;
|
|
188
217
|
}
|
|
218
|
+
|
|
219
|
+
// src/providers/cache-provider-memory.ts
|
|
189
220
|
function deserializeValue(str) {
|
|
190
221
|
return JSON.parse(str);
|
|
191
222
|
}
|
|
192
|
-
function
|
|
193
|
-
return
|
|
223
|
+
function operationFailure(reason, cause) {
|
|
224
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_operationFailed", {
|
|
225
|
+
params: { error: reason }
|
|
226
|
+
}), cause);
|
|
227
|
+
}
|
|
228
|
+
function serializationFailure(error) {
|
|
229
|
+
return err(HaiCacheError.SERIALIZATION_FAILED, cacheM("cache_serializationFailed"), error);
|
|
230
|
+
}
|
|
231
|
+
function sliceByRank(values, start, stop) {
|
|
232
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(stop))
|
|
233
|
+
throw new RangeError("Range indices must be safe integers");
|
|
234
|
+
const first = start < 0 ? Math.max(values.length + start, 0) : start;
|
|
235
|
+
const end = stop < 0 ? Math.max(values.length + stop + 1, 0) : stop + 1;
|
|
236
|
+
return values.slice(first, end);
|
|
237
|
+
}
|
|
238
|
+
function compareRanks(left, right) {
|
|
239
|
+
if (left[1] !== right[1])
|
|
240
|
+
return left[1] - right[1];
|
|
241
|
+
return Buffer.compare(Buffer.from(left[0]), Buffer.from(right[0]));
|
|
242
|
+
}
|
|
243
|
+
function parseScoreBound(bound) {
|
|
244
|
+
const exclusive = typeof bound === "string" && bound.startsWith("(");
|
|
245
|
+
const raw = exclusive ? bound.slice(1) : bound;
|
|
246
|
+
if (typeof raw === "number" && !Number.isNaN(raw))
|
|
247
|
+
return { value: raw, exclusive };
|
|
248
|
+
if (typeof raw === "string") {
|
|
249
|
+
if (/^[+-]?inf(?:inity)?$/i.test(raw)) {
|
|
250
|
+
return {
|
|
251
|
+
value: raw.startsWith("-") ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
|
|
252
|
+
exclusive
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw)) {
|
|
256
|
+
const value = Number(raw);
|
|
257
|
+
if (Number.isFinite(value))
|
|
258
|
+
return { value, exclusive };
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
throw new RangeError("Invalid sorted set score bound");
|
|
262
|
+
}
|
|
263
|
+
function scoreRange(min, max) {
|
|
264
|
+
const lower = parseScoreBound(min);
|
|
265
|
+
const upper = parseScoreBound(max);
|
|
266
|
+
return (score) => (lower.exclusive ? score > lower.value : score >= lower.value) && (upper.exclusive ? score < upper.value : score <= upper.value);
|
|
267
|
+
}
|
|
268
|
+
function drawMember(members) {
|
|
269
|
+
const index = Math.floor(Math.random() * members.length);
|
|
270
|
+
const member = members[index];
|
|
271
|
+
const last = members.pop();
|
|
272
|
+
if (index < members.length)
|
|
273
|
+
members[index] = last;
|
|
274
|
+
return member;
|
|
194
275
|
}
|
|
195
276
|
function globToRegex(pattern) {
|
|
196
277
|
const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -254,34 +335,28 @@ function createMemoryProvider() {
|
|
|
254
335
|
])
|
|
255
336
|
].filter((key) => keyType(key) !== "none");
|
|
256
337
|
}
|
|
338
|
+
function hasWrongType(key, type) {
|
|
339
|
+
const actual = keyType(key);
|
|
340
|
+
return actual !== "none" && actual !== type;
|
|
341
|
+
}
|
|
342
|
+
function wrongType() {
|
|
343
|
+
return operationFailure("Key contains another data type");
|
|
344
|
+
}
|
|
257
345
|
function guardStructure(operations, type) {
|
|
258
346
|
return new Proxy(operations, {
|
|
259
347
|
get(target, property, receiver) {
|
|
260
348
|
const operation = Reflect.get(target, property, receiver);
|
|
261
349
|
if (typeof operation !== "function")
|
|
262
350
|
return operation;
|
|
263
|
-
return (...args) => {
|
|
264
|
-
const keys = (
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
for (const key of keys) {
|
|
272
|
-
const actual = keyType(key);
|
|
273
|
-
if (actual !== "none" && actual !== type) {
|
|
274
|
-
return Promise.resolve(err(HaiCacheError.OPERATION_FAILED, cacheM("cache_operationFailed", {
|
|
275
|
-
params: { error: "Key contains another data type" }
|
|
276
|
-
})));
|
|
277
|
-
}
|
|
351
|
+
return async (...args) => {
|
|
352
|
+
const keys = property === "blpop" || property === "brpop" ? [] : (property === "sinter" || property === "sunion" || property === "sdiff" ? args : args.slice(0, 1)).filter((key) => typeof key === "string");
|
|
353
|
+
try {
|
|
354
|
+
if (keys.some((key) => hasWrongType(key, type)))
|
|
355
|
+
return wrongType();
|
|
356
|
+
return await Reflect.apply(operation, target, args);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
return error instanceof CacheSerializationError ? serializationFailure(error) : operationFailure(error instanceof Error ? error.message : String(error), error);
|
|
278
359
|
}
|
|
279
|
-
return Promise.resolve(Reflect.apply(operation, target, args)).finally(() => {
|
|
280
|
-
for (const key of keys) {
|
|
281
|
-
if (keyType(key) === "none")
|
|
282
|
-
deleteKey(key);
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
360
|
};
|
|
286
361
|
}
|
|
287
362
|
});
|
|
@@ -317,28 +392,23 @@ function createMemoryProvider() {
|
|
|
317
392
|
try {
|
|
318
393
|
if (options?.px !== void 0 && (!Number.isSafeInteger(options.px) || options.px <= 0) || options?.px !== void 0 && options.keepTtl)
|
|
319
394
|
throw new TypeError("Invalid compare-and-swap expiry");
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
395
|
+
const expectedSnapshot = expected === void 0 ? void 0 : serializeCacheValue(expected);
|
|
396
|
+
const valueSnapshot = value === void 0 ? void 0 : deserializeValue(serializeCacheValue(value));
|
|
397
|
+
if (hasWrongType(key, "string"))
|
|
398
|
+
return wrongType();
|
|
323
399
|
const entry = getValidEntry(key);
|
|
324
|
-
const actual = entry ?
|
|
325
|
-
if (actual !==
|
|
400
|
+
const actual = entry ? serializeCacheValue(entry.value) : void 0;
|
|
401
|
+
if (actual !== expectedSnapshot)
|
|
326
402
|
return ok(false);
|
|
327
|
-
|
|
328
|
-
if (value === void 0) {
|
|
403
|
+
if (valueSnapshot === void 0) {
|
|
329
404
|
store.delete(key);
|
|
330
405
|
} else {
|
|
331
406
|
const expiresAt = options?.px !== void 0 ? Date.now() + options.px : options?.keepTtl ? entry?.expiresAt : void 0;
|
|
332
|
-
store.set(key, {
|
|
333
|
-
value: deserializeValue(serializeValue(value)),
|
|
334
|
-
expiresAt
|
|
335
|
-
});
|
|
407
|
+
store.set(key, { value: valueSnapshot, expiresAt });
|
|
336
408
|
}
|
|
337
409
|
return ok(true);
|
|
338
410
|
} catch (error) {
|
|
339
|
-
return
|
|
340
|
-
params: { error: "Compare-and-swap failed" }
|
|
341
|
-
}), error);
|
|
411
|
+
return error instanceof CacheSerializationError ? serializationFailure(error) : operationFailure("Compare-and-swap failed", error);
|
|
342
412
|
}
|
|
343
413
|
},
|
|
344
414
|
async get(key) {
|
|
@@ -350,7 +420,7 @@ function createMemoryProvider() {
|
|
|
350
420
|
}));
|
|
351
421
|
}
|
|
352
422
|
const entry = getValidEntry(key);
|
|
353
|
-
return ok(entry ? deserializeValue(
|
|
423
|
+
return ok(entry ? deserializeValue(serializeCacheValue(entry.value)) : null);
|
|
354
424
|
} catch (error) {
|
|
355
425
|
return err(HaiCacheError.SERIALIZATION_FAILED, cacheM("cache_operationFailed", {
|
|
356
426
|
params: { error: "JSON snapshot failed" }
|
|
@@ -362,11 +432,11 @@ function createMemoryProvider() {
|
|
|
362
432
|
if (!validated.success)
|
|
363
433
|
return validated;
|
|
364
434
|
const policy = validated.data;
|
|
365
|
-
const existing = keyType(key) !== "none";
|
|
366
|
-
if (policy.nx && existing || policy.xx && !existing)
|
|
367
|
-
return ok(false);
|
|
368
435
|
try {
|
|
369
|
-
const snapshot = deserializeValue(
|
|
436
|
+
const snapshot = deserializeValue(serializeCacheValue(value));
|
|
437
|
+
const existing = keyType(key) !== "none";
|
|
438
|
+
if (policy.nx && existing || policy.xx && !existing)
|
|
439
|
+
return ok(false);
|
|
370
440
|
const expiresAt = policy.keepTtl ? keyExpiry(key) : policy.expiresAt;
|
|
371
441
|
deleteKey(key);
|
|
372
442
|
if (expiresAt !== void 0 && expiresAt <= Date.now())
|
|
@@ -375,7 +445,7 @@ function createMemoryProvider() {
|
|
|
375
445
|
store.set(key, { value: snapshot, expiresAt });
|
|
376
446
|
return ok(true);
|
|
377
447
|
} catch (error) {
|
|
378
|
-
return
|
|
448
|
+
return serializationFailure(error);
|
|
379
449
|
}
|
|
380
450
|
},
|
|
381
451
|
async del(...keys) {
|
|
@@ -396,15 +466,21 @@ function createMemoryProvider() {
|
|
|
396
466
|
return ok(count);
|
|
397
467
|
},
|
|
398
468
|
async expire(key, seconds) {
|
|
469
|
+
const expiry = Date.now() + seconds * 1e3;
|
|
470
|
+
if (!Number.isSafeInteger(seconds) || !Number.isSafeInteger(expiry))
|
|
471
|
+
return operationFailure("Invalid expiry");
|
|
399
472
|
if (keyType(key) === "none")
|
|
400
473
|
return ok(false);
|
|
401
|
-
setKeyExpiry(key,
|
|
474
|
+
setKeyExpiry(key, expiry);
|
|
402
475
|
return ok(true);
|
|
403
476
|
},
|
|
404
477
|
async expireAt(key, timestamp) {
|
|
478
|
+
const expiry = timestamp * 1e3;
|
|
479
|
+
if (!Number.isSafeInteger(timestamp) || !Number.isSafeInteger(expiry))
|
|
480
|
+
return operationFailure("Invalid expiry");
|
|
405
481
|
if (keyType(key) === "none")
|
|
406
482
|
return ok(false);
|
|
407
|
-
setKeyExpiry(key,
|
|
483
|
+
setKeyExpiry(key, expiry);
|
|
408
484
|
return ok(true);
|
|
409
485
|
},
|
|
410
486
|
async ttl(key) {
|
|
@@ -416,7 +492,7 @@ function createMemoryProvider() {
|
|
|
416
492
|
return ok(Math.ceil((expiresAt - Date.now()) / 1e3));
|
|
417
493
|
},
|
|
418
494
|
async persist(key) {
|
|
419
|
-
if (keyType(key) === "none")
|
|
495
|
+
if (keyType(key) === "none" || keyExpiry(key) === void 0)
|
|
420
496
|
return ok(false);
|
|
421
497
|
const entry = store.get(key);
|
|
422
498
|
if (entry)
|
|
@@ -452,7 +528,7 @@ function createMemoryProvider() {
|
|
|
452
528
|
const results = [];
|
|
453
529
|
for (const key of keys) {
|
|
454
530
|
const entry = getValidEntry(key);
|
|
455
|
-
results.push(entry ? deserializeValue(
|
|
531
|
+
results.push(entry ? deserializeValue(serializeCacheValue(entry.value)) : null);
|
|
456
532
|
}
|
|
457
533
|
return ok(results);
|
|
458
534
|
} catch (error) {
|
|
@@ -465,7 +541,7 @@ function createMemoryProvider() {
|
|
|
465
541
|
try {
|
|
466
542
|
const snapshots = entries.map(([key, value]) => [
|
|
467
543
|
key,
|
|
468
|
-
deserializeValue(
|
|
544
|
+
deserializeValue(serializeCacheValue(value))
|
|
469
545
|
]);
|
|
470
546
|
for (const [key, value] of snapshots) {
|
|
471
547
|
deleteKey(key);
|
|
@@ -473,7 +549,7 @@ function createMemoryProvider() {
|
|
|
473
549
|
}
|
|
474
550
|
return ok(void 0);
|
|
475
551
|
} catch (error) {
|
|
476
|
-
return
|
|
552
|
+
return serializationFailure(error);
|
|
477
553
|
}
|
|
478
554
|
},
|
|
479
555
|
async scan(cursor, options) {
|
|
@@ -509,25 +585,28 @@ function createMemoryProvider() {
|
|
|
509
585
|
if (typeof fieldOrData !== "string" && (fieldOrData === null || Array.isArray(fieldOrData))) {
|
|
510
586
|
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidHashSetInput"));
|
|
511
587
|
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
588
|
+
if (typeof fieldOrData === "string" && value === void 0)
|
|
589
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidHashSetInput"));
|
|
590
|
+
const entries = typeof fieldOrData === "string" ? [
|
|
591
|
+
[
|
|
592
|
+
fieldOrData,
|
|
593
|
+
serializeCacheValue(value)
|
|
594
|
+
]
|
|
595
|
+
] : Object.entries(fieldOrData).map(([field, fieldValue]) => [
|
|
596
|
+
field,
|
|
597
|
+
serializeCacheValue(fieldValue)
|
|
598
|
+
]);
|
|
599
|
+
if (hasWrongType(key, "hash"))
|
|
600
|
+
return wrongType();
|
|
601
|
+
const map = hashStore.get(key) ?? /* @__PURE__ */ new Map();
|
|
525
602
|
let count = 0;
|
|
526
|
-
for (const [
|
|
527
|
-
if (!map.has(
|
|
603
|
+
for (const [field, serialized] of entries) {
|
|
604
|
+
if (!map.has(field))
|
|
528
605
|
count++;
|
|
529
|
-
map.set(
|
|
606
|
+
map.set(field, serialized);
|
|
530
607
|
}
|
|
608
|
+
if (map.size)
|
|
609
|
+
hashStore.set(key, map);
|
|
531
610
|
return ok(count);
|
|
532
611
|
}),
|
|
533
612
|
async hdel(key, ...fields) {
|
|
@@ -539,6 +618,8 @@ function createMemoryProvider() {
|
|
|
539
618
|
if (map.delete(field))
|
|
540
619
|
count++;
|
|
541
620
|
}
|
|
621
|
+
if (!map.size)
|
|
622
|
+
deleteKey(key);
|
|
542
623
|
return ok(count);
|
|
543
624
|
},
|
|
544
625
|
async hexists(key, field) {
|
|
@@ -577,36 +658,56 @@ function createMemoryProvider() {
|
|
|
577
658
|
return ok(results);
|
|
578
659
|
},
|
|
579
660
|
async hincrBy(key, field, increment) {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
const current = map.has(field) ? Number(deserializeValue(map.get(field))) : 0;
|
|
661
|
+
const map = hashStore.get(key) ?? /* @__PURE__ */ new Map();
|
|
662
|
+
const stored = map.get(field);
|
|
663
|
+
const current = stored === void 0 ? 0 : deserializeValue(stored);
|
|
664
|
+
if (typeof current !== "number" || !Number.isSafeInteger(current) || !Number.isSafeInteger(increment))
|
|
665
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_valueNotNumber"));
|
|
586
666
|
const newValue = current + increment;
|
|
587
|
-
|
|
667
|
+
if (!Number.isSafeInteger(newValue))
|
|
668
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_valueNotNumber"));
|
|
669
|
+
map.set(field, serializeCacheValue(newValue));
|
|
670
|
+
hashStore.set(key, map);
|
|
588
671
|
return ok(newValue);
|
|
589
672
|
}
|
|
590
673
|
};
|
|
674
|
+
function popFirstList(keys, end) {
|
|
675
|
+
for (const key of keys) {
|
|
676
|
+
if (hasWrongType(key, "list"))
|
|
677
|
+
return wrongType();
|
|
678
|
+
const items = listStore.get(key);
|
|
679
|
+
if (!items?.length)
|
|
680
|
+
continue;
|
|
681
|
+
const value = items[end]();
|
|
682
|
+
if (!items.length)
|
|
683
|
+
deleteKey(key);
|
|
684
|
+
return ok([
|
|
685
|
+
key,
|
|
686
|
+
deserializeValue(value)
|
|
687
|
+
]);
|
|
688
|
+
}
|
|
689
|
+
return ok(null);
|
|
690
|
+
}
|
|
591
691
|
const list = {
|
|
592
692
|
async lpush(key, ...values) {
|
|
593
|
-
|
|
594
|
-
if (
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
return ok(arr.length);
|
|
693
|
+
const serialized = values.map(serializeCacheValue).reverse();
|
|
694
|
+
if (hasWrongType(key, "list"))
|
|
695
|
+
return wrongType();
|
|
696
|
+
const arr = listStore.get(key) ?? [];
|
|
697
|
+
const next = serialized.concat(arr);
|
|
698
|
+
if (next.length)
|
|
699
|
+
listStore.set(key, next);
|
|
700
|
+
return ok(next.length);
|
|
602
701
|
},
|
|
603
702
|
async rpush(key, ...values) {
|
|
604
|
-
|
|
605
|
-
if (
|
|
606
|
-
|
|
703
|
+
const serialized = values.map(serializeCacheValue);
|
|
704
|
+
if (hasWrongType(key, "list"))
|
|
705
|
+
return wrongType();
|
|
706
|
+
const arr = listStore.get(key) ?? [];
|
|
707
|
+
for (const value of serialized)
|
|
708
|
+
arr.push(value);
|
|
709
|
+
if (arr.length)
|
|
607
710
|
listStore.set(key, arr);
|
|
608
|
-
}
|
|
609
|
-
arr.push(...values.map(serializeValue));
|
|
610
711
|
return ok(arr.length);
|
|
611
712
|
},
|
|
612
713
|
async lpop(key) {
|
|
@@ -614,6 +715,8 @@ function createMemoryProvider() {
|
|
|
614
715
|
if (!arr || arr.length === 0)
|
|
615
716
|
return ok(null);
|
|
616
717
|
const val = arr.shift();
|
|
718
|
+
if (!arr.length)
|
|
719
|
+
deleteKey(key);
|
|
617
720
|
return ok(deserializeValue(val));
|
|
618
721
|
},
|
|
619
722
|
async rpop(key) {
|
|
@@ -621,6 +724,8 @@ function createMemoryProvider() {
|
|
|
621
724
|
if (!arr || arr.length === 0)
|
|
622
725
|
return ok(null);
|
|
623
726
|
const val = arr.pop();
|
|
727
|
+
if (!arr.length)
|
|
728
|
+
deleteKey(key);
|
|
624
729
|
return ok(deserializeValue(val));
|
|
625
730
|
},
|
|
626
731
|
async llen(key) {
|
|
@@ -628,15 +733,11 @@ function createMemoryProvider() {
|
|
|
628
733
|
return ok(arr?.length ?? 0);
|
|
629
734
|
},
|
|
630
735
|
async lrange(key, start, stop) {
|
|
631
|
-
|
|
632
|
-
if (!arr)
|
|
633
|
-
return ok([]);
|
|
634
|
-
const len = arr.length;
|
|
635
|
-
const s = start < 0 ? Math.max(len + start, 0) : start;
|
|
636
|
-
const e = stop < 0 ? len + stop + 1 : stop + 1;
|
|
637
|
-
return ok(arr.slice(s, e).map((v) => deserializeValue(v)));
|
|
736
|
+
return ok(sliceByRank(listStore.get(key) ?? [], start, stop).map((value) => deserializeValue(value)));
|
|
638
737
|
},
|
|
639
738
|
async lindex(key, index) {
|
|
739
|
+
if (!Number.isSafeInteger(index))
|
|
740
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_indexOutOfRange"));
|
|
640
741
|
const arr = listStore.get(key);
|
|
641
742
|
if (!arr)
|
|
642
743
|
return ok(null);
|
|
@@ -645,86 +746,67 @@ function createMemoryProvider() {
|
|
|
645
746
|
return ok(val !== void 0 ? deserializeValue(val) : null);
|
|
646
747
|
},
|
|
647
748
|
async lset(key, index, value) {
|
|
749
|
+
const serialized = serializeCacheValue(value);
|
|
750
|
+
if (hasWrongType(key, "list"))
|
|
751
|
+
return wrongType();
|
|
648
752
|
const arr = listStore.get(key);
|
|
649
753
|
if (!arr) {
|
|
650
754
|
return err(HaiCacheError.KEY_NOT_FOUND, cacheM("cache_keyNotFound"));
|
|
651
755
|
}
|
|
652
756
|
const i = index < 0 ? arr.length + index : index;
|
|
653
|
-
if (i < 0 || i >= arr.length) {
|
|
757
|
+
if (!Number.isSafeInteger(index) || i < 0 || i >= arr.length) {
|
|
654
758
|
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_indexOutOfRange"));
|
|
655
759
|
}
|
|
656
|
-
arr[i] =
|
|
760
|
+
arr[i] = serialized;
|
|
657
761
|
return ok(void 0);
|
|
658
762
|
},
|
|
659
763
|
async ltrim(key, start, stop) {
|
|
660
|
-
const
|
|
661
|
-
if (
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
const s = start < 0 ? Math.max(len + start, 0) : start;
|
|
665
|
-
const e = stop < 0 ? len + stop + 1 : stop + 1;
|
|
666
|
-
listStore.set(key, arr.slice(s, e));
|
|
764
|
+
const remaining = sliceByRank(listStore.get(key) ?? [], start, stop);
|
|
765
|
+
if (remaining.length)
|
|
766
|
+
listStore.set(key, remaining);
|
|
767
|
+
else deleteKey(key);
|
|
667
768
|
return ok(void 0);
|
|
668
769
|
},
|
|
669
770
|
/**
|
|
670
771
|
* Memory 版本的 blpop 为“非阻塞模拟”:忽略 timeout,立即按 keys 顺序尝试弹出。
|
|
671
772
|
*/
|
|
672
773
|
async blpop(_timeout, ...keys) {
|
|
673
|
-
|
|
674
|
-
const arr = listStore.get(key);
|
|
675
|
-
if (arr && arr.length > 0) {
|
|
676
|
-
const val = arr.shift();
|
|
677
|
-
return ok([
|
|
678
|
-
key,
|
|
679
|
-
deserializeValue(val)
|
|
680
|
-
]);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
return ok(null);
|
|
774
|
+
return popFirstList(keys, "shift");
|
|
684
775
|
},
|
|
685
776
|
/**
|
|
686
777
|
* Memory 版本的 brpop 为“非阻塞模拟”:忽略 timeout,立即按 keys 顺序尝试弹出。
|
|
687
778
|
*/
|
|
688
779
|
async brpop(_timeout, ...keys) {
|
|
689
|
-
|
|
690
|
-
const arr = listStore.get(key);
|
|
691
|
-
if (arr && arr.length > 0) {
|
|
692
|
-
const val = arr.pop();
|
|
693
|
-
return ok([
|
|
694
|
-
key,
|
|
695
|
-
deserializeValue(val)
|
|
696
|
-
]);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
return ok(null);
|
|
780
|
+
return popFirstList(keys, "pop");
|
|
700
781
|
}
|
|
701
782
|
};
|
|
702
783
|
const set_ = {
|
|
703
784
|
async sadd(key, ...members) {
|
|
704
|
-
|
|
705
|
-
if (
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
count++;
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
return ok(count);
|
|
785
|
+
const serialized = members.map(serializeCacheValue);
|
|
786
|
+
if (hasWrongType(key, "set"))
|
|
787
|
+
return wrongType();
|
|
788
|
+
const set = setStore.get(key) ?? /* @__PURE__ */ new Set();
|
|
789
|
+
const sizeBefore = set.size;
|
|
790
|
+
for (const member of serialized)
|
|
791
|
+
set.add(member);
|
|
792
|
+
if (set.size)
|
|
793
|
+
setStore.set(key, set);
|
|
794
|
+
return ok(set.size - sizeBefore);
|
|
718
795
|
},
|
|
719
796
|
async srem(key, ...members) {
|
|
797
|
+
const serialized = members.map(serializeCacheValue);
|
|
798
|
+
if (hasWrongType(key, "set"))
|
|
799
|
+
return wrongType();
|
|
720
800
|
const s = setStore.get(key);
|
|
721
801
|
if (!s)
|
|
722
802
|
return ok(0);
|
|
723
803
|
let count = 0;
|
|
724
|
-
for (const member of
|
|
725
|
-
if (s.delete(
|
|
804
|
+
for (const member of serialized) {
|
|
805
|
+
if (s.delete(member))
|
|
726
806
|
count++;
|
|
727
807
|
}
|
|
808
|
+
if (!s.size)
|
|
809
|
+
deleteKey(key);
|
|
728
810
|
return ok(count);
|
|
729
811
|
},
|
|
730
812
|
async smembers(key) {
|
|
@@ -734,48 +816,54 @@ function createMemoryProvider() {
|
|
|
734
816
|
return ok(Array.from(s).map((v) => deserializeValue(v)));
|
|
735
817
|
},
|
|
736
818
|
async sismember(key, member) {
|
|
819
|
+
const serialized = serializeCacheValue(member);
|
|
820
|
+
if (hasWrongType(key, "set"))
|
|
821
|
+
return wrongType();
|
|
737
822
|
const s = setStore.get(key);
|
|
738
|
-
return ok(s?.has(
|
|
823
|
+
return ok(s?.has(serialized) ?? false);
|
|
739
824
|
},
|
|
740
825
|
async scard(key) {
|
|
741
826
|
const s = setStore.get(key);
|
|
742
827
|
return ok(s?.size ?? 0);
|
|
743
828
|
},
|
|
744
829
|
async srandmember(key, count) {
|
|
830
|
+
if (count !== void 0 && !Number.isSafeInteger(count))
|
|
831
|
+
return operationFailure("Invalid random member count");
|
|
745
832
|
const s = setStore.get(key);
|
|
746
|
-
if (!s || s.size === 0)
|
|
747
|
-
return ok(null);
|
|
748
|
-
const arr = Array.from(s);
|
|
749
|
-
if (count === void 0) {
|
|
750
|
-
const idx = Math.floor(Math.random() * arr.length);
|
|
751
|
-
return ok(deserializeValue(arr[idx]));
|
|
833
|
+
if (!s || s.size === 0) {
|
|
834
|
+
return ok(count === void 0 ? null : []);
|
|
752
835
|
}
|
|
753
|
-
const
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
836
|
+
const arr = Array.from(s);
|
|
837
|
+
if (count === void 0)
|
|
838
|
+
return ok(deserializeValue(drawMember(arr)));
|
|
839
|
+
if (count < 0) {
|
|
840
|
+
return ok(Array.from({ length: -count }, () => {
|
|
841
|
+
const index = Math.floor(Math.random() * arr.length);
|
|
842
|
+
return deserializeValue(arr[index]);
|
|
843
|
+
}));
|
|
757
844
|
}
|
|
758
|
-
return ok(
|
|
845
|
+
return ok(Array.from({
|
|
846
|
+
length: Math.min(count, arr.length)
|
|
847
|
+
}, () => deserializeValue(drawMember(arr))));
|
|
759
848
|
},
|
|
760
849
|
async spop(key, count) {
|
|
850
|
+
if (count !== void 0 && (!Number.isSafeInteger(count) || count < 0))
|
|
851
|
+
return operationFailure("Invalid pop count");
|
|
761
852
|
const s = setStore.get(key);
|
|
762
|
-
if (!s || s.size === 0)
|
|
763
|
-
return ok(null);
|
|
764
|
-
const arr = Array.from(s);
|
|
765
|
-
if (count === void 0) {
|
|
766
|
-
const idx = Math.floor(Math.random() * arr.length);
|
|
767
|
-
const val = arr[idx];
|
|
768
|
-
s.delete(val);
|
|
769
|
-
return ok(deserializeValue(val));
|
|
853
|
+
if (!s || s.size === 0) {
|
|
854
|
+
return ok(count === void 0 ? null : []);
|
|
770
855
|
}
|
|
771
|
-
const
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
856
|
+
const arr = Array.from(s);
|
|
857
|
+
const result = Array.from({
|
|
858
|
+
length: Math.min(count ?? 1, arr.length)
|
|
859
|
+
}, () => {
|
|
860
|
+
const member = drawMember(arr);
|
|
861
|
+
s.delete(member);
|
|
862
|
+
return deserializeValue(member);
|
|
863
|
+
});
|
|
864
|
+
if (!s.size)
|
|
865
|
+
deleteKey(key);
|
|
866
|
+
return ok(count === void 0 ? result[0] : result);
|
|
779
867
|
},
|
|
780
868
|
async sinter(...keys) {
|
|
781
869
|
if (keys.length === 0)
|
|
@@ -810,17 +898,20 @@ function createMemoryProvider() {
|
|
|
810
898
|
};
|
|
811
899
|
const zset = {
|
|
812
900
|
async zadd(key, ...members) {
|
|
813
|
-
|
|
814
|
-
if (
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
901
|
+
const entries = members.map(({ member, score }) => ({ member, score }));
|
|
902
|
+
if (entries.some(({ score }) => typeof score !== "number" || Number.isNaN(score)))
|
|
903
|
+
return operationFailure("Invalid sorted set score");
|
|
904
|
+
if (hasWrongType(key, "zset"))
|
|
905
|
+
return wrongType();
|
|
906
|
+
const map = zsetStore.get(key) ?? /* @__PURE__ */ new Map();
|
|
818
907
|
let count = 0;
|
|
819
|
-
for (const { score, member } of
|
|
908
|
+
for (const { score, member } of entries) {
|
|
820
909
|
if (!map.has(member))
|
|
821
910
|
count++;
|
|
822
911
|
map.set(member, score);
|
|
823
912
|
}
|
|
913
|
+
if (map.size)
|
|
914
|
+
zsetStore.set(key, map);
|
|
824
915
|
return ok(count);
|
|
825
916
|
},
|
|
826
917
|
async zrem(key, ...members) {
|
|
@@ -832,6 +923,8 @@ function createMemoryProvider() {
|
|
|
832
923
|
if (map.delete(member))
|
|
833
924
|
count++;
|
|
834
925
|
}
|
|
926
|
+
if (!map.size)
|
|
927
|
+
deleteKey(key);
|
|
835
928
|
return ok(count);
|
|
836
929
|
},
|
|
837
930
|
async zscore(key, member) {
|
|
@@ -843,7 +936,7 @@ function createMemoryProvider() {
|
|
|
843
936
|
const map = zsetStore.get(key);
|
|
844
937
|
if (!map || !map.has(member))
|
|
845
938
|
return ok(null);
|
|
846
|
-
const sorted = Array.from(map.entries()).sort(
|
|
939
|
+
const sorted = Array.from(map.entries()).sort(compareRanks);
|
|
847
940
|
const idx = sorted.findIndex(([m]) => m === member);
|
|
848
941
|
return ok(idx >= 0 ? idx : null);
|
|
849
942
|
},
|
|
@@ -851,50 +944,35 @@ function createMemoryProvider() {
|
|
|
851
944
|
const map = zsetStore.get(key);
|
|
852
945
|
if (!map || !map.has(member))
|
|
853
946
|
return ok(null);
|
|
854
|
-
const sorted = Array.from(map.entries()).sort((
|
|
947
|
+
const sorted = Array.from(map.entries()).sort((left, right) => compareRanks(right, left));
|
|
855
948
|
const idx = sorted.findIndex(([m]) => m === member);
|
|
856
949
|
return ok(idx >= 0 ? idx : null);
|
|
857
950
|
},
|
|
858
951
|
async zrange(key, start, stop, withScores) {
|
|
859
|
-
const
|
|
860
|
-
|
|
861
|
-
return ok([]);
|
|
862
|
-
const sorted = Array.from(map.entries()).sort((a, b) => a[1] - b[1]);
|
|
863
|
-
const len = sorted.length;
|
|
864
|
-
const s = start < 0 ? Math.max(len + start, 0) : start;
|
|
865
|
-
const e = stop < 0 ? len + stop + 1 : stop + 1;
|
|
866
|
-
const slice = sorted.slice(s, e);
|
|
952
|
+
const sorted = Array.from(zsetStore.get(key) ?? []).sort(compareRanks);
|
|
953
|
+
const slice = sliceByRank(sorted, start, stop);
|
|
867
954
|
if (withScores) {
|
|
868
955
|
return ok(slice.map(([member, score]) => ({ member, score })));
|
|
869
956
|
}
|
|
870
957
|
return ok(slice.map(([member]) => member));
|
|
871
958
|
},
|
|
872
959
|
async zrevrange(key, start, stop, withScores) {
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
return ok([]);
|
|
876
|
-
const sorted = Array.from(map.entries()).sort((a, b) => b[1] - a[1]);
|
|
877
|
-
const len = sorted.length;
|
|
878
|
-
const s = start < 0 ? Math.max(len + start, 0) : start;
|
|
879
|
-
const e = stop < 0 ? len + stop + 1 : stop + 1;
|
|
880
|
-
const slice = sorted.slice(s, e);
|
|
960
|
+
const sorted = Array.from(zsetStore.get(key) ?? []).sort((left, right) => compareRanks(right, left));
|
|
961
|
+
const slice = sliceByRank(sorted, start, stop);
|
|
881
962
|
if (withScores) {
|
|
882
963
|
return ok(slice.map(([member, score]) => ({ member, score })));
|
|
883
964
|
}
|
|
884
965
|
return ok(slice.map(([member]) => member));
|
|
885
966
|
},
|
|
886
967
|
async zrangeByScore(key, min, max, options) {
|
|
887
|
-
const
|
|
888
|
-
|
|
968
|
+
const inRange = scoreRange(min, max);
|
|
969
|
+
const offset = options?.offset ?? 0;
|
|
970
|
+
const count = options?.count ?? -1;
|
|
971
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(count))
|
|
972
|
+
return operationFailure("Invalid sorted set pagination");
|
|
973
|
+
if (offset < 0 || count === 0)
|
|
889
974
|
return ok([]);
|
|
890
|
-
const
|
|
891
|
-
const maxVal = max === "+inf" ? Number.POSITIVE_INFINITY : Number(max);
|
|
892
|
-
let sorted = Array.from(map.entries()).filter(([, score]) => score >= minVal && score <= maxVal).sort((a, b) => a[1] - b[1]);
|
|
893
|
-
if (options?.offset !== void 0 || options?.count !== void 0) {
|
|
894
|
-
const offset = options.offset ?? 0;
|
|
895
|
-
const count = options.count ?? sorted.length;
|
|
896
|
-
sorted = sorted.slice(offset, offset + count);
|
|
897
|
-
}
|
|
975
|
+
const sorted = Array.from(zsetStore.get(key) ?? []).filter(([, score]) => inRange(score)).sort(compareRanks).slice(offset, count < 0 ? void 0 : offset + count);
|
|
898
976
|
if (options?.withScores) {
|
|
899
977
|
return ok(sorted.map(([member, score]) => ({ member, score })));
|
|
900
978
|
}
|
|
@@ -905,102 +983,124 @@ function createMemoryProvider() {
|
|
|
905
983
|
return ok(map?.size ?? 0);
|
|
906
984
|
},
|
|
907
985
|
async zcount(key, min, max) {
|
|
986
|
+
const inRange = scoreRange(min, max);
|
|
908
987
|
const map = zsetStore.get(key);
|
|
909
988
|
if (!map)
|
|
910
989
|
return ok(0);
|
|
911
|
-
const minVal = min === "-inf" ? Number.NEGATIVE_INFINITY : Number(min);
|
|
912
|
-
const maxVal = max === "+inf" ? Number.POSITIVE_INFINITY : Number(max);
|
|
913
990
|
let count = 0;
|
|
914
991
|
for (const score of map.values()) {
|
|
915
|
-
if (score
|
|
992
|
+
if (inRange(score))
|
|
916
993
|
count++;
|
|
917
994
|
}
|
|
918
995
|
return ok(count);
|
|
919
996
|
},
|
|
920
997
|
async zincrBy(key, increment, member) {
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
zsetStore.set(key, map);
|
|
925
|
-
}
|
|
998
|
+
if (typeof increment !== "number")
|
|
999
|
+
return operationFailure("Invalid sorted set increment");
|
|
1000
|
+
const map = zsetStore.get(key) ?? /* @__PURE__ */ new Map();
|
|
926
1001
|
const current = map.get(member) ?? 0;
|
|
927
1002
|
const newScore = current + increment;
|
|
1003
|
+
if (Number.isNaN(newScore))
|
|
1004
|
+
return operationFailure("Invalid sorted set score");
|
|
928
1005
|
map.set(member, newScore);
|
|
1006
|
+
zsetStore.set(key, map);
|
|
929
1007
|
return ok(newScore);
|
|
930
1008
|
},
|
|
931
1009
|
async zremRangeByRank(key, start, stop) {
|
|
932
|
-
const map = zsetStore.get(key);
|
|
933
|
-
|
|
934
|
-
return ok(0);
|
|
935
|
-
const sorted = Array.from(map.entries()).sort((a, b) => a[1] - b[1]);
|
|
936
|
-
const len = sorted.length;
|
|
937
|
-
const s = start < 0 ? Math.max(len + start, 0) : start;
|
|
938
|
-
const e = stop < 0 ? len + stop + 1 : stop + 1;
|
|
939
|
-
const toRemove = sorted.slice(s, e);
|
|
1010
|
+
const map = zsetStore.get(key) ?? /* @__PURE__ */ new Map();
|
|
1011
|
+
const toRemove = sliceByRank(Array.from(map.entries()).sort(compareRanks), start, stop);
|
|
940
1012
|
for (const [member] of toRemove) {
|
|
941
1013
|
map.delete(member);
|
|
942
1014
|
}
|
|
1015
|
+
if (!map.size)
|
|
1016
|
+
deleteKey(key);
|
|
943
1017
|
return ok(toRemove.length);
|
|
944
1018
|
},
|
|
945
1019
|
async zremRangeByScore(key, min, max) {
|
|
1020
|
+
const inRange = scoreRange(min, max);
|
|
946
1021
|
const map = zsetStore.get(key);
|
|
947
1022
|
if (!map)
|
|
948
1023
|
return ok(0);
|
|
949
|
-
const minVal = min === "-inf" ? Number.NEGATIVE_INFINITY : Number(min);
|
|
950
|
-
const maxVal = max === "+inf" ? Number.POSITIVE_INFINITY : Number(max);
|
|
951
1024
|
let count = 0;
|
|
952
1025
|
for (const [member, score] of map.entries()) {
|
|
953
|
-
if (score
|
|
1026
|
+
if (inRange(score)) {
|
|
954
1027
|
map.delete(member);
|
|
955
1028
|
count++;
|
|
956
1029
|
}
|
|
957
1030
|
}
|
|
1031
|
+
if (!map.size)
|
|
1032
|
+
deleteKey(key);
|
|
958
1033
|
return ok(count);
|
|
959
1034
|
}
|
|
960
1035
|
};
|
|
961
1036
|
const LOCK_PREFIX = "__lock:";
|
|
1037
|
+
function getOwnedLock(key, owner) {
|
|
1038
|
+
if (!isValidLockOwner(owner))
|
|
1039
|
+
return void 0;
|
|
1040
|
+
const entry = getValidEntry(key);
|
|
1041
|
+
if (!entry || typeof entry.value !== "string")
|
|
1042
|
+
return void 0;
|
|
1043
|
+
if (entry.value === owner)
|
|
1044
|
+
return { entry, depth: 1 };
|
|
1045
|
+
const prefix = `${owner}|`;
|
|
1046
|
+
if (!entry.value.startsWith(prefix))
|
|
1047
|
+
return void 0;
|
|
1048
|
+
const count = entry.value.slice(prefix.length);
|
|
1049
|
+
const depth = Number(count);
|
|
1050
|
+
if (/^[1-9]\d*$/.test(count) && Number.isSafeInteger(depth) && depth > 1)
|
|
1051
|
+
return { entry, depth };
|
|
1052
|
+
return void 0;
|
|
1053
|
+
}
|
|
962
1054
|
const lock = {
|
|
963
1055
|
async acquire(key, options) {
|
|
964
1056
|
const lockKey = `${LOCK_PREFIX}${key}`;
|
|
965
|
-
const ttl = options
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
1057
|
+
const { owner, ttl: configuredTtl } = options ?? {};
|
|
1058
|
+
if (owner !== void 0) {
|
|
1059
|
+
if (configuredTtl !== void 0)
|
|
1060
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockOwnerOptions"));
|
|
1061
|
+
const held = getOwnedLock(lockKey, owner);
|
|
1062
|
+
if (!held || held.depth === Number.MAX_SAFE_INTEGER)
|
|
1063
|
+
return ok(null);
|
|
1064
|
+
held.entry.value = `${owner}|${held.depth + 1}`;
|
|
1065
|
+
return ok(owner);
|
|
970
1066
|
}
|
|
1067
|
+
const ttl = configuredTtl === void 0 ? 30 : configuredTtl;
|
|
1068
|
+
if (!isValidLockTtl(ttl))
|
|
1069
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockTtl"));
|
|
1070
|
+
if (keyType(lockKey) !== "none")
|
|
1071
|
+
return ok(null);
|
|
1072
|
+
const token = core.id.uuid();
|
|
971
1073
|
store.set(lockKey, {
|
|
972
|
-
value:
|
|
1074
|
+
value: token,
|
|
973
1075
|
expiresAt: Date.now() + ttl * 1e3
|
|
974
1076
|
});
|
|
975
|
-
return ok(
|
|
1077
|
+
return ok(token);
|
|
976
1078
|
},
|
|
977
1079
|
async release(key, owner) {
|
|
978
1080
|
const lockKey = `${LOCK_PREFIX}${key}`;
|
|
979
|
-
const
|
|
980
|
-
if (!
|
|
1081
|
+
const held = getOwnedLock(lockKey, owner);
|
|
1082
|
+
if (!held)
|
|
981
1083
|
return ok(false);
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1084
|
+
if (held.depth === 1)
|
|
1085
|
+
store.delete(lockKey);
|
|
1086
|
+
else if (held.depth === 2)
|
|
1087
|
+
held.entry.value = owner;
|
|
1088
|
+
else
|
|
1089
|
+
held.entry.value = `${owner}|${held.depth - 1}`;
|
|
987
1090
|
return ok(true);
|
|
988
1091
|
},
|
|
989
1092
|
async isLocked(key) {
|
|
990
1093
|
const lockKey = `${LOCK_PREFIX}${key}`;
|
|
991
|
-
|
|
992
|
-
return ok(entry !== null);
|
|
1094
|
+
return ok(keyType(lockKey) !== "none");
|
|
993
1095
|
},
|
|
994
1096
|
async extend(key, ttl, owner) {
|
|
1097
|
+
if (!isValidLockTtl(ttl))
|
|
1098
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockTtl"));
|
|
995
1099
|
const lockKey = `${LOCK_PREFIX}${key}`;
|
|
996
|
-
const
|
|
997
|
-
if (!
|
|
1100
|
+
const held = getOwnedLock(lockKey, owner);
|
|
1101
|
+
if (!held)
|
|
998
1102
|
return ok(false);
|
|
999
|
-
|
|
1000
|
-
if (!owner || entry.value !== owner) {
|
|
1001
|
-
return ok(false);
|
|
1002
|
-
}
|
|
1003
|
-
entry.expiresAt = Date.now() + ttl * 1e3;
|
|
1103
|
+
held.entry.expiresAt = Date.now() + ttl * 1e3;
|
|
1004
1104
|
return ok(true);
|
|
1005
1105
|
}
|
|
1006
1106
|
};
|
|
@@ -1128,6 +1228,23 @@ function redisErrorDiagnostics(error) {
|
|
|
1128
1228
|
causeCode: typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : cause instanceof Error ? /^(NOAUTH|WRONGPASS|NOPERM|LOADING|CLUSTERDOWN)\b/.exec(cause.message)?.[1] : void 0
|
|
1129
1229
|
};
|
|
1130
1230
|
}
|
|
1231
|
+
function deserializeScore(score) {
|
|
1232
|
+
if (score === "inf")
|
|
1233
|
+
return Infinity;
|
|
1234
|
+
if (score === "-inf")
|
|
1235
|
+
return -Infinity;
|
|
1236
|
+
return Number(score);
|
|
1237
|
+
}
|
|
1238
|
+
function deserializeScoredMembers(result) {
|
|
1239
|
+
const members = [];
|
|
1240
|
+
for (let i = 0; i < result.length; i += 2) {
|
|
1241
|
+
members.push({
|
|
1242
|
+
member: result[i],
|
|
1243
|
+
score: deserializeScore(result[i + 1])
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
return members;
|
|
1247
|
+
}
|
|
1131
1248
|
var COMPARE_AND_SWAP_SCRIPT = `
|
|
1132
1249
|
local current = redis.call('get', KEYS[1])
|
|
1133
1250
|
if ARGV[1] == 'missing' then
|
|
@@ -1144,49 +1261,120 @@ var COMPARE_AND_SWAP_SCRIPT = `
|
|
|
1144
1261
|
end
|
|
1145
1262
|
return 1
|
|
1146
1263
|
`;
|
|
1147
|
-
var
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1264
|
+
var UPDATE_LOCK_SCRIPT = `
|
|
1265
|
+
local key, owner, operation = KEYS[1], ARGV[1], ARGV[2]
|
|
1266
|
+
local value = redis.call('get', key)
|
|
1267
|
+
if not value then return 0 end
|
|
1268
|
+
|
|
1269
|
+
local depth = 1
|
|
1270
|
+
local maxDepth = 9007199254740991
|
|
1271
|
+
if value ~= owner then
|
|
1272
|
+
local storedOwner, storedDepth = string.match(value, '^(.-)|([1-9]%d*)$')
|
|
1273
|
+
if storedOwner ~= owner then return 0 end
|
|
1274
|
+
depth = tonumber(storedDepth)
|
|
1275
|
+
if depth < 2 or depth > maxDepth then return 0 end
|
|
1152
1276
|
end
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1277
|
+
|
|
1278
|
+
if operation == 'extend' then
|
|
1279
|
+
return redis.call('expire', key, ARGV[3])
|
|
1280
|
+
end
|
|
1281
|
+
if operation == 'release' then
|
|
1282
|
+
if depth == 1 then return redis.call('del', key) end
|
|
1283
|
+
depth = depth - 1
|
|
1157
1284
|
else
|
|
1158
|
-
return 0
|
|
1285
|
+
if depth == maxDepth then return 0 end
|
|
1286
|
+
depth = depth + 1
|
|
1159
1287
|
end
|
|
1288
|
+
|
|
1289
|
+
local nextValue = owner
|
|
1290
|
+
if depth > 1 then nextValue = owner .. '|' .. string.format('%.0f', depth) end
|
|
1291
|
+
redis.call('set', key, nextValue, 'KEEPTTL')
|
|
1292
|
+
return 1
|
|
1160
1293
|
`;
|
|
1294
|
+
function duplicateWithoutReplay(source, overrides = {}) {
|
|
1295
|
+
const redisOptions = { ...overrides, autoResendUnfulfilledCommands: false };
|
|
1296
|
+
if (!(source instanceof Redis.Cluster))
|
|
1297
|
+
return source.duplicate({ ...redisOptions, retryStrategy: null });
|
|
1298
|
+
return source.duplicate(
|
|
1299
|
+
source.nodes("master").map((node) => ({ host: node.options.host, port: node.options.port })),
|
|
1300
|
+
{
|
|
1301
|
+
clusterRetryStrategy: () => null,
|
|
1302
|
+
retryDelayOnFailover: 0,
|
|
1303
|
+
redisOptions
|
|
1304
|
+
}
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
async function withCancellation(signal, start) {
|
|
1308
|
+
signal.throwIfAborted();
|
|
1309
|
+
let rejectCancellation;
|
|
1310
|
+
const canceled = new Promise((_resolve, reject) => {
|
|
1311
|
+
rejectCancellation = reject;
|
|
1312
|
+
});
|
|
1313
|
+
const cancel = () => rejectCancellation(signal.reason);
|
|
1314
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1315
|
+
try {
|
|
1316
|
+
return await Promise.race([
|
|
1317
|
+
canceled,
|
|
1318
|
+
Promise.resolve().then(() => {
|
|
1319
|
+
signal.throwIfAborted();
|
|
1320
|
+
return start();
|
|
1321
|
+
})
|
|
1322
|
+
]);
|
|
1323
|
+
} finally {
|
|
1324
|
+
signal.removeEventListener("abort", cancel);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1161
1327
|
function createRedisProvider() {
|
|
1162
1328
|
let client = null;
|
|
1163
1329
|
let ready = false;
|
|
1164
1330
|
let closing = null;
|
|
1331
|
+
let lockConnection = null;
|
|
1332
|
+
const blockingClients = /* @__PURE__ */ new Map();
|
|
1333
|
+
function cancelLockConnection(connection) {
|
|
1334
|
+
connection.cancellation.abort(new Error(cacheM("cache_lockOperationInterrupted")));
|
|
1335
|
+
}
|
|
1336
|
+
function disconnectLockConnection(connection) {
|
|
1337
|
+
if (connection && connection === lockConnection) {
|
|
1338
|
+
cancelLockConnection(connection);
|
|
1339
|
+
connection.client.disconnect();
|
|
1340
|
+
lockConnection = null;
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
function disconnectBlockingClient(blockingClient) {
|
|
1344
|
+
if (blockingClients.has(blockingClient)) {
|
|
1345
|
+
blockingClient.disconnect();
|
|
1346
|
+
blockingClients.delete(blockingClient);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1165
1349
|
function closeClient() {
|
|
1166
1350
|
const graceful = ready && client?.status === "ready";
|
|
1167
1351
|
ready = false;
|
|
1168
1352
|
if (closing)
|
|
1169
1353
|
return closing;
|
|
1170
1354
|
const owned = client;
|
|
1171
|
-
if (!owned)
|
|
1355
|
+
if (!owned && !lockConnection && blockingClients.size === 0)
|
|
1172
1356
|
return Promise.resolve();
|
|
1173
1357
|
closing = (async () => {
|
|
1358
|
+
for (const cancellation of blockingClients.values())
|
|
1359
|
+
cancellation.abort(new Error(cacheM("cache_blockingPopCanceled")));
|
|
1360
|
+
if (lockConnection)
|
|
1361
|
+
cancelLockConnection(lockConnection);
|
|
1362
|
+
for (const blockingClient of blockingClients.keys())
|
|
1363
|
+
disconnectBlockingClient(blockingClient);
|
|
1364
|
+
disconnectLockConnection(lockConnection);
|
|
1174
1365
|
try {
|
|
1175
|
-
if (graceful)
|
|
1366
|
+
if (graceful && owned)
|
|
1176
1367
|
await owned.quit();
|
|
1177
1368
|
} catch (error) {
|
|
1178
1369
|
logger.warn("Redis graceful shutdown failed; disconnecting client", redisErrorDiagnostics(error));
|
|
1179
1370
|
}
|
|
1180
|
-
owned
|
|
1371
|
+
owned?.disconnect();
|
|
1181
1372
|
client = null;
|
|
1182
1373
|
})().finally(() => {
|
|
1183
1374
|
closing = null;
|
|
1184
1375
|
});
|
|
1185
1376
|
return closing;
|
|
1186
1377
|
}
|
|
1187
|
-
function serialize(value) {
|
|
1188
|
-
return JSON.stringify(value);
|
|
1189
|
-
}
|
|
1190
1378
|
function deserialize(value) {
|
|
1191
1379
|
if (value === null)
|
|
1192
1380
|
return null;
|
|
@@ -1207,6 +1395,8 @@ function createRedisProvider() {
|
|
|
1207
1395
|
const result = await operation();
|
|
1208
1396
|
return ok(result);
|
|
1209
1397
|
} catch (error) {
|
|
1398
|
+
if (error instanceof CacheSerializationError)
|
|
1399
|
+
return err(HaiCacheError.SERIALIZATION_FAILED, cacheM("cache_serializationFailed"), error);
|
|
1210
1400
|
if (error instanceof RedisScanError) {
|
|
1211
1401
|
return error.reason === "topology" ? err(HaiCacheError.SCAN_TOPOLOGY_CHANGED, cacheM("cache_scanTopologyChanged"), error) : err(HaiCacheError.INVALID_SCAN, cacheM("cache_invalidScan"), error);
|
|
1212
1402
|
}
|
|
@@ -1226,6 +1416,47 @@ function createRedisProvider() {
|
|
|
1226
1416
|
function isRedisOne(result) {
|
|
1227
1417
|
return result === 1 || result === "1";
|
|
1228
1418
|
}
|
|
1419
|
+
function getLockConnection() {
|
|
1420
|
+
if (lockConnection?.cancellation.signal.aborted)
|
|
1421
|
+
disconnectLockConnection(lockConnection);
|
|
1422
|
+
if (lockConnection)
|
|
1423
|
+
return lockConnection;
|
|
1424
|
+
const owned = duplicateWithoutReplay(client);
|
|
1425
|
+
const cancellation = new AbortController();
|
|
1426
|
+
setMaxListeners(0, cancellation.signal);
|
|
1427
|
+
const connection = {
|
|
1428
|
+
client: owned,
|
|
1429
|
+
cancellation,
|
|
1430
|
+
connected: withCancellation(cancellation.signal, () => owned.connect())
|
|
1431
|
+
};
|
|
1432
|
+
lockConnection = connection;
|
|
1433
|
+
owned.on("error", (error) => {
|
|
1434
|
+
if (!cancellation.signal.aborted)
|
|
1435
|
+
logger.warn("Redis lock connection error", redisErrorDiagnostics(error));
|
|
1436
|
+
});
|
|
1437
|
+
owned.once("end", () => {
|
|
1438
|
+
cancelLockConnection(connection);
|
|
1439
|
+
if (lockConnection === connection)
|
|
1440
|
+
lockConnection = null;
|
|
1441
|
+
});
|
|
1442
|
+
return connection;
|
|
1443
|
+
}
|
|
1444
|
+
async function runLockMutation(operation) {
|
|
1445
|
+
const connection = getLockConnection();
|
|
1446
|
+
try {
|
|
1447
|
+
await connection.connected;
|
|
1448
|
+
return await withCancellation(connection.cancellation.signal, () => operation(connection.client));
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
if (connection.client.status !== "ready" || error instanceof Error && ["Connection is closed.", "Command timed out"].includes(error.message)) {
|
|
1451
|
+
try {
|
|
1452
|
+
disconnectLockConnection(connection);
|
|
1453
|
+
} catch (cleanupError) {
|
|
1454
|
+
logger.warn("Redis lock connection cleanup failed", redisErrorDiagnostics(cleanupError));
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
throw error;
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1229
1460
|
async function mapIndependentKeys(keys, operation) {
|
|
1230
1461
|
const values = [];
|
|
1231
1462
|
for (let offset = 0; offset < keys.length; offset += 64)
|
|
@@ -1237,7 +1468,7 @@ function createRedisProvider() {
|
|
|
1237
1468
|
return wrapOperation(async () => {
|
|
1238
1469
|
if (options?.px !== void 0 && (!Number.isSafeInteger(options.px) || options.px <= 0) || options?.px !== void 0 && options.keepTtl)
|
|
1239
1470
|
throw new TypeError("Invalid compare-and-swap expiry");
|
|
1240
|
-
return isRedisOne(await client.eval(COMPARE_AND_SWAP_SCRIPT, 1, key, expected === void 0 ? "missing" : "value", expected === void 0 ? "" :
|
|
1471
|
+
return isRedisOne(await client.eval(COMPARE_AND_SWAP_SCRIPT, 1, key, expected === void 0 ? "missing" : "value", expected === void 0 ? "" : serializeCacheValue(expected), value === void 0 ? "delete" : "value", value === void 0 ? "" : serializeCacheValue(value), options?.keepTtl ? "keep" : options?.px !== void 0 ? "px" : "none", options?.px ?? 0));
|
|
1241
1472
|
});
|
|
1242
1473
|
},
|
|
1243
1474
|
async get(key) {
|
|
@@ -1254,7 +1485,7 @@ function createRedisProvider() {
|
|
|
1254
1485
|
const policy = validated.data;
|
|
1255
1486
|
const args = [
|
|
1256
1487
|
key,
|
|
1257
|
-
|
|
1488
|
+
serializeCacheValue(value)
|
|
1258
1489
|
];
|
|
1259
1490
|
if (policy.expiry)
|
|
1260
1491
|
args.push(...policy.expiry);
|
|
@@ -1323,7 +1554,8 @@ function createRedisProvider() {
|
|
|
1323
1554
|
},
|
|
1324
1555
|
async mget(...keys) {
|
|
1325
1556
|
return wrapOperation(async () => {
|
|
1326
|
-
const
|
|
1557
|
+
const source = client;
|
|
1558
|
+
const values = keys.length === 0 ? [] : source instanceof Redis.Cluster ? await mapIndependentKeys(keys, async (key) => (await source.mget(key))[0]) : await source.mget(...keys);
|
|
1327
1559
|
return values.map((v) => deserialize(v));
|
|
1328
1560
|
});
|
|
1329
1561
|
},
|
|
@@ -1333,7 +1565,7 @@ function createRedisProvider() {
|
|
|
1333
1565
|
return;
|
|
1334
1566
|
const args = [];
|
|
1335
1567
|
for (const [key, value] of entries) {
|
|
1336
|
-
args.push(key,
|
|
1568
|
+
args.push(key, serializeCacheValue(value));
|
|
1337
1569
|
}
|
|
1338
1570
|
await client.mset(...args);
|
|
1339
1571
|
});
|
|
@@ -1373,12 +1605,12 @@ function createRedisProvider() {
|
|
|
1373
1605
|
}
|
|
1374
1606
|
return wrapOperation(async () => {
|
|
1375
1607
|
if (typeof fieldOrData === "string" && value !== void 0) {
|
|
1376
|
-
return client.hset(key, fieldOrData,
|
|
1608
|
+
return client.hset(key, fieldOrData, serializeCacheValue(value));
|
|
1377
1609
|
}
|
|
1378
1610
|
if (typeof fieldOrData === "object") {
|
|
1379
1611
|
const serialized = Object.fromEntries(Object.entries(fieldOrData).map(([key2, value2]) => [
|
|
1380
1612
|
key2,
|
|
1381
|
-
|
|
1613
|
+
serializeCacheValue(value2)
|
|
1382
1614
|
]));
|
|
1383
1615
|
return client.hset(key, serialized);
|
|
1384
1616
|
}
|
|
@@ -1425,12 +1657,42 @@ function createRedisProvider() {
|
|
|
1425
1657
|
return wrapOperation(() => client.hincrby(key, field, increment));
|
|
1426
1658
|
}
|
|
1427
1659
|
};
|
|
1660
|
+
function popBlocking(method, timeout, keys) {
|
|
1661
|
+
return wrapOperation(async () => {
|
|
1662
|
+
const source = client;
|
|
1663
|
+
const blockingClient = duplicateWithoutReplay(source, { commandTimeout: void 0 });
|
|
1664
|
+
const cancellation = new AbortController();
|
|
1665
|
+
const { signal } = cancellation;
|
|
1666
|
+
blockingClients.set(blockingClient, cancellation);
|
|
1667
|
+
blockingClient.on("error", (error) => {
|
|
1668
|
+
if (!signal.aborted)
|
|
1669
|
+
logger.warn("Redis blocking connection error", redisErrorDiagnostics(error));
|
|
1670
|
+
});
|
|
1671
|
+
blockingClient.once("end", () => cancellation.abort(new Error(cacheM("cache_blockingPopCanceled"))));
|
|
1672
|
+
try {
|
|
1673
|
+
const result = await withCancellation(signal, async () => {
|
|
1674
|
+
await blockingClient.connect();
|
|
1675
|
+
signal.throwIfAborted();
|
|
1676
|
+
return blockingClient[method](...keys, timeout);
|
|
1677
|
+
});
|
|
1678
|
+
if (!result)
|
|
1679
|
+
return null;
|
|
1680
|
+
const prefix = source.options.keyPrefix ?? "";
|
|
1681
|
+
return [
|
|
1682
|
+
result[0].slice(prefix.length),
|
|
1683
|
+
deserialize(result[1])
|
|
1684
|
+
];
|
|
1685
|
+
} finally {
|
|
1686
|
+
disconnectBlockingClient(blockingClient);
|
|
1687
|
+
}
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1428
1690
|
const list = {
|
|
1429
1691
|
async lpush(key, ...values) {
|
|
1430
|
-
return wrapOperation(() => client.lpush(key, ...values.map(
|
|
1692
|
+
return wrapOperation(() => client.lpush(key, ...values.map(serializeCacheValue)));
|
|
1431
1693
|
},
|
|
1432
1694
|
async rpush(key, ...values) {
|
|
1433
|
-
return wrapOperation(() => client.rpush(key, ...values.map(
|
|
1695
|
+
return wrapOperation(() => client.rpush(key, ...values.map(serializeCacheValue)));
|
|
1434
1696
|
},
|
|
1435
1697
|
async lpop(key) {
|
|
1436
1698
|
return wrapOperation(async () => {
|
|
@@ -1461,7 +1723,7 @@ function createRedisProvider() {
|
|
|
1461
1723
|
},
|
|
1462
1724
|
async lset(key, index, value) {
|
|
1463
1725
|
return wrapOperation(async () => {
|
|
1464
|
-
await client.lset(key, index,
|
|
1726
|
+
await client.lset(key, index, serializeCacheValue(value));
|
|
1465
1727
|
});
|
|
1466
1728
|
},
|
|
1467
1729
|
async ltrim(key, start, stop) {
|
|
@@ -1470,34 +1732,18 @@ function createRedisProvider() {
|
|
|
1470
1732
|
});
|
|
1471
1733
|
},
|
|
1472
1734
|
async blpop(timeout, ...keys) {
|
|
1473
|
-
return
|
|
1474
|
-
const result = await client.blpop(...keys, timeout);
|
|
1475
|
-
if (!result)
|
|
1476
|
-
return null;
|
|
1477
|
-
return [
|
|
1478
|
-
result[0],
|
|
1479
|
-
deserialize(result[1])
|
|
1480
|
-
];
|
|
1481
|
-
});
|
|
1735
|
+
return popBlocking("blpop", timeout, keys);
|
|
1482
1736
|
},
|
|
1483
1737
|
async brpop(timeout, ...keys) {
|
|
1484
|
-
return
|
|
1485
|
-
const result = await client.brpop(...keys, timeout);
|
|
1486
|
-
if (!result)
|
|
1487
|
-
return null;
|
|
1488
|
-
return [
|
|
1489
|
-
result[0],
|
|
1490
|
-
deserialize(result[1])
|
|
1491
|
-
];
|
|
1492
|
-
});
|
|
1738
|
+
return popBlocking("brpop", timeout, keys);
|
|
1493
1739
|
}
|
|
1494
1740
|
};
|
|
1495
1741
|
const set_ = {
|
|
1496
1742
|
async sadd(key, ...members) {
|
|
1497
|
-
return wrapOperation(() => client.sadd(key, ...members.map(
|
|
1743
|
+
return wrapOperation(() => client.sadd(key, ...members.map(serializeCacheValue)));
|
|
1498
1744
|
},
|
|
1499
1745
|
async srem(key, ...members) {
|
|
1500
|
-
return wrapOperation(() => client.srem(key, ...members.map(
|
|
1746
|
+
return wrapOperation(() => client.srem(key, ...members.map(serializeCacheValue)));
|
|
1501
1747
|
},
|
|
1502
1748
|
async smembers(key) {
|
|
1503
1749
|
return wrapOperation(async () => {
|
|
@@ -1507,7 +1753,7 @@ function createRedisProvider() {
|
|
|
1507
1753
|
},
|
|
1508
1754
|
async sismember(key, member) {
|
|
1509
1755
|
return wrapOperation(async () => {
|
|
1510
|
-
const result = await client.sismember(key,
|
|
1756
|
+
const result = await client.sismember(key, serializeCacheValue(member));
|
|
1511
1757
|
return result === 1;
|
|
1512
1758
|
});
|
|
1513
1759
|
},
|
|
@@ -1569,7 +1815,7 @@ function createRedisProvider() {
|
|
|
1569
1815
|
async zscore(key, member) {
|
|
1570
1816
|
return wrapOperation(async () => {
|
|
1571
1817
|
const score = await client.zscore(key, member);
|
|
1572
|
-
return score !== null ?
|
|
1818
|
+
return score !== null ? deserializeScore(score) : null;
|
|
1573
1819
|
});
|
|
1574
1820
|
},
|
|
1575
1821
|
async zrank(key, member) {
|
|
@@ -1580,60 +1826,28 @@ function createRedisProvider() {
|
|
|
1580
1826
|
},
|
|
1581
1827
|
async zrange(key, start, stop, withScores) {
|
|
1582
1828
|
return wrapOperation(async () => {
|
|
1583
|
-
if (withScores)
|
|
1584
|
-
|
|
1585
|
-
const members = [];
|
|
1586
|
-
for (let i = 0; i < result.length; i += 2) {
|
|
1587
|
-
members.push({
|
|
1588
|
-
member: result[i],
|
|
1589
|
-
score: Number.parseFloat(result[i + 1])
|
|
1590
|
-
});
|
|
1591
|
-
}
|
|
1592
|
-
return members;
|
|
1593
|
-
}
|
|
1829
|
+
if (withScores)
|
|
1830
|
+
return deserializeScoredMembers(await client.zrange(key, String(start), String(stop), "WITHSCORES"));
|
|
1594
1831
|
return client.zrange(key, String(start), String(stop));
|
|
1595
1832
|
});
|
|
1596
1833
|
},
|
|
1597
1834
|
async zrevrange(key, start, stop, withScores) {
|
|
1598
1835
|
return wrapOperation(async () => {
|
|
1599
|
-
if (withScores)
|
|
1600
|
-
|
|
1601
|
-
const members = [];
|
|
1602
|
-
for (let i = 0; i < result.length; i += 2) {
|
|
1603
|
-
members.push({
|
|
1604
|
-
member: result[i],
|
|
1605
|
-
score: Number.parseFloat(result[i + 1])
|
|
1606
|
-
});
|
|
1607
|
-
}
|
|
1608
|
-
return members;
|
|
1609
|
-
}
|
|
1836
|
+
if (withScores)
|
|
1837
|
+
return deserializeScoredMembers(await client.zrevrange(key, start, stop, "WITHSCORES"));
|
|
1610
1838
|
return client.zrevrange(key, start, stop);
|
|
1611
1839
|
});
|
|
1612
1840
|
},
|
|
1613
1841
|
async zrangeByScore(key, min, max, options) {
|
|
1614
1842
|
return wrapOperation(async () => {
|
|
1615
|
-
const
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
String(max)
|
|
1619
|
-
];
|
|
1620
|
-
if (options?.withScores)
|
|
1621
|
-
args.push("WITHSCORES");
|
|
1622
|
-
if (options?.offset !== void 0 && options?.count !== void 0) {
|
|
1623
|
-
args.push("LIMIT", options.offset, options.count);
|
|
1624
|
-
}
|
|
1625
|
-
const result = await client.zrangebyscore.call(client, ...args);
|
|
1843
|
+
const paginated = options?.offset !== void 0 || options?.count !== void 0;
|
|
1844
|
+
const offset = options?.offset ?? 0;
|
|
1845
|
+
const count = options?.count ?? -1;
|
|
1626
1846
|
if (options?.withScores) {
|
|
1627
|
-
const members =
|
|
1628
|
-
|
|
1629
|
-
members.push({
|
|
1630
|
-
member: result[i],
|
|
1631
|
-
score: Number.parseFloat(result[i + 1])
|
|
1632
|
-
});
|
|
1633
|
-
}
|
|
1634
|
-
return members;
|
|
1847
|
+
const members = paginated ? await client.zrangebyscore(key, min, max, "WITHSCORES", "LIMIT", offset, count) : await client.zrangebyscore(key, min, max, "WITHSCORES");
|
|
1848
|
+
return deserializeScoredMembers(members);
|
|
1635
1849
|
}
|
|
1636
|
-
return
|
|
1850
|
+
return paginated ? client.zrangebyscore(key, min, max, "LIMIT", offset, count) : client.zrangebyscore(key, min, max);
|
|
1637
1851
|
});
|
|
1638
1852
|
},
|
|
1639
1853
|
async zcard(key) {
|
|
@@ -1645,7 +1859,7 @@ function createRedisProvider() {
|
|
|
1645
1859
|
async zincrBy(key, increment, member) {
|
|
1646
1860
|
return wrapOperation(async () => {
|
|
1647
1861
|
const result = await client.zincrby(key, increment, member);
|
|
1648
|
-
return
|
|
1862
|
+
return deserializeScore(result);
|
|
1649
1863
|
});
|
|
1650
1864
|
},
|
|
1651
1865
|
async zremRangeByRank(key, start, stop) {
|
|
@@ -1656,23 +1870,44 @@ function createRedisProvider() {
|
|
|
1656
1870
|
}
|
|
1657
1871
|
};
|
|
1658
1872
|
const LOCK_PREFIX = "__lock:";
|
|
1873
|
+
async function updateLock(key, owner, operation, ttl) {
|
|
1874
|
+
const result = await runLockMutation((connection) => connection.eval(
|
|
1875
|
+
UPDATE_LOCK_SCRIPT,
|
|
1876
|
+
1,
|
|
1877
|
+
`${LOCK_PREFIX}${key}`,
|
|
1878
|
+
owner,
|
|
1879
|
+
operation,
|
|
1880
|
+
...ttl === void 0 ? [] : [ttl]
|
|
1881
|
+
));
|
|
1882
|
+
return isRedisOne(result);
|
|
1883
|
+
}
|
|
1659
1884
|
const lock = {
|
|
1660
1885
|
async acquire(key, options) {
|
|
1886
|
+
const { ttl, owner } = options ?? {};
|
|
1887
|
+
if (owner !== void 0) {
|
|
1888
|
+
if (ttl !== void 0)
|
|
1889
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockOwnerOptions"));
|
|
1890
|
+
return wrapOperation(async () => {
|
|
1891
|
+
if (!isValidLockOwner(owner))
|
|
1892
|
+
return null;
|
|
1893
|
+
return await updateLock(key, owner, "reenter") ? owner : null;
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
const lockTtl = ttl === void 0 ? 30 : ttl;
|
|
1897
|
+
if (!isValidLockTtl(lockTtl))
|
|
1898
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockTtl"));
|
|
1661
1899
|
return wrapOperation(async () => {
|
|
1662
1900
|
const lockKey = `${LOCK_PREFIX}${key}`;
|
|
1663
|
-
const
|
|
1664
|
-
const
|
|
1665
|
-
|
|
1666
|
-
return result === "OK" ? owner : null;
|
|
1901
|
+
const token = core.id.uuid();
|
|
1902
|
+
const result = await runLockMutation((connection) => connection.set(lockKey, token, "EX", lockTtl, "NX"));
|
|
1903
|
+
return result === "OK" ? token : null;
|
|
1667
1904
|
});
|
|
1668
1905
|
},
|
|
1669
1906
|
async release(key, owner) {
|
|
1670
1907
|
return wrapOperation(async () => {
|
|
1671
|
-
|
|
1672
|
-
if (!owner)
|
|
1908
|
+
if (!isValidLockOwner(owner))
|
|
1673
1909
|
return false;
|
|
1674
|
-
|
|
1675
|
-
return isRedisOne(result);
|
|
1910
|
+
return updateLock(key, owner, "release");
|
|
1676
1911
|
});
|
|
1677
1912
|
},
|
|
1678
1913
|
async isLocked(key) {
|
|
@@ -1683,12 +1918,12 @@ function createRedisProvider() {
|
|
|
1683
1918
|
});
|
|
1684
1919
|
},
|
|
1685
1920
|
async extend(key, ttl, owner) {
|
|
1921
|
+
if (!isValidLockTtl(ttl))
|
|
1922
|
+
return err(HaiCacheError.OPERATION_FAILED, cacheM("cache_invalidLockTtl"));
|
|
1686
1923
|
return wrapOperation(async () => {
|
|
1687
|
-
|
|
1688
|
-
if (!owner)
|
|
1924
|
+
if (!isValidLockOwner(owner))
|
|
1689
1925
|
return false;
|
|
1690
|
-
|
|
1691
|
-
return isRedisOne(result);
|
|
1926
|
+
return updateLock(key, owner, "extend", ttl);
|
|
1692
1927
|
});
|
|
1693
1928
|
}
|
|
1694
1929
|
};
|
|
@@ -1833,18 +2068,16 @@ function createRedisProvider() {
|
|
|
1833
2068
|
|
|
1834
2069
|
// src/cache-main.ts
|
|
1835
2070
|
var logger2 = core.logger.child({ module: "cache", scope: "main" });
|
|
1836
|
-
var
|
|
1837
|
-
var currentConfig = null;
|
|
2071
|
+
var currentCache = null;
|
|
1838
2072
|
var initInProgress = false;
|
|
1839
2073
|
var pendingProvider = null;
|
|
1840
2074
|
var initCompletion = null;
|
|
1841
2075
|
var closingPromise = null;
|
|
1842
2076
|
async function closeOwnedProvider() {
|
|
1843
|
-
if (
|
|
1844
|
-
pendingProvider =
|
|
1845
|
-
|
|
2077
|
+
if (currentCache) {
|
|
2078
|
+
pendingProvider = currentCache.provider;
|
|
2079
|
+
currentCache = null;
|
|
1846
2080
|
}
|
|
1847
|
-
currentConfig = null;
|
|
1848
2081
|
if (!pendingProvider)
|
|
1849
2082
|
return ok(void 0);
|
|
1850
2083
|
try {
|
|
@@ -1908,6 +2141,21 @@ var notInitializedList = notInitialized.proxy();
|
|
|
1908
2141
|
var notInitializedSet = notInitialized.proxy();
|
|
1909
2142
|
var notInitializedZSet = notInitialized.proxy();
|
|
1910
2143
|
var notInitializedLock = notInitialized.proxy();
|
|
2144
|
+
function bindOperations(provider, operations) {
|
|
2145
|
+
return Object.fromEntries(Object.keys(operations).map((key) => {
|
|
2146
|
+
const operation = Reflect.get(operations, key);
|
|
2147
|
+
if (typeof operation !== "function")
|
|
2148
|
+
return [key, operation];
|
|
2149
|
+
return [
|
|
2150
|
+
key,
|
|
2151
|
+
(...args) => {
|
|
2152
|
+
if (currentCache?.provider !== provider)
|
|
2153
|
+
return Promise.resolve(notInitialized.result());
|
|
2154
|
+
return Reflect.apply(operation, operations, args);
|
|
2155
|
+
}
|
|
2156
|
+
];
|
|
2157
|
+
}));
|
|
2158
|
+
}
|
|
1911
2159
|
var cache = {
|
|
1912
2160
|
/**
|
|
1913
2161
|
* 初始化缓存连接。
|
|
@@ -1972,9 +2220,17 @@ var cache = {
|
|
|
1972
2220
|
logger2.error("Cache module initialization failed", { errorCode: connectResult.error.code });
|
|
1973
2221
|
return await failInitialization(connectResult);
|
|
1974
2222
|
}
|
|
2223
|
+
currentCache = {
|
|
2224
|
+
provider,
|
|
2225
|
+
config: parsed,
|
|
2226
|
+
kv: bindOperations(provider, provider.kv),
|
|
2227
|
+
hash: bindOperations(provider, provider.hash),
|
|
2228
|
+
list: bindOperations(provider, provider.list),
|
|
2229
|
+
set_: bindOperations(provider, provider.set_),
|
|
2230
|
+
zset: bindOperations(provider, provider.zset),
|
|
2231
|
+
lock: bindOperations(provider, provider.lock)
|
|
2232
|
+
};
|
|
1975
2233
|
pendingProvider = null;
|
|
1976
|
-
currentProvider = provider;
|
|
1977
|
-
currentConfig = parsed;
|
|
1978
2234
|
logger2.info("Cache module initialized", { type: parsed.type });
|
|
1979
2235
|
return ok(void 0);
|
|
1980
2236
|
} catch (error) {
|
|
@@ -1997,35 +2253,35 @@ var cache = {
|
|
|
1997
2253
|
},
|
|
1998
2254
|
/** KV 操作子接口;未 init 时所有方法返回 NOT_INITIALIZED */
|
|
1999
2255
|
get kv() {
|
|
2000
|
-
return
|
|
2256
|
+
return currentCache?.kv ?? notInitializedKv;
|
|
2001
2257
|
},
|
|
2002
2258
|
/** Hash 操作子接口 */
|
|
2003
2259
|
get hash() {
|
|
2004
|
-
return
|
|
2260
|
+
return currentCache?.hash ?? notInitializedHash;
|
|
2005
2261
|
},
|
|
2006
2262
|
/** List 操作子接口 */
|
|
2007
2263
|
get list() {
|
|
2008
|
-
return
|
|
2264
|
+
return currentCache?.list ?? notInitializedList;
|
|
2009
2265
|
},
|
|
2010
2266
|
/** Set 操作子接口(名称加 _ 以避免与 JS 关键字冲突) */
|
|
2011
2267
|
get set_() {
|
|
2012
|
-
return
|
|
2268
|
+
return currentCache?.set_ ?? notInitializedSet;
|
|
2013
2269
|
},
|
|
2014
2270
|
/** ZSet(有序集合)操作子接口 */
|
|
2015
2271
|
get zset() {
|
|
2016
|
-
return
|
|
2272
|
+
return currentCache?.zset ?? notInitializedZSet;
|
|
2017
2273
|
},
|
|
2018
2274
|
/** 分布式锁操作子接口 */
|
|
2019
2275
|
get lock() {
|
|
2020
|
-
return
|
|
2276
|
+
return currentCache?.lock ?? notInitializedLock;
|
|
2021
2277
|
},
|
|
2022
2278
|
/** 当前脱敏后的配置快照;未初始化时返回 null */
|
|
2023
2279
|
get config() {
|
|
2024
|
-
return
|
|
2280
|
+
return currentCache ? core.sanitize.sanitizeSensitiveFields(currentCache.config) : null;
|
|
2025
2281
|
},
|
|
2026
2282
|
/** 是否已初始化并连接;Provider 不存在或未连接时返回 false */
|
|
2027
2283
|
get isInitialized() {
|
|
2028
|
-
return
|
|
2284
|
+
return currentCache?.provider.isConnected() ?? false;
|
|
2029
2285
|
},
|
|
2030
2286
|
/**
|
|
2031
2287
|
* 测试缓存连接状态
|
|
@@ -2033,7 +2289,7 @@ var cache = {
|
|
|
2033
2289
|
* @returns 成功时返回 'PONG';未初始化时返回 NOT_INITIALIZED 错误
|
|
2034
2290
|
*/
|
|
2035
2291
|
ping() {
|
|
2036
|
-
return
|
|
2292
|
+
return currentCache?.provider.ping() ?? Promise.resolve(notInitialized.result());
|
|
2037
2293
|
},
|
|
2038
2294
|
/**
|
|
2039
2295
|
* 停止提供缓存操作并释放资源;等待正在进行的初始化,并合并并发关闭。
|