@jintianxiayu/cache-decorator 0.1.3 → 1.0.1
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/CHANGELOG.md +24 -0
- package/README.md +306 -79
- package/dist/adapters/ioredis-cache-client.d.ts +9 -0
- package/dist/adapters/ioredis-cache-client.d.ts.map +1 -0
- package/dist/adapters/ioredis-cache-client.js +73 -0
- package/dist/adapters/ioredis-cache-client.js.map +1 -0
- package/dist/adapters/node-redis-cache-client.d.ts +10 -0
- package/dist/adapters/node-redis-cache-client.d.ts.map +1 -0
- package/dist/adapters/node-redis-cache-client.js +81 -0
- package/dist/adapters/node-redis-cache-client.js.map +1 -0
- package/dist/adapters/redis-key-prefix.d.ts +22 -0
- package/dist/adapters/redis-key-prefix.d.ts.map +1 -0
- package/dist/adapters/redis-key-prefix.js +41 -0
- package/dist/adapters/redis-key-prefix.js.map +1 -0
- package/dist/core/cache-error.d.ts +75 -0
- package/dist/core/cache-error.d.ts.map +1 -0
- package/dist/core/cache-error.js +168 -0
- package/dist/core/cache-error.js.map +1 -0
- package/dist/core/cache-logger.d.ts +29 -0
- package/dist/core/cache-logger.d.ts.map +1 -0
- package/dist/core/cache-logger.js +72 -0
- package/dist/core/cache-logger.js.map +1 -0
- package/dist/core/cache-provider-registry.d.ts.map +1 -1
- package/dist/core/cache-provider-registry.js.map +1 -1
- package/dist/core/cache-provider.d.ts.map +1 -1
- package/dist/core/key-builder.d.ts.map +1 -1
- package/dist/core/key-builder.js +3 -2
- package/dist/core/key-builder.js.map +1 -1
- package/dist/core/native-cache.d.ts.map +1 -1
- package/dist/core/native-cache.js +2 -1
- package/dist/core/native-cache.js.map +1 -1
- package/dist/core/pending-cache.d.ts.map +1 -1
- package/dist/core/pending-cache.js +6 -3
- package/dist/core/pending-cache.js.map +1 -1
- package/dist/core/redis-cache-client.d.ts +156 -0
- package/dist/core/redis-cache-client.d.ts.map +1 -0
- package/dist/core/redis-cache-client.js +3 -0
- package/dist/core/redis-cache-client.js.map +1 -0
- package/dist/core/redis-cache.d.ts +39 -7
- package/dist/core/redis-cache.d.ts.map +1 -1
- package/dist/core/redis-cache.js +63 -22
- package/dist/core/redis-cache.js.map +1 -1
- package/dist/decorators/cache-evict.d.ts +1 -1
- package/dist/decorators/cache-evict.d.ts.map +1 -1
- package/dist/decorators/cache-evict.js +68 -14
- package/dist/decorators/cache-evict.js.map +1 -1
- package/dist/decorators/cache.d.ts +7 -1
- package/dist/decorators/cache.d.ts.map +1 -1
- package/dist/decorators/cache.js +169 -24
- package/dist/decorators/cache.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/jest.config.js +1 -1
- package/package.json +26 -29
- package/src/adapters/ioredis-cache-client.ts +89 -0
- package/src/adapters/node-redis-cache-client.ts +95 -0
- package/src/adapters/redis-key-prefix.ts +38 -0
- package/src/core/cache-error.ts +233 -0
- package/src/core/cache-logger.ts +116 -0
- package/src/core/key-builder.ts +3 -1
- package/src/core/native-cache.ts +3 -1
- package/src/core/pending-cache.ts +6 -3
- package/src/core/redis-cache-client.ts +160 -0
- package/src/core/redis-cache.ts +68 -20
- package/src/decorators/cache-evict.ts +76 -16
- package/src/decorators/cache.ts +220 -26
- package/src/index.ts +3 -0
- package/test/cache-evict-logging.test.ts +362 -0
- package/test/cache-logger.integration.test.ts +129 -0
- package/test/cache-logger.test.ts +156 -0
- package/test/cache-logging.test.ts +852 -0
- package/test/cache.test.ts +717 -34
- package/test/fixtures/cache-logger-child.mjs +108 -0
- package/test/helpers/legacy-redis-cache.ts +41 -0
- package/test/helpers/package-consumer.ts +231 -0
- package/test/helpers/redis-fixture.ts +142 -0
- package/test/ioredis-cache-client.test.ts +143 -0
- package/test/legacy-redis-cache.test.ts +51 -0
- package/test/native-cache.test.ts +9 -3
- package/test/node-redis-cache-client.test.ts +149 -0
- package/test/pending-cache.test.ts +11 -0
- package/test/redis-cache-client-lifecycle.test.ts +112 -0
- package/test/redis-cache-client-types.test.ts +184 -0
- package/test/redis-cache-client.integration.test.ts +355 -0
- package/test/redis-cache-decorator.test.ts +540 -0
- package/test/redis-cache-package.integration.test.ts +328 -0
- package/test/redis-cache-provider.test.ts +269 -0
- package/test/type-contract/contract.ts +119 -0
- package/test/type-contract/tsconfig.json +12 -0
- package/tsconfig.json +1 -1
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/** 异常缓存使用的固定 envelope 类型标识。 */
|
|
2
|
+
const CACHE_ERROR_KIND = '@jintianxiayu/cache-decorator/error';
|
|
3
|
+
|
|
4
|
+
/** 当前异常缓存 envelope 版本。 */
|
|
5
|
+
const CACHE_ERROR_VERSION = 1;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 异常缓存编解码器,将业务异常转换为可持久化 payload,并在命中时恢复异常语义。
|
|
9
|
+
*/
|
|
10
|
+
export interface CacheErrorCodec {
|
|
11
|
+
/**
|
|
12
|
+
* 编码本次业务异常。
|
|
13
|
+
* @param error 被装饰业务方法抛出或拒绝的值。
|
|
14
|
+
* @returns 可 JSON 往返的 payload。
|
|
15
|
+
*/
|
|
16
|
+
encode(error: unknown): unknown;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 解码缓存中的 payload。
|
|
20
|
+
* @param payload 当前版本 envelope 中的 JSON payload。
|
|
21
|
+
* @returns 命中时应向调用方抛出的值。
|
|
22
|
+
*/
|
|
23
|
+
decode(payload: unknown): unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 业务异常持久化策略;提供该对象即显式启用异常缓存。
|
|
28
|
+
*/
|
|
29
|
+
export interface CacheErrorPolicy {
|
|
30
|
+
/** 独立于正常结果 TTL 的正整数秒级异常 TTL。 */
|
|
31
|
+
ttl: number;
|
|
32
|
+
|
|
33
|
+
/** 返回 true 时允许缓存本次业务异常;省略时接受全部业务异常。 */
|
|
34
|
+
shouldCache?: (error: unknown) => boolean;
|
|
35
|
+
|
|
36
|
+
/** 成对提供的异常编解码器;省略时使用标准 Error/JSON 值 codec。 */
|
|
37
|
+
codec?: CacheErrorCodec;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 装饰器求值时完成校验并绑定默认 codec 的内部策略。 */
|
|
41
|
+
export interface NormalizedCacheErrorPolicy {
|
|
42
|
+
readonly ttl: number;
|
|
43
|
+
readonly shouldCache: ((error: unknown) => boolean) | undefined;
|
|
44
|
+
readonly codec: CacheErrorCodec;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Provider 中异常条目的版本化内容。 */
|
|
48
|
+
export interface VersionedCacheErrorPayload {
|
|
49
|
+
readonly kind: typeof CACHE_ERROR_KIND;
|
|
50
|
+
readonly version: typeof CACHE_ERROR_VERSION;
|
|
51
|
+
readonly payload: unknown;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface DefaultErrorPayload {
|
|
55
|
+
readonly type: 'error';
|
|
56
|
+
readonly name: string;
|
|
57
|
+
readonly message: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface DefaultValuePayload {
|
|
61
|
+
readonly type: 'value';
|
|
62
|
+
readonly value: unknown;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
|
|
66
|
+
return typeof value === 'object' && value !== null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isPlainObject(value: object): boolean {
|
|
70
|
+
const prototype = Object.getPrototypeOf(value) as unknown;
|
|
71
|
+
return prototype === Object.prototype || prototype === null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 递归校验值是否可以无损表示为 JSON,拒绝 JSON.stringify 会静默丢弃或改写的结构。
|
|
76
|
+
* @param value 待校验的 payload 或 envelope 节点。
|
|
77
|
+
* @param ancestors 当前递归路径上的对象,用于识别循环引用而不拒绝普通重复引用。
|
|
78
|
+
* @returns 无返回值。
|
|
79
|
+
* @throws 值包含非 JSON 类型、非有限数、稀疏数组、symbol key、特殊对象或循环引用时抛出 TypeError。
|
|
80
|
+
*/
|
|
81
|
+
function validateJsonValue(value: unknown, ancestors: Set<object>): void {
|
|
82
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (typeof value === 'number') {
|
|
86
|
+
if (!Number.isFinite(value)) {
|
|
87
|
+
throw new TypeError('Cache error payload numbers must be finite');
|
|
88
|
+
}
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (!isRecord(value)) {
|
|
92
|
+
throw new TypeError('Cache error payload must contain only JSON-compatible values');
|
|
93
|
+
}
|
|
94
|
+
if ((!Array.isArray(value) && !isPlainObject(value)) || Object.getOwnPropertySymbols(value).length > 0) {
|
|
95
|
+
throw new TypeError('Cache error payload must use JSON objects and arrays');
|
|
96
|
+
}
|
|
97
|
+
if (ancestors.has(value)) {
|
|
98
|
+
throw new TypeError('Cache error payload must not contain circular references');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
ancestors.add(value);
|
|
102
|
+
try {
|
|
103
|
+
if (Array.isArray(value)) {
|
|
104
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
105
|
+
if (!Object.prototype.hasOwnProperty.call(value, index)) {
|
|
106
|
+
throw new TypeError('Cache error payload arrays must not be sparse');
|
|
107
|
+
}
|
|
108
|
+
validateJsonValue(value[index], ancestors);
|
|
109
|
+
}
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
for (const child of Object.values(value)) {
|
|
113
|
+
validateJsonValue(child, ancestors);
|
|
114
|
+
}
|
|
115
|
+
} finally {
|
|
116
|
+
ancestors.delete(value);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 校验并执行一次 JSON stringify/parse,以统一 Memory、Redis 与自定义 Provider 得到的表示。
|
|
122
|
+
* @param value codec 产生的完整版本化 envelope。
|
|
123
|
+
* @returns JSON 往返后的独立规范化值。
|
|
124
|
+
* @throws 无法安全 JSON 往返时抛出 TypeError 或底层序列化错误。
|
|
125
|
+
*/
|
|
126
|
+
function normalizeJsonValue(value: unknown): unknown {
|
|
127
|
+
validateJsonValue(value, new Set<object>());
|
|
128
|
+
const serialized = JSON.stringify(value);
|
|
129
|
+
if (typeof serialized !== 'string') {
|
|
130
|
+
throw new TypeError('Cache error payload must serialize to JSON');
|
|
131
|
+
}
|
|
132
|
+
return JSON.parse(serialized) as unknown;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const defaultCacheErrorCodec: CacheErrorCodec = Object.freeze({
|
|
136
|
+
encode(error: unknown): DefaultErrorPayload | DefaultValuePayload {
|
|
137
|
+
if (error instanceof Error) {
|
|
138
|
+
return { type: 'error', name: error.name, message: error.message };
|
|
139
|
+
}
|
|
140
|
+
return { type: 'value', value: error };
|
|
141
|
+
},
|
|
142
|
+
decode(payload: unknown): unknown {
|
|
143
|
+
if (!isRecord(payload)) {
|
|
144
|
+
throw new TypeError('Default cache error payload must be an object');
|
|
145
|
+
}
|
|
146
|
+
if (payload.type === 'error' && typeof payload.name === 'string' && typeof payload.message === 'string') {
|
|
147
|
+
const error = new Error(payload.message);
|
|
148
|
+
error.name = payload.name;
|
|
149
|
+
return error;
|
|
150
|
+
}
|
|
151
|
+
if (payload.type === 'value' && Object.prototype.hasOwnProperty.call(payload, 'value')) {
|
|
152
|
+
return payload.value;
|
|
153
|
+
}
|
|
154
|
+
throw new TypeError('Default cache error payload has an unsupported shape');
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 在 legacy decorator 求值阶段校验外部异常策略并绑定默认 codec。
|
|
160
|
+
* @param policy 调用方传入的可选异常策略。
|
|
161
|
+
* @returns 禁用状态返回 undefined;启用状态返回不可变的内部策略快照。
|
|
162
|
+
* @throws TTL 非正有限整数时抛 RangeError;筛选器或 codec 结构非法时抛 TypeError。
|
|
163
|
+
*/
|
|
164
|
+
export function normalizeCacheErrorPolicy(
|
|
165
|
+
policy: CacheErrorPolicy | undefined
|
|
166
|
+
): NormalizedCacheErrorPolicy | undefined {
|
|
167
|
+
if (policy === undefined) {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
if (!isRecord(policy)) {
|
|
171
|
+
throw new TypeError('Cache error policy must be an object');
|
|
172
|
+
}
|
|
173
|
+
const ttl = policy.ttl;
|
|
174
|
+
const shouldCache = policy.shouldCache;
|
|
175
|
+
const configuredCodec = policy.codec;
|
|
176
|
+
if (typeof ttl !== 'number' || !Number.isFinite(ttl) || !Number.isInteger(ttl) || ttl < 1) {
|
|
177
|
+
throw new RangeError('Cache error TTL must be a positive finite integer');
|
|
178
|
+
}
|
|
179
|
+
if (shouldCache !== undefined && typeof shouldCache !== 'function') {
|
|
180
|
+
throw new TypeError('Cache error shouldCache must be a function');
|
|
181
|
+
}
|
|
182
|
+
const codec = configuredCodec === undefined ? defaultCacheErrorCodec : configuredCodec;
|
|
183
|
+
if (!isRecord(codec) || typeof codec.encode !== 'function' || typeof codec.decode !== 'function') {
|
|
184
|
+
throw new TypeError('Cache error codec must provide encode and decode functions');
|
|
185
|
+
}
|
|
186
|
+
return Object.freeze({ ttl, shouldCache, codec });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 将业务异常编码为当前版本且已经 JSON 规范化的 envelope。
|
|
191
|
+
* @param error 本次业务方法产生的原始异常。
|
|
192
|
+
* @param policy 已在 decorator 求值阶段归一化的策略。
|
|
193
|
+
* @returns 可直接交给任意 CacheProvider 的版本化异常内容。
|
|
194
|
+
* @throws codec 或 JSON 往返失败时传播错误。
|
|
195
|
+
*/
|
|
196
|
+
export function encodeCacheError(error: unknown, policy: NormalizedCacheErrorPolicy): VersionedCacheErrorPayload {
|
|
197
|
+
const envelope = {
|
|
198
|
+
kind: CACHE_ERROR_KIND,
|
|
199
|
+
version: CACHE_ERROR_VERSION,
|
|
200
|
+
payload: policy.codec.encode(error),
|
|
201
|
+
};
|
|
202
|
+
return normalizeJsonValue(envelope) as VersionedCacheErrorPayload;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 判断 Provider 返回的 error 字段是否为当前版本 envelope。
|
|
207
|
+
* @param value Provider 返回的 error 字段。
|
|
208
|
+
* @returns kind、version 与 payload 完整匹配当前协议时返回 true。
|
|
209
|
+
*/
|
|
210
|
+
export function isCurrentCacheErrorPayload(value: unknown): value is VersionedCacheErrorPayload {
|
|
211
|
+
return (
|
|
212
|
+
isRecord(value) &&
|
|
213
|
+
value.kind === CACHE_ERROR_KIND &&
|
|
214
|
+
value.version === CACHE_ERROR_VERSION &&
|
|
215
|
+
Object.prototype.hasOwnProperty.call(value, 'payload')
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 使用当前策略解码异常,并拒绝异步或不能安全表示的非 Error 结果。
|
|
221
|
+
* @param envelope 已识别为当前版本的异常内容。
|
|
222
|
+
* @param policy 当前装饰器启用的异常策略。
|
|
223
|
+
* @returns codec 产生的同一个异常结果。
|
|
224
|
+
* @throws codec 抛错或返回不受支持的结果时抛出。
|
|
225
|
+
*/
|
|
226
|
+
export function decodeCacheError(envelope: VersionedCacheErrorPayload, policy: NormalizedCacheErrorPolicy): unknown {
|
|
227
|
+
const decoded = policy.codec.decode(envelope.payload);
|
|
228
|
+
if (decoded instanceof Error) {
|
|
229
|
+
return decoded;
|
|
230
|
+
}
|
|
231
|
+
validateJsonValue(decoded, new Set<object>());
|
|
232
|
+
return decoded;
|
|
233
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { LoggerFactory, type LoggerInterface } from '@jintianxiayu/logger';
|
|
2
|
+
|
|
3
|
+
const CACHE_LOGGER_NAME = '@jintianxiayu/cache-decorator';
|
|
4
|
+
|
|
5
|
+
export type CacheLogEvent =
|
|
6
|
+
| 'cache.pending_hit'
|
|
7
|
+
| 'cache.hit'
|
|
8
|
+
| 'cache.miss'
|
|
9
|
+
| 'cache.write_dispatched'
|
|
10
|
+
| 'cache.error_cache_skipped'
|
|
11
|
+
| 'cache.error_cache_failed'
|
|
12
|
+
| 'cache.evict_dispatched'
|
|
13
|
+
| 'cache.evict_completed'
|
|
14
|
+
| 'cache.key_fallback'
|
|
15
|
+
| 'cache.evict_skipped'
|
|
16
|
+
| 'cache.operation_failed';
|
|
17
|
+
|
|
18
|
+
type CacheLogLevel = 'debug' | 'warn' | 'error';
|
|
19
|
+
|
|
20
|
+
interface CacheLogDefinition {
|
|
21
|
+
readonly level: CacheLogLevel;
|
|
22
|
+
readonly message: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 缓存日志只接受与决策相关的稳定字段,避免业务数据和 cache key 被意外带入输出。 */
|
|
26
|
+
export interface CacheLogContext {
|
|
27
|
+
readonly cacheName: string;
|
|
28
|
+
readonly methodName: string;
|
|
29
|
+
readonly providerName: string;
|
|
30
|
+
readonly entryType?: 'value' | 'error';
|
|
31
|
+
readonly scope?: 'key' | 'allEntries';
|
|
32
|
+
readonly reason?:
|
|
33
|
+
| 'resolver_error'
|
|
34
|
+
| 'business_error'
|
|
35
|
+
| 'disabled'
|
|
36
|
+
| 'predicate_rejected'
|
|
37
|
+
| 'legacy_entry'
|
|
38
|
+
| 'disabled_entry';
|
|
39
|
+
readonly phase?: 'predicate' | 'encode' | 'decode';
|
|
40
|
+
readonly operation?: 'provider_resolution' | 'read' | 'write' | 'evict';
|
|
41
|
+
readonly error?: unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 日志定义映射中 K 为稳定事件名,V 为固定的日志级别与无业务数据消息。 */
|
|
45
|
+
const CACHE_LOG_DEFINITIONS: Readonly<Record<CacheLogEvent, CacheLogDefinition>> = {
|
|
46
|
+
'cache.pending_hit': { level: 'debug', message: 'Cache pending request reused' },
|
|
47
|
+
'cache.hit': { level: 'debug', message: 'Cache entry hit' },
|
|
48
|
+
'cache.miss': { level: 'debug', message: 'Cache entry missed' },
|
|
49
|
+
'cache.write_dispatched': { level: 'debug', message: 'Cache write dispatched' },
|
|
50
|
+
'cache.error_cache_skipped': { level: 'debug', message: 'Cache error entry skipped' },
|
|
51
|
+
'cache.error_cache_failed': { level: 'warn', message: 'Cache error policy failed' },
|
|
52
|
+
'cache.evict_dispatched': { level: 'debug', message: 'Cache eviction dispatched' },
|
|
53
|
+
'cache.evict_completed': { level: 'debug', message: 'Cache eviction completed' },
|
|
54
|
+
'cache.key_fallback': { level: 'warn', message: 'Cache key resolver failed; using default key' },
|
|
55
|
+
'cache.evict_skipped': { level: 'warn', message: 'Cache eviction skipped after business failure' },
|
|
56
|
+
'cache.operation_failed': { level: 'error', message: 'Cache operation failed' },
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
let cacheLogger: LoggerInterface | undefined;
|
|
60
|
+
|
|
61
|
+
function getCacheLogger(): LoggerInterface {
|
|
62
|
+
cacheLogger ??= LoggerFactory.getLogger(CACHE_LOGGER_NAME);
|
|
63
|
+
return cacheLogger;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 按稳定事件定义调用对应 Logger level,不提供 info 分支以防高频缓存事件误入 info。
|
|
68
|
+
* @param logger 应用共享的 cache 命名 Logger。
|
|
69
|
+
* @param definition 当前事件固定的 level 与 message。
|
|
70
|
+
* @param metadata 只包含缓存决策白名单字段的结构化元数据。
|
|
71
|
+
* @returns 无返回值。
|
|
72
|
+
* @throws Logger 同步写入失败时透传给外层安全边界处理。
|
|
73
|
+
*/
|
|
74
|
+
function writeCacheLog(
|
|
75
|
+
logger: LoggerInterface,
|
|
76
|
+
definition: CacheLogDefinition,
|
|
77
|
+
metadata: CacheLogContext & { readonly event: CacheLogEvent }
|
|
78
|
+
): void {
|
|
79
|
+
if (definition.level === 'debug') {
|
|
80
|
+
logger.debug(definition.message, metadata);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (definition.level === 'warn') {
|
|
84
|
+
logger.warn(definition.message, metadata);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
logger.error(definition.message, metadata);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 提交一条不会影响缓存或业务结果的结构化日志。
|
|
92
|
+
* @param event 决定固定 message 与 level 的缓存事件。
|
|
93
|
+
* @param context 不包含参数、值或 key 的缓存决策上下文。
|
|
94
|
+
* @returns 无返回值;Logger 获取或同步写入失败时静默结束。
|
|
95
|
+
* @throws 不主动抛出异常。
|
|
96
|
+
*/
|
|
97
|
+
export function logCacheEvent(event: CacheLogEvent, context: CacheLogContext): void {
|
|
98
|
+
try {
|
|
99
|
+
writeCacheLog(getCacheLogger(), CACHE_LOG_DEFINITIONS[event], { event, ...context });
|
|
100
|
+
} catch (_error) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 将 decorator 配置中的 Provider 名称转换为稳定日志标签。
|
|
107
|
+
* @param providerName 用户显式配置的 Provider 名称。
|
|
108
|
+
* @returns 非空显式名称;缺省或空字符串返回 `default`。
|
|
109
|
+
* @throws 不主动抛出异常。
|
|
110
|
+
*/
|
|
111
|
+
export function cacheProviderLabel(providerName: string | undefined): string {
|
|
112
|
+
if (providerName === undefined || providerName.length === 0) {
|
|
113
|
+
return 'default';
|
|
114
|
+
}
|
|
115
|
+
return providerName;
|
|
116
|
+
}
|
package/src/core/key-builder.ts
CHANGED
|
@@ -15,7 +15,9 @@ export class KeyBuilder {
|
|
|
15
15
|
}
|
|
16
16
|
const serializedArgs = args
|
|
17
17
|
.map((arg) => {
|
|
18
|
-
if (arg === null || arg === undefined)
|
|
18
|
+
if (arg === null || arg === undefined) {
|
|
19
|
+
return 'null';
|
|
20
|
+
}
|
|
19
21
|
if (typeof arg === 'object') {
|
|
20
22
|
try {
|
|
21
23
|
return JSON.stringify(arg);
|
package/src/core/native-cache.ts
CHANGED
|
@@ -17,7 +17,9 @@ export class MemoryCacheProvider implements CacheProvider {
|
|
|
17
17
|
|
|
18
18
|
get<T>(key: string): T | undefined {
|
|
19
19
|
const entry = this.cache.get(key);
|
|
20
|
-
if (!entry)
|
|
20
|
+
if (!entry) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
21
23
|
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
22
24
|
this.cache.delete(key);
|
|
23
25
|
return undefined;
|
|
@@ -11,9 +11,12 @@ export class PendingCache {
|
|
|
11
11
|
|
|
12
12
|
set<T>(key: string, promise: Promise<T>): void {
|
|
13
13
|
this.pending.set(key, promise);
|
|
14
|
-
|
|
15
|
-
this.pending.
|
|
16
|
-
|
|
14
|
+
const deleteSettledPromise = (): void => {
|
|
15
|
+
if (this.pending.get(key) === promise) {
|
|
16
|
+
this.pending.delete(key);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
void promise.then(deleteSettledPromise, deleteSettledPromise);
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
delete(key: string): void {
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/** Redis 缓存使用的最小字符串命令边界,连接及其生命周期由调用方持有。 */
|
|
2
|
+
export interface RedisCacheClient {
|
|
3
|
+
/**
|
|
4
|
+
* 读取逻辑缓存键对应的字符串值。
|
|
5
|
+
* @param key 未经 Provider 改写的逻辑缓存键。
|
|
6
|
+
* @returns 缓存字符串;键不存在时返回 null。
|
|
7
|
+
* @throws 客户端命令失败时传播原始错误。
|
|
8
|
+
*/
|
|
9
|
+
get(key: string): Promise<string | null>;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 写入已经由 Provider 序列化的缓存字符串。
|
|
13
|
+
* @param request 逻辑缓存键、字符串值及可选的秒级 TTL。
|
|
14
|
+
* @returns 命令成功后完成。
|
|
15
|
+
* @throws 客户端命令失败时传播原始错误。
|
|
16
|
+
*/
|
|
17
|
+
set(request: { readonly key: string; readonly value: string; readonly ttlSeconds?: number }): Promise<void>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 批量删除逻辑缓存键;空数组不得发送无参数 DEL。
|
|
21
|
+
* @param keys 保持调用顺序的逻辑缓存键集合。
|
|
22
|
+
* @returns 删除命令成功后完成。
|
|
23
|
+
* @throws 客户端命令失败时传播原始错误。
|
|
24
|
+
*/
|
|
25
|
+
deleteMany(keys: readonly string[]): Promise<void>;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 按逻辑 glob pattern 扫描一页缓存键。
|
|
29
|
+
* @param request 当前游标、逻辑 pattern 和本页数量提示。
|
|
30
|
+
* @returns 下一游标及已经恢复为逻辑形式的缓存键。
|
|
31
|
+
* @throws 客户端命令失败或响应不受支持时传播错误。
|
|
32
|
+
*/
|
|
33
|
+
scan(request: { readonly cursor: string; readonly pattern: string; readonly count: number }): Promise<{
|
|
34
|
+
readonly cursor: string;
|
|
35
|
+
readonly keys: readonly string[];
|
|
36
|
+
}>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 清空客户端当前选择的整个 Redis 数据库。
|
|
40
|
+
* @returns 清库命令成功后完成。
|
|
41
|
+
* @throws 客户端命令失败时传播原始错误。
|
|
42
|
+
*/
|
|
43
|
+
flushDatabase(): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ioredis 适配器实际使用的命令形状,避免公共声明依赖完整客户端类型。 */
|
|
47
|
+
export interface IoredisCacheClientSource {
|
|
48
|
+
/** 调用方连接的现有选项;适配器只读取 keyPrefix。 */
|
|
49
|
+
readonly options: { readonly keyPrefix?: string };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 读取由 ioredis 自行应用 keyPrefix 的逻辑键。
|
|
53
|
+
* @param key 逻辑缓存键。
|
|
54
|
+
* @returns ioredis 原始 GET 响应。
|
|
55
|
+
* @throws 客户端命令错误。
|
|
56
|
+
*/
|
|
57
|
+
get(key: string): Promise<unknown>;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 不带过期时间写入由 ioredis 自行应用 keyPrefix 的逻辑键。
|
|
61
|
+
* @param key 逻辑缓存键。
|
|
62
|
+
* @param value 已序列化的缓存字符串。
|
|
63
|
+
* @returns ioredis 原始 SET 响应。
|
|
64
|
+
* @throws 客户端命令错误。
|
|
65
|
+
*/
|
|
66
|
+
set(key: string, value: string): Promise<unknown>;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 使用秒级 TTL 写入由 ioredis 自行应用 keyPrefix 的逻辑键。
|
|
70
|
+
* @param key 逻辑缓存键。
|
|
71
|
+
* @param ttlSeconds 正整数秒级 TTL。
|
|
72
|
+
* @param value 已序列化的缓存字符串。
|
|
73
|
+
* @returns ioredis 原始 SETEX 响应。
|
|
74
|
+
* @throws 客户端命令错误。
|
|
75
|
+
*/
|
|
76
|
+
setex(key: string, ttlSeconds: number, value: string): Promise<unknown>;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 删除由 ioredis 自行应用 keyPrefix 的逻辑键。
|
|
80
|
+
* @param keys 保持调用顺序的逻辑缓存键。
|
|
81
|
+
* @returns ioredis 原始 DEL 响应。
|
|
82
|
+
* @throws 客户端命令错误。
|
|
83
|
+
*/
|
|
84
|
+
del(...keys: string[]): Promise<unknown>;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 使用 ioredis 的五段 SCAN 参数形状扫描物理键。
|
|
88
|
+
* @param args 游标、MATCH、物理 pattern、COUNT 和数量提示。
|
|
89
|
+
* @returns ioredis 原始 tuple SCAN 响应。
|
|
90
|
+
* @throws 客户端命令错误。
|
|
91
|
+
*/
|
|
92
|
+
scan(...args: [cursor: string, match: 'MATCH', pattern: string, count: 'COUNT', limit: number]): Promise<unknown>;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 清空连接当前选择的 Redis 数据库。
|
|
96
|
+
* @returns ioredis 原始 FLUSHDB 响应。
|
|
97
|
+
* @throws 客户端命令错误。
|
|
98
|
+
*/
|
|
99
|
+
flushdb(): Promise<unknown>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** node-redis 适配器实际使用的命令形状,避免公共声明依赖完整客户端类型。 */
|
|
103
|
+
export interface NodeRedisCacheClientSource {
|
|
104
|
+
/**
|
|
105
|
+
* 读取已经应用适配器前缀的物理键。
|
|
106
|
+
* @param key 物理缓存键。
|
|
107
|
+
* @returns node-redis 原始 GET 响应。
|
|
108
|
+
* @throws 客户端命令错误。
|
|
109
|
+
*/
|
|
110
|
+
get(key: string): Promise<unknown>;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 不带过期时间写入已经应用适配器前缀的物理键。
|
|
114
|
+
* @param key 物理缓存键。
|
|
115
|
+
* @param value 已序列化的缓存字符串。
|
|
116
|
+
* @returns node-redis 原始 SET 响应。
|
|
117
|
+
* @throws 客户端命令错误。
|
|
118
|
+
*/
|
|
119
|
+
set(key: string, value: string): Promise<unknown>;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 使用秒级 TTL 写入已经应用适配器前缀的物理键。
|
|
123
|
+
* @param key 物理缓存键。
|
|
124
|
+
* @param ttlSeconds 正整数秒级 TTL。
|
|
125
|
+
* @param value 已序列化的缓存字符串。
|
|
126
|
+
* @returns node-redis 原始 SETEX 响应。
|
|
127
|
+
* @throws 客户端命令错误。
|
|
128
|
+
*/
|
|
129
|
+
setEx(key: string, ttlSeconds: number, value: string): Promise<unknown>;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 删除一个或多个已经应用适配器前缀的物理键。
|
|
133
|
+
* @param keys 单个物理键或保持调用顺序的物理键数组。
|
|
134
|
+
* @returns node-redis 原始 DEL 响应。
|
|
135
|
+
* @throws 客户端命令错误。
|
|
136
|
+
*/
|
|
137
|
+
del(keys: string | string[]): Promise<unknown>;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 使用 node-redis 的对象选项扫描物理键。
|
|
141
|
+
* @param cursor 当前 Redis 游标。
|
|
142
|
+
* @param options 物理 MATCH pattern 和本页数量提示。
|
|
143
|
+
* @returns node-redis 原始对象 SCAN 响应。
|
|
144
|
+
* @throws 客户端命令错误。
|
|
145
|
+
*/
|
|
146
|
+
scan(cursor: string, options: { MATCH: string; COUNT: number }): Promise<unknown>;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 清空连接当前选择的 Redis 数据库。
|
|
150
|
+
* @returns node-redis 原始 FLUSHDB 响应。
|
|
151
|
+
* @throws 客户端命令错误。
|
|
152
|
+
*/
|
|
153
|
+
flushDb(): Promise<unknown>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** node-redis 没有透明 keyPrefix,通过适配器显式保持逻辑命名空间。 */
|
|
157
|
+
export interface NodeRedisCacheClientOptions {
|
|
158
|
+
/** 拼接到每个逻辑 key 前的字面字符串,缺省为空字符串。 */
|
|
159
|
+
readonly keyPrefix?: string;
|
|
160
|
+
}
|
package/src/core/redis-cache.ts
CHANGED
|
@@ -1,56 +1,104 @@
|
|
|
1
1
|
import { CacheProvider } from './cache-provider';
|
|
2
|
-
import
|
|
2
|
+
import { RedisCacheClient } from './redis-cache-client';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Redis
|
|
6
|
-
*
|
|
5
|
+
* Redis 缓存提供者,在客户端无关的字符串命令之上维护统一缓存协议。
|
|
6
|
+
* 适用于分布式场景,支持跨进程及跨客户端共享缓存。
|
|
7
7
|
*/
|
|
8
8
|
export class RedisCacheProvider implements CacheProvider {
|
|
9
|
-
private
|
|
9
|
+
private readonly client: RedisCacheClient;
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* 创建复用调用方 Redis 连接的缓存提供者。
|
|
13
|
+
* @param client 已适配的最小 Redis 缓存客户端。
|
|
14
|
+
*/
|
|
15
|
+
constructor(client: RedisCacheClient) {
|
|
16
|
+
this.client = client;
|
|
13
17
|
}
|
|
14
18
|
|
|
19
|
+
/**
|
|
20
|
+
* 按既有协议读取并反序列化缓存值。
|
|
21
|
+
* @param key 未经 Provider 改写的逻辑缓存键。
|
|
22
|
+
* @returns 解析后的业务值;Redis miss 时返回 undefined。
|
|
23
|
+
* @throws GET 命令失败时传播客户端原始错误。
|
|
24
|
+
*/
|
|
15
25
|
async get<T>(key: string): Promise<T | undefined> {
|
|
16
|
-
const value = await this.
|
|
17
|
-
if (value === null)
|
|
26
|
+
const value = await this.client.get(key);
|
|
27
|
+
if (value === null) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
18
30
|
try {
|
|
19
31
|
return JSON.parse(value) as T;
|
|
20
32
|
} catch {
|
|
33
|
+
// 兼容既有协议:不是合法 JSON 的字符串按原值返回。
|
|
21
34
|
return value as unknown as T;
|
|
22
35
|
}
|
|
23
36
|
}
|
|
24
37
|
|
|
38
|
+
/**
|
|
39
|
+
* 按既有字符串或 JSON 协议写入缓存值。
|
|
40
|
+
* @param key 未经 Provider 改写的逻辑缓存键。
|
|
41
|
+
* @param value 需要缓存的业务值。
|
|
42
|
+
* @param ttl 可选的正整数秒级 TTL;undefined 或 0 表示永不过期。
|
|
43
|
+
* @returns 写入命令成功后完成。
|
|
44
|
+
* @throws 值不能序列化时抛 TypeError,TTL 非法时抛 RangeError,命令失败时传播原始错误。
|
|
45
|
+
*/
|
|
25
46
|
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
|
|
47
|
+
const ttlSeconds = this.normalizeTtl(ttl);
|
|
26
48
|
const serialized = typeof value === 'string' ? value : JSON.stringify(value);
|
|
27
|
-
if (
|
|
28
|
-
|
|
29
|
-
}
|
|
30
|
-
|
|
49
|
+
if (typeof serialized !== 'string') {
|
|
50
|
+
throw new TypeError('Cache value must serialize to a string');
|
|
51
|
+
}
|
|
52
|
+
if (ttlSeconds === undefined) {
|
|
53
|
+
await this.client.set({ key, value: serialized });
|
|
54
|
+
return;
|
|
31
55
|
}
|
|
56
|
+
await this.client.set({ key, value: serialized, ttlSeconds });
|
|
32
57
|
}
|
|
33
58
|
|
|
59
|
+
/**
|
|
60
|
+
* 幂等删除一个逻辑缓存键。
|
|
61
|
+
* @param key 未经 Provider 改写的逻辑缓存键。
|
|
62
|
+
* @returns 删除命令成功后完成。
|
|
63
|
+
* @throws DEL 命令失败时传播客户端原始错误。
|
|
64
|
+
*/
|
|
34
65
|
async delete(key: string): Promise<void> {
|
|
35
|
-
await this.
|
|
66
|
+
await this.client.deleteMany([key]);
|
|
36
67
|
}
|
|
37
68
|
|
|
69
|
+
/**
|
|
70
|
+
* 清空客户端当前选择的整个 Redis 数据库。
|
|
71
|
+
* @returns FLUSHDB 命令成功后完成。
|
|
72
|
+
* @throws 清库命令失败时传播客户端原始错误。
|
|
73
|
+
*/
|
|
38
74
|
async clear(): Promise<void> {
|
|
39
|
-
await this.
|
|
75
|
+
await this.client.flushDatabase();
|
|
40
76
|
}
|
|
41
77
|
|
|
42
78
|
/**
|
|
43
|
-
*
|
|
44
|
-
* @param pattern glob
|
|
79
|
+
* 使用游标扫描并按页删除匹配的逻辑缓存键,避免阻塞 Redis。
|
|
80
|
+
* @param pattern 保留 glob 语义的逻辑 pattern,例如 user:*。
|
|
81
|
+
* @returns 游标归零且所有已扫描页面删除成功后完成。
|
|
82
|
+
* @throws SCAN 或任一页 DEL 失败时传播客户端原始错误,并停止后续页面。
|
|
45
83
|
*/
|
|
46
84
|
async deleteByPattern(pattern: string): Promise<void> {
|
|
47
85
|
let cursor = '0';
|
|
48
86
|
do {
|
|
49
|
-
const
|
|
50
|
-
cursor =
|
|
51
|
-
if (keys.length > 0) {
|
|
52
|
-
await this.
|
|
87
|
+
const page = await this.client.scan({ cursor, pattern, count: 100 });
|
|
88
|
+
cursor = page.cursor;
|
|
89
|
+
if (page.keys.length > 0) {
|
|
90
|
+
await this.client.deleteMany(page.keys);
|
|
53
91
|
}
|
|
54
92
|
} while (cursor !== '0');
|
|
55
93
|
}
|
|
94
|
+
|
|
95
|
+
private normalizeTtl(ttl: number | undefined): number | undefined {
|
|
96
|
+
if (ttl === undefined || ttl === 0) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
if (!Number.isFinite(ttl) || !Number.isInteger(ttl) || ttl < 1) {
|
|
100
|
+
throw new RangeError('Redis cache TTL must be a positive finite integer or zero');
|
|
101
|
+
}
|
|
102
|
+
return ttl;
|
|
103
|
+
}
|
|
56
104
|
}
|