qwenproxy-cli 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.
Files changed (109) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +77 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2878 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +259 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/update-cli.ts +121 -0
  105. package/src/utils/context-truncation.ts +84 -84
  106. package/src/utils/json.ts +380 -380
  107. package/src/utils/session-id.ts +37 -37
  108. package/src/utils/tool-call-guard.ts +84 -84
  109. package/src/utils/types.ts +109 -109
@@ -1,385 +1,385 @@
1
- import { promisify } from "util";
2
- import { brotliCompress, brotliDecompress, constants } from "zlib";
3
- import { config } from "../core/config.js";
4
- import { metrics } from "../core/metrics.js";
5
-
6
- const compressAsync = promisify(brotliCompress);
7
- const decompressAsync = promisify(brotliDecompress);
8
-
9
- export type CacheKey =
10
- | `auth:${string}`
11
- | `session:${string}`
12
- | `prompt:${string}`
13
- | `response:${string}`
14
- | `rate:${string}`
15
- | `topic:${string}`;
16
-
17
- interface CacheEntry<T> {
18
- value: T;
19
- expiresAt: number;
20
- compressed?: boolean;
21
- }
22
-
23
- export class MemoryCache {
24
- private connected = false;
25
- private store: Map<string, CacheEntry<any>>;
26
- private defaultTTL: number;
27
- private prefix: string;
28
- private cleanupInterval: NodeJS.Timeout | null;
29
- private hits: number = 0;
30
- private misses: number = 0;
31
- private totalBytesSaved: number = 0;
32
- private totalCompressedBytes: number = 0;
33
- private compressionCount: number = 0;
34
- private mutationQueue: Promise<void> = Promise.resolve();
35
- // Cache for compiled regex patterns in scan operations (upstream: a63f054)
36
- private scanRegexCache: Map<string, RegExp> = new Map();
37
-
38
- constructor(options?: { prefix?: string; defaultTTL?: number }) {
39
- this.prefix = options?.prefix || "qwenproxy:";
40
- this.defaultTTL = options?.defaultTTL || config.cache.defaultTTL;
41
- this.store = new Map();
42
- this.cleanupInterval = null;
43
-
44
- this.startCleanup();
45
- }
46
-
47
- private startCleanup(): void {
48
- this.cleanupInterval = setInterval(() => {
49
- if (this.store.size === 0) return;
50
- const now = Date.now();
51
- for (const [key, entry] of this.store.entries()) {
52
- if (entry.expiresAt <= now) {
53
- this.store.delete(key);
54
- }
55
- }
56
- }, 60000);
57
- this.cleanupInterval.unref?.();
58
- }
59
-
60
- async connect(): Promise<void> {
61
- this.connected = true;
62
- }
63
-
64
- async set<T>(key: CacheKey, value: T, ttl?: number): Promise<void> {
65
- const serialized = this.serialize(value);
66
- let storedValue: string | Buffer = serialized;
67
- let compressed = false;
68
- let originalSize: number;
69
-
70
- if (config.cache.compression.enabled) {
71
- // Encode once and reuse for both the size check and compression,
72
- // avoiding a second UTF-8 pass over large values.
73
- const encoded = Buffer.from(serialized);
74
- originalSize = encoded.length;
75
- if (originalSize >= config.cache.compression.threshold) {
76
- try {
77
- const compressedBuffer = await compressAsync(encoded, {
78
- params: {
79
- [constants.BROTLI_PARAM_QUALITY]: config.cache.compression.level,
80
- },
81
- });
82
-
83
- const compressedSize = compressedBuffer.length;
84
- const saved = originalSize - compressedSize;
85
-
86
- if (saved > 0) {
87
- storedValue = compressedBuffer;
88
- compressed = true;
89
- this.totalBytesSaved += saved;
90
- this.totalCompressedBytes += compressedSize;
91
- this.compressionCount++;
92
-
93
- metrics.increment("cache.compression.bytes.saved", saved);
94
- metrics.histogram(
95
- "cache.compression.ratio",
96
- originalSize / compressedSize,
97
- );
98
- }
99
- } catch (err) {
100
- // Compression failed, store uncompressed
101
- }
102
- }
103
- } else {
104
- originalSize = Buffer.byteLength(serialized);
105
- }
106
-
107
- const effectiveTTL = ttl || this.defaultTTL;
108
- const fullKey = this.prefix + key;
109
-
110
- this.store.set(fullKey, {
111
- value: storedValue,
112
- expiresAt: Date.now() + effectiveTTL * 1000,
113
- compressed,
114
- });
115
-
116
- metrics.increment("cache.set");
117
- metrics.histogram("cache.value.size", originalSize);
118
- }
119
-
120
- async get<T>(key: CacheKey): Promise<T | null> {
121
- const fullKey = this.prefix + key;
122
- const entry = this.store.get(fullKey);
123
-
124
- if (!entry || entry.expiresAt <= Date.now()) {
125
- if (entry) this.store.delete(fullKey);
126
- this.misses++;
127
- metrics.increment("cache.miss");
128
- return null;
129
- }
130
-
131
- this.hits++;
132
- metrics.increment("cache.hit");
133
-
134
- // Decompress if needed
135
- if (entry.compressed && Buffer.isBuffer(entry.value)) {
136
- try {
137
- const decompressed = await decompressAsync(entry.value);
138
- return this.deserialize<T>(decompressed.toString());
139
- } catch (err) {
140
- // Decompression failed, return null
141
- this.store.delete(fullKey);
142
- return null;
143
- }
144
- }
145
-
146
- if (entry.compressed) {
147
- this.store.delete(fullKey);
148
- return null;
149
- }
150
-
151
- const serialized =
152
- typeof entry.value === "string" ? entry.value : String(entry.value);
153
-
154
- return this.deserialize<T>(serialized);
155
- }
156
-
157
- async delete(key: CacheKey): Promise<void> {
158
- const fullKey = this.prefix + key;
159
- this.store.delete(fullKey);
160
- metrics.increment("cache.deleted");
161
- }
162
-
163
- async exists(key: CacheKey): Promise<boolean> {
164
- const fullKey = this.prefix + key;
165
- const entry = this.store.get(fullKey);
166
- if (!entry || entry.expiresAt <= Date.now()) {
167
- if (entry) this.store.delete(fullKey);
168
- return false;
169
- }
170
- return true;
171
- }
172
-
173
- async setWithNX<T>(key: CacheKey, value: T, ttl?: number): Promise<boolean> {
174
- return this.withMutation(async () => {
175
- const fullKey = this.prefix + key;
176
- const entry = this.store.get(fullKey);
177
- if (entry && entry.expiresAt > Date.now()) {
178
- return false;
179
- }
180
- if (entry) this.store.delete(fullKey);
181
- await this.set(key, value, ttl);
182
- return true;
183
- });
184
- }
185
-
186
- async increment(
187
- key: CacheKey,
188
- by: number = 1,
189
- ttl?: number,
190
- ): Promise<number> {
191
- return this.withMutation(async () => {
192
- const currentValue = await this.get<number>(key);
193
- const current =
194
- typeof currentValue === "number" && Number.isFinite(currentValue)
195
- ? currentValue
196
- : 0;
197
-
198
- const newValue = current + by;
199
- const effectiveTTL = ttl || this.defaultTTL;
200
- const fullKey = this.prefix + key;
201
-
202
- this.store.set(fullKey, {
203
- value: this.serialize(newValue),
204
- expiresAt: Date.now() + effectiveTTL * 1000,
205
- });
206
-
207
- return newValue;
208
- });
209
- }
210
-
211
- async getMulti<T>(keys: CacheKey[]): Promise<(T | null)[]> {
212
- return Promise.all(keys.map((key) => this.get<T>(key)));
213
- }
214
-
215
- async scan(pattern: string, _count: number = 100): Promise<string[]> {
216
- // Use cached regex for repeated patterns (upstream: a63f054)
217
- let regex = this.scanRegexCache.get(pattern);
218
- if (!regex) {
219
- regex = new RegExp(this.prefix + pattern.replace(/\*/g, ".*"));
220
- this.scanRegexCache.set(pattern, regex);
221
- }
222
- const now = Date.now();
223
- const keys: string[] = [];
224
-
225
- for (const [key, entry] of this.store.entries()) {
226
- if (regex.test(key) && entry.expiresAt > now) {
227
- keys.push(key);
228
- }
229
- }
230
- return keys;
231
- }
232
-
233
- async flush(pattern?: string): Promise<void> {
234
- if (pattern) {
235
- const keys = await this.scan(pattern);
236
- for (const key of keys) {
237
- this.store.delete(key);
238
- }
239
- } else {
240
- this.store.clear();
241
- }
242
- metrics.increment("cache.flushed");
243
- }
244
-
245
- async getStats(): Promise<{
246
- connected: boolean;
247
- keysCount: number;
248
- memoryUsage: string;
249
- hitRatio: number;
250
- compressionRatio: number;
251
- bytesSaved: number;
252
- }> {
253
- const now = Date.now();
254
- let validKeys = 0;
255
- let totalBytes = 0;
256
- for (const [key, entry] of this.store.entries()) {
257
- if (entry.expiresAt > now) {
258
- validKeys++;
259
- const valueSize = Buffer.isBuffer(entry.value)
260
- ? entry.value.length
261
- : Buffer.byteLength(String(entry.value));
262
- totalBytes += valueSize + Buffer.byteLength(key);
263
- }
264
- }
265
-
266
- const totalRequests = this.hits + this.misses;
267
- const hitRatio = totalRequests > 0 ? this.hits / totalRequests : 0;
268
- const avgCompressionRatio =
269
- this.totalCompressedBytes > 0
270
- ? (this.totalCompressedBytes + this.totalBytesSaved) /
271
- this.totalCompressedBytes
272
- : 1;
273
-
274
- // Update gauge metrics
275
- metrics.gauge("cache.hit.ratio", hitRatio);
276
- metrics.gauge("cache.memory.usage.bytes", totalBytes);
277
- metrics.gauge("cache.entries.count", validKeys);
278
-
279
- return {
280
- connected: this.connected,
281
- keysCount: validKeys,
282
- memoryUsage: `${(totalBytes / 1024).toFixed(2)}KB`,
283
- hitRatio,
284
- compressionRatio: avgCompressionRatio,
285
- bytesSaved: this.totalBytesSaved,
286
- };
287
- }
288
-
289
- private async withMutation<T>(fn: () => Promise<T>): Promise<T> {
290
- const previous = this.mutationQueue;
291
- let release!: () => void;
292
- this.mutationQueue = new Promise<void>((resolve) => {
293
- release = resolve;
294
- });
295
-
296
- await previous;
297
- try {
298
- return await fn();
299
- } finally {
300
- release();
301
- }
302
- }
303
-
304
- async close(): Promise<void> {
305
- if (this.cleanupInterval) {
306
- clearInterval(this.cleanupInterval);
307
- this.cleanupInterval = null;
308
- }
309
- this.store.clear();
310
- this.connected = false;
311
- }
312
-
313
- // Preserve primitive types without coercing numeric-looking strings.
314
- private serialize<T>(value: T): string {
315
- if (value === null) return "l:";
316
- if (value === undefined) return "u:";
317
-
318
- switch (typeof value) {
319
- case "string":
320
- return `s:${value}`;
321
- case "number":
322
- return `n:${value}`;
323
- case "boolean":
324
- return value ? "b:1" : "b:0";
325
- default:
326
- return `j:${JSON.stringify(value)}`;
327
- }
328
- }
329
-
330
- private deserialize<T>(serialized: string): T {
331
- if (serialized.length >= 2 && serialized[1] === ":") {
332
- const type = serialized[0];
333
- const payload = serialized.slice(2);
334
-
335
- switch (type) {
336
- case "l":
337
- return null as T;
338
- case "u":
339
- return undefined as T;
340
- case "s":
341
- return payload as T;
342
- case "n":
343
- return Number(payload) as T;
344
- case "b":
345
- return (payload === "1") as T;
346
- case "j":
347
- return JSON.parse(payload) as T;
348
- }
349
- }
350
-
351
- if (serialized === "null") return null as T;
352
- if (serialized === "undefined") return undefined as T;
353
- if (serialized === "true") return true as T;
354
- if (serialized === "false") return false as T;
355
- if (/^-?\d+(\.\d+)?$/.test(serialized)) {
356
- return Number(serialized) as T;
357
- }
358
-
359
- try {
360
- return JSON.parse(serialized) as T;
361
- } catch {
362
- return serialized as T;
363
- }
364
- }
365
-
366
- // Invalidate entries by pattern (topic-based)
367
- async invalidateByPattern(pattern: string): Promise<number> {
368
- const keys = await this.scan(pattern);
369
- let count = 0;
370
- for (const key of keys) {
371
- this.store.delete(key);
372
- count++;
373
- }
374
- if (count > 0) {
375
- metrics.increment("cache.topic.invalidation", count);
376
- }
377
- return count;
378
- }
379
-
380
- // Invalidate all entries for a session
381
- async invalidateBySession(sessionId: string): Promise<number> {
382
- const pattern = `*session:*${sessionId}*`;
383
- return this.invalidateByPattern(pattern);
384
- }
385
- }
1
+ import { promisify } from "util";
2
+ import { brotliCompress, brotliDecompress, constants } from "zlib";
3
+ import { config } from "../core/config.js";
4
+ import { metrics } from "../core/metrics.js";
5
+
6
+ const compressAsync = promisify(brotliCompress);
7
+ const decompressAsync = promisify(brotliDecompress);
8
+
9
+ export type CacheKey =
10
+ | `auth:${string}`
11
+ | `session:${string}`
12
+ | `prompt:${string}`
13
+ | `response:${string}`
14
+ | `rate:${string}`
15
+ | `topic:${string}`;
16
+
17
+ interface CacheEntry<T> {
18
+ value: T;
19
+ expiresAt: number;
20
+ compressed?: boolean;
21
+ }
22
+
23
+ export class MemoryCache {
24
+ private connected = false;
25
+ private store: Map<string, CacheEntry<any>>;
26
+ private defaultTTL: number;
27
+ private prefix: string;
28
+ private cleanupInterval: NodeJS.Timeout | null;
29
+ private hits: number = 0;
30
+ private misses: number = 0;
31
+ private totalBytesSaved: number = 0;
32
+ private totalCompressedBytes: number = 0;
33
+ private compressionCount: number = 0;
34
+ private mutationQueue: Promise<void> = Promise.resolve();
35
+ // Cache for compiled regex patterns in scan operations (upstream: a63f054)
36
+ private scanRegexCache: Map<string, RegExp> = new Map();
37
+
38
+ constructor(options?: { prefix?: string; defaultTTL?: number }) {
39
+ this.prefix = options?.prefix || "qwenproxy:";
40
+ this.defaultTTL = options?.defaultTTL || config.cache.defaultTTL;
41
+ this.store = new Map();
42
+ this.cleanupInterval = null;
43
+
44
+ this.startCleanup();
45
+ }
46
+
47
+ private startCleanup(): void {
48
+ this.cleanupInterval = setInterval(() => {
49
+ if (this.store.size === 0) return;
50
+ const now = Date.now();
51
+ for (const [key, entry] of this.store.entries()) {
52
+ if (entry.expiresAt <= now) {
53
+ this.store.delete(key);
54
+ }
55
+ }
56
+ }, 60000);
57
+ this.cleanupInterval.unref?.();
58
+ }
59
+
60
+ async connect(): Promise<void> {
61
+ this.connected = true;
62
+ }
63
+
64
+ async set<T>(key: CacheKey, value: T, ttl?: number): Promise<void> {
65
+ const serialized = this.serialize(value);
66
+ let storedValue: string | Buffer = serialized;
67
+ let compressed = false;
68
+ let originalSize: number;
69
+
70
+ if (config.cache.compression.enabled) {
71
+ // Encode once and reuse for both the size check and compression,
72
+ // avoiding a second UTF-8 pass over large values.
73
+ const encoded = Buffer.from(serialized);
74
+ originalSize = encoded.length;
75
+ if (originalSize >= config.cache.compression.threshold) {
76
+ try {
77
+ const compressedBuffer = await compressAsync(encoded, {
78
+ params: {
79
+ [constants.BROTLI_PARAM_QUALITY]: config.cache.compression.level,
80
+ },
81
+ });
82
+
83
+ const compressedSize = compressedBuffer.length;
84
+ const saved = originalSize - compressedSize;
85
+
86
+ if (saved > 0) {
87
+ storedValue = compressedBuffer;
88
+ compressed = true;
89
+ this.totalBytesSaved += saved;
90
+ this.totalCompressedBytes += compressedSize;
91
+ this.compressionCount++;
92
+
93
+ metrics.increment("cache.compression.bytes.saved", saved);
94
+ metrics.histogram(
95
+ "cache.compression.ratio",
96
+ originalSize / compressedSize,
97
+ );
98
+ }
99
+ } catch (err) {
100
+ // Compression failed, store uncompressed
101
+ }
102
+ }
103
+ } else {
104
+ originalSize = Buffer.byteLength(serialized);
105
+ }
106
+
107
+ const effectiveTTL = ttl || this.defaultTTL;
108
+ const fullKey = this.prefix + key;
109
+
110
+ this.store.set(fullKey, {
111
+ value: storedValue,
112
+ expiresAt: Date.now() + effectiveTTL * 1000,
113
+ compressed,
114
+ });
115
+
116
+ metrics.increment("cache.set");
117
+ metrics.histogram("cache.value.size", originalSize);
118
+ }
119
+
120
+ async get<T>(key: CacheKey): Promise<T | null> {
121
+ const fullKey = this.prefix + key;
122
+ const entry = this.store.get(fullKey);
123
+
124
+ if (!entry || entry.expiresAt <= Date.now()) {
125
+ if (entry) this.store.delete(fullKey);
126
+ this.misses++;
127
+ metrics.increment("cache.miss");
128
+ return null;
129
+ }
130
+
131
+ this.hits++;
132
+ metrics.increment("cache.hit");
133
+
134
+ // Decompress if needed
135
+ if (entry.compressed && Buffer.isBuffer(entry.value)) {
136
+ try {
137
+ const decompressed = await decompressAsync(entry.value);
138
+ return this.deserialize<T>(decompressed.toString());
139
+ } catch (err) {
140
+ // Decompression failed, return null
141
+ this.store.delete(fullKey);
142
+ return null;
143
+ }
144
+ }
145
+
146
+ if (entry.compressed) {
147
+ this.store.delete(fullKey);
148
+ return null;
149
+ }
150
+
151
+ const serialized =
152
+ typeof entry.value === "string" ? entry.value : String(entry.value);
153
+
154
+ return this.deserialize<T>(serialized);
155
+ }
156
+
157
+ async delete(key: CacheKey): Promise<void> {
158
+ const fullKey = this.prefix + key;
159
+ this.store.delete(fullKey);
160
+ metrics.increment("cache.deleted");
161
+ }
162
+
163
+ async exists(key: CacheKey): Promise<boolean> {
164
+ const fullKey = this.prefix + key;
165
+ const entry = this.store.get(fullKey);
166
+ if (!entry || entry.expiresAt <= Date.now()) {
167
+ if (entry) this.store.delete(fullKey);
168
+ return false;
169
+ }
170
+ return true;
171
+ }
172
+
173
+ async setWithNX<T>(key: CacheKey, value: T, ttl?: number): Promise<boolean> {
174
+ return this.withMutation(async () => {
175
+ const fullKey = this.prefix + key;
176
+ const entry = this.store.get(fullKey);
177
+ if (entry && entry.expiresAt > Date.now()) {
178
+ return false;
179
+ }
180
+ if (entry) this.store.delete(fullKey);
181
+ await this.set(key, value, ttl);
182
+ return true;
183
+ });
184
+ }
185
+
186
+ async increment(
187
+ key: CacheKey,
188
+ by: number = 1,
189
+ ttl?: number,
190
+ ): Promise<number> {
191
+ return this.withMutation(async () => {
192
+ const currentValue = await this.get<number>(key);
193
+ const current =
194
+ typeof currentValue === "number" && Number.isFinite(currentValue)
195
+ ? currentValue
196
+ : 0;
197
+
198
+ const newValue = current + by;
199
+ const effectiveTTL = ttl || this.defaultTTL;
200
+ const fullKey = this.prefix + key;
201
+
202
+ this.store.set(fullKey, {
203
+ value: this.serialize(newValue),
204
+ expiresAt: Date.now() + effectiveTTL * 1000,
205
+ });
206
+
207
+ return newValue;
208
+ });
209
+ }
210
+
211
+ async getMulti<T>(keys: CacheKey[]): Promise<(T | null)[]> {
212
+ return Promise.all(keys.map((key) => this.get<T>(key)));
213
+ }
214
+
215
+ async scan(pattern: string, _count: number = 100): Promise<string[]> {
216
+ // Use cached regex for repeated patterns (upstream: a63f054)
217
+ let regex = this.scanRegexCache.get(pattern);
218
+ if (!regex) {
219
+ regex = new RegExp(this.prefix + pattern.replace(/\*/g, ".*"));
220
+ this.scanRegexCache.set(pattern, regex);
221
+ }
222
+ const now = Date.now();
223
+ const keys: string[] = [];
224
+
225
+ for (const [key, entry] of this.store.entries()) {
226
+ if (regex.test(key) && entry.expiresAt > now) {
227
+ keys.push(key);
228
+ }
229
+ }
230
+ return keys;
231
+ }
232
+
233
+ async flush(pattern?: string): Promise<void> {
234
+ if (pattern) {
235
+ const keys = await this.scan(pattern);
236
+ for (const key of keys) {
237
+ this.store.delete(key);
238
+ }
239
+ } else {
240
+ this.store.clear();
241
+ }
242
+ metrics.increment("cache.flushed");
243
+ }
244
+
245
+ async getStats(): Promise<{
246
+ connected: boolean;
247
+ keysCount: number;
248
+ memoryUsage: string;
249
+ hitRatio: number;
250
+ compressionRatio: number;
251
+ bytesSaved: number;
252
+ }> {
253
+ const now = Date.now();
254
+ let validKeys = 0;
255
+ let totalBytes = 0;
256
+ for (const [key, entry] of this.store.entries()) {
257
+ if (entry.expiresAt > now) {
258
+ validKeys++;
259
+ const valueSize = Buffer.isBuffer(entry.value)
260
+ ? entry.value.length
261
+ : Buffer.byteLength(String(entry.value));
262
+ totalBytes += valueSize + Buffer.byteLength(key);
263
+ }
264
+ }
265
+
266
+ const totalRequests = this.hits + this.misses;
267
+ const hitRatio = totalRequests > 0 ? this.hits / totalRequests : 0;
268
+ const avgCompressionRatio =
269
+ this.totalCompressedBytes > 0
270
+ ? (this.totalCompressedBytes + this.totalBytesSaved) /
271
+ this.totalCompressedBytes
272
+ : 1;
273
+
274
+ // Update gauge metrics
275
+ metrics.gauge("cache.hit.ratio", hitRatio);
276
+ metrics.gauge("cache.memory.usage.bytes", totalBytes);
277
+ metrics.gauge("cache.entries.count", validKeys);
278
+
279
+ return {
280
+ connected: this.connected,
281
+ keysCount: validKeys,
282
+ memoryUsage: `${(totalBytes / 1024).toFixed(2)}KB`,
283
+ hitRatio,
284
+ compressionRatio: avgCompressionRatio,
285
+ bytesSaved: this.totalBytesSaved,
286
+ };
287
+ }
288
+
289
+ private async withMutation<T>(fn: () => Promise<T>): Promise<T> {
290
+ const previous = this.mutationQueue;
291
+ let release!: () => void;
292
+ this.mutationQueue = new Promise<void>((resolve) => {
293
+ release = resolve;
294
+ });
295
+
296
+ await previous;
297
+ try {
298
+ return await fn();
299
+ } finally {
300
+ release();
301
+ }
302
+ }
303
+
304
+ async close(): Promise<void> {
305
+ if (this.cleanupInterval) {
306
+ clearInterval(this.cleanupInterval);
307
+ this.cleanupInterval = null;
308
+ }
309
+ this.store.clear();
310
+ this.connected = false;
311
+ }
312
+
313
+ // Preserve primitive types without coercing numeric-looking strings.
314
+ private serialize<T>(value: T): string {
315
+ if (value === null) return "l:";
316
+ if (value === undefined) return "u:";
317
+
318
+ switch (typeof value) {
319
+ case "string":
320
+ return `s:${value}`;
321
+ case "number":
322
+ return `n:${value}`;
323
+ case "boolean":
324
+ return value ? "b:1" : "b:0";
325
+ default:
326
+ return `j:${JSON.stringify(value)}`;
327
+ }
328
+ }
329
+
330
+ private deserialize<T>(serialized: string): T {
331
+ if (serialized.length >= 2 && serialized[1] === ":") {
332
+ const type = serialized[0];
333
+ const payload = serialized.slice(2);
334
+
335
+ switch (type) {
336
+ case "l":
337
+ return null as T;
338
+ case "u":
339
+ return undefined as T;
340
+ case "s":
341
+ return payload as T;
342
+ case "n":
343
+ return Number(payload) as T;
344
+ case "b":
345
+ return (payload === "1") as T;
346
+ case "j":
347
+ return JSON.parse(payload) as T;
348
+ }
349
+ }
350
+
351
+ if (serialized === "null") return null as T;
352
+ if (serialized === "undefined") return undefined as T;
353
+ if (serialized === "true") return true as T;
354
+ if (serialized === "false") return false as T;
355
+ if (/^-?\d+(\.\d+)?$/.test(serialized)) {
356
+ return Number(serialized) as T;
357
+ }
358
+
359
+ try {
360
+ return JSON.parse(serialized) as T;
361
+ } catch {
362
+ return serialized as T;
363
+ }
364
+ }
365
+
366
+ // Invalidate entries by pattern (topic-based)
367
+ async invalidateByPattern(pattern: string): Promise<number> {
368
+ const keys = await this.scan(pattern);
369
+ let count = 0;
370
+ for (const key of keys) {
371
+ this.store.delete(key);
372
+ count++;
373
+ }
374
+ if (count > 0) {
375
+ metrics.increment("cache.topic.invalidation", count);
376
+ }
377
+ return count;
378
+ }
379
+
380
+ // Invalidate all entries for a session
381
+ async invalidateBySession(sessionId: string): Promise<number> {
382
+ const pattern = `*session:*${sessionId}*`;
383
+ return this.invalidateByPattern(pattern);
384
+ }
385
+ }