-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocCache.ts
More file actions
154 lines (133 loc) · 3.87 KB
/
docCache.ts
File metadata and controls
154 lines (133 loc) · 3.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// Copyright (c) Mapbox, Inc.
// Licensed under the MIT License.
const DEFAULT_TTL_MS = parseInt(
process.env.MAPBOX_DOCS_CACHE_TTL_MS ?? '3600000',
10
);
// Cache limits
const MAX_ENTRIES = 512;
export const MAX_ENTRY_BYTES = 2 * 1024 * 1024; // 2 MB per entry
const MAX_TOTAL_BYTES = 50 * 1024 * 1024; // 50 MB total
interface CacheEntry {
content: string;
expiresAt: number;
bytes: number;
}
/**
* Normalize a URL for use as a cache key by stripping query parameters
* and hash fragments. This prevents cache-busting via unique query strings
* from creating unbounded cache entries.
*/
export function normalizeCacheKey(url: string): string {
try {
const parsed = new URL(url);
parsed.search = '';
parsed.hash = '';
return parsed.toString();
} catch {
return url;
}
}
class DocCache {
private cache = new Map<string, CacheEntry>();
private totalBytes = 0;
get(url: string): string | null {
const key = normalizeCacheKey(url);
const entry = this.cache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
this.totalBytes -= entry.bytes;
this.cache.delete(key);
return null;
}
// Re-insert to move to end (LRU: most-recently-used stays at the back)
this.cache.delete(key);
this.cache.set(key, entry);
return entry.content;
}
set(url: string, content: string, ttlMs: number = DEFAULT_TTL_MS): void {
const bytes = Buffer.byteLength(content, 'utf8');
if (bytes > MAX_ENTRY_BYTES) {
return; // Silently reject oversized entries
}
const key = normalizeCacheKey(url);
// Remove existing entry for this key if present
const existing = this.cache.get(key);
if (existing) {
this.totalBytes -= existing.bytes;
this.cache.delete(key);
}
// Evict oldest entries (front of Map) until there is room
while (
this.cache.size >= MAX_ENTRIES ||
this.totalBytes + bytes > MAX_TOTAL_BYTES
) {
const oldestKey = this.cache.keys().next().value;
if (oldestKey === undefined) break;
const oldest = this.cache.get(oldestKey)!;
this.totalBytes -= oldest.bytes;
this.cache.delete(oldestKey);
}
this.cache.set(key, { content, expiresAt: Date.now() + ttlMs, bytes });
this.totalBytes += bytes;
}
has(url: string): boolean {
return this.get(url) !== null;
}
clear(): void {
this.cache.clear();
this.totalBytes = 0;
}
/** Exposed for testing only. */
get size(): number {
return this.cache.size;
}
/** Exposed for testing only. */
get currentTotalBytes(): number {
return this.totalBytes;
}
}
export const docCache = new DocCache();
/**
* Read a Response body up to `maxBytes`, aborting early if the limit is
* exceeded. Checks Content-Length first when present so no bytes are
* buffered for obviously-oversized responses.
*/
export async function readBodyWithLimit(
response: Response,
maxBytes: number
): Promise<string> {
const contentLength = response.headers.get('content-length');
if (contentLength) {
const cl = parseInt(contentLength, 10);
if (Number.isFinite(cl) && cl > maxBytes) {
throw new Error(
`Response too large: Content-Length ${cl} exceeds limit of ${maxBytes} bytes`
);
}
}
if (!response.body) {
const text = await response.text();
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
throw new Error('Response too large');
}
return text;
}
const chunks: Buffer[] = [];
let totalBytes = 0;
const reader = response.body.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > maxBytes) {
throw new Error('Response too large');
}
chunks.push(Buffer.from(value));
}
} finally {
reader.releaseLock();
}
return Buffer.concat(chunks).toString('utf8');
}