@jintianxiayu/cache-decorator 1.0.0 → 1.0.2
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 +25 -11
- package/README.md +364 -270
- 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 +3 -2
- package/dist/core/cache-logger.d.ts.map +1 -1
- package/dist/core/cache-logger.js +2 -0
- package/dist/core/cache-logger.js.map +1 -1
- package/dist/decorators/cache-evict.d.ts.map +1 -1
- package/dist/decorators/cache-evict.js +15 -10
- package/dist/decorators/cache-evict.js.map +1 -1
- package/dist/decorators/cache.d.ts +6 -0
- package/dist/decorators/cache.d.ts.map +1 -1
- package/dist/decorators/cache.js +113 -36
- package/dist/decorators/cache.js.map +1 -1
- package/jest.config.js +11 -11
- package/package.json +1 -1
- package/src/adapters/ioredis-cache-client.ts +89 -89
- package/src/adapters/node-redis-cache-client.ts +95 -95
- package/src/adapters/redis-key-prefix.ts +38 -38
- package/src/core/cache-error.ts +233 -0
- package/src/core/cache-logger.ts +116 -105
- package/src/core/key-builder.ts +33 -33
- package/src/core/native-cache.ts +55 -55
- package/src/core/pending-cache.ts +29 -29
- package/src/core/redis-cache-client.ts +160 -160
- package/src/core/redis-cache.ts +104 -104
- package/src/decorators/cache-evict.ts +137 -129
- package/src/decorators/cache.ts +323 -203
- package/src/index.ts +11 -11
- package/test/cache-evict-logging.test.ts +398 -362
- package/test/cache-logger.integration.test.ts +159 -129
- package/test/cache-logger.test.ts +156 -153
- package/test/cache-logging.test.ts +929 -544
- package/test/cache.test.ts +1017 -255
- package/test/fixtures/cache-logger-child.mjs +108 -108
- package/test/fixtures/cache-provider-failure-child.mjs +70 -0
- package/test/helpers/legacy-redis-cache.ts +41 -22
- package/test/helpers/package-consumer.ts +231 -231
- package/test/helpers/redis-fixture.ts +142 -142
- package/test/ioredis-cache-client.test.ts +143 -143
- package/test/legacy-redis-cache.test.ts +51 -0
- package/test/native-cache.test.ts +77 -77
- package/test/node-redis-cache-client.test.ts +149 -149
- package/test/pending-cache.test.ts +69 -69
- package/test/redis-cache-client-lifecycle.test.ts +112 -112
- package/test/redis-cache-client-types.test.ts +184 -184
- package/test/redis-cache-client.integration.test.ts +355 -327
- package/test/redis-cache-decorator.test.ts +601 -201
- package/test/redis-cache-provider.test.ts +269 -269
- package/test/type-contract/contract.ts +119 -64
- package/test/type-contract/tsconfig.json +12 -12
- package/tsconfig.json +8 -8
|
@@ -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
|
+
}
|
package/src/core/cache-logger.ts
CHANGED
|
@@ -1,105 +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.
|
|
11
|
-
| 'cache.
|
|
12
|
-
| 'cache.
|
|
13
|
-
| 'cache.
|
|
14
|
-
| 'cache.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
readonly
|
|
28
|
-
readonly
|
|
29
|
-
readonly
|
|
30
|
-
readonly
|
|
31
|
-
readonly
|
|
32
|
-
readonly
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
'
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
*
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 缓存 Key 构建器
|
|
3
|
-
* 负责将缓存名称和参数转换为统一的 key 字符串
|
|
4
|
-
*/
|
|
5
|
-
export class KeyBuilder {
|
|
6
|
-
/**
|
|
7
|
-
* 构建缓存 key
|
|
8
|
-
* @param cacheName 缓存名称
|
|
9
|
-
* @param args 方法参数列表
|
|
10
|
-
* @returns 格式为 {cacheName}:{serializedArgs} 的 key 字符串
|
|
11
|
-
*/
|
|
12
|
-
static build(cacheName: string, args: unknown[]): string {
|
|
13
|
-
if (args.length === 0) {
|
|
14
|
-
return cacheName;
|
|
15
|
-
}
|
|
16
|
-
const serializedArgs = args
|
|
17
|
-
.map((arg) => {
|
|
18
|
-
if (arg === null || arg === undefined) {
|
|
19
|
-
return 'null';
|
|
20
|
-
}
|
|
21
|
-
if (typeof arg === 'object') {
|
|
22
|
-
try {
|
|
23
|
-
return JSON.stringify(arg);
|
|
24
|
-
} catch {
|
|
25
|
-
return String(arg);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
return String(arg);
|
|
29
|
-
})
|
|
30
|
-
.join('&');
|
|
31
|
-
return `${cacheName}:${serializedArgs}`;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 缓存 Key 构建器
|
|
3
|
+
* 负责将缓存名称和参数转换为统一的 key 字符串
|
|
4
|
+
*/
|
|
5
|
+
export class KeyBuilder {
|
|
6
|
+
/**
|
|
7
|
+
* 构建缓存 key
|
|
8
|
+
* @param cacheName 缓存名称
|
|
9
|
+
* @param args 方法参数列表
|
|
10
|
+
* @returns 格式为 {cacheName}:{serializedArgs} 的 key 字符串
|
|
11
|
+
*/
|
|
12
|
+
static build(cacheName: string, args: unknown[]): string {
|
|
13
|
+
if (args.length === 0) {
|
|
14
|
+
return cacheName;
|
|
15
|
+
}
|
|
16
|
+
const serializedArgs = args
|
|
17
|
+
.map((arg) => {
|
|
18
|
+
if (arg === null || arg === undefined) {
|
|
19
|
+
return 'null';
|
|
20
|
+
}
|
|
21
|
+
if (typeof arg === 'object') {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.stringify(arg);
|
|
24
|
+
} catch {
|
|
25
|
+
return String(arg);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return String(arg);
|
|
29
|
+
})
|
|
30
|
+
.join('&');
|
|
31
|
+
return `${cacheName}:${serializedArgs}`;
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/core/native-cache.ts
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
import { CacheProvider } from './cache-provider';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 缓存条目结构
|
|
5
|
-
*/
|
|
6
|
-
interface CacheEntry<T> {
|
|
7
|
-
value: T;
|
|
8
|
-
expiresAt: number | null;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 内存缓存提供者,基于 Map 实现
|
|
13
|
-
* 适用于单机应用,缓存随进程重启清除
|
|
14
|
-
*/
|
|
15
|
-
export class MemoryCacheProvider implements CacheProvider {
|
|
16
|
-
private cache = new Map<string, CacheEntry<unknown>>();
|
|
17
|
-
|
|
18
|
-
get<T>(key: string): T | undefined {
|
|
19
|
-
const entry = this.cache.get(key);
|
|
20
|
-
if (!entry) {
|
|
21
|
-
return undefined;
|
|
22
|
-
}
|
|
23
|
-
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
24
|
-
this.cache.delete(key);
|
|
25
|
-
return undefined;
|
|
26
|
-
}
|
|
27
|
-
return entry.value as T;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
set<T>(key: string, value: T, ttl?: number): void {
|
|
31
|
-
const expiresAt = ttl ? Date.now() + ttl * 1000 : null;
|
|
32
|
-
this.cache.set(key, { value, expiresAt });
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
delete(key: string): void {
|
|
36
|
-
this.cache.delete(key);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
clear(): void {
|
|
40
|
-
this.cache.clear();
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* 根据模式删除匹配的缓存键
|
|
45
|
-
* @param pattern glob模式字符串(如 user:*),末尾的 * 作为前缀匹配
|
|
46
|
-
*/
|
|
47
|
-
deleteByPattern(pattern: string): void {
|
|
48
|
-
const prefix = pattern.replace(/\*$/, '');
|
|
49
|
-
for (const key of this.cache.keys()) {
|
|
50
|
-
if (key.startsWith(prefix)) {
|
|
51
|
-
this.cache.delete(key);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
1
|
+
import { CacheProvider } from './cache-provider';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 缓存条目结构
|
|
5
|
+
*/
|
|
6
|
+
interface CacheEntry<T> {
|
|
7
|
+
value: T;
|
|
8
|
+
expiresAt: number | null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 内存缓存提供者,基于 Map 实现
|
|
13
|
+
* 适用于单机应用,缓存随进程重启清除
|
|
14
|
+
*/
|
|
15
|
+
export class MemoryCacheProvider implements CacheProvider {
|
|
16
|
+
private cache = new Map<string, CacheEntry<unknown>>();
|
|
17
|
+
|
|
18
|
+
get<T>(key: string): T | undefined {
|
|
19
|
+
const entry = this.cache.get(key);
|
|
20
|
+
if (!entry) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
if (entry.expiresAt !== null && Date.now() > entry.expiresAt) {
|
|
24
|
+
this.cache.delete(key);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
return entry.value as T;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
set<T>(key: string, value: T, ttl?: number): void {
|
|
31
|
+
const expiresAt = ttl ? Date.now() + ttl * 1000 : null;
|
|
32
|
+
this.cache.set(key, { value, expiresAt });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
delete(key: string): void {
|
|
36
|
+
this.cache.delete(key);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
clear(): void {
|
|
40
|
+
this.cache.clear();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 根据模式删除匹配的缓存键
|
|
45
|
+
* @param pattern glob模式字符串(如 user:*),末尾的 * 作为前缀匹配
|
|
46
|
+
*/
|
|
47
|
+
deleteByPattern(pattern: string): void {
|
|
48
|
+
const prefix = pattern.replace(/\*$/, '');
|
|
49
|
+
for (const key of this.cache.keys()) {
|
|
50
|
+
if (key.startsWith(prefix)) {
|
|
51
|
+
this.cache.delete(key);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|