File size: 4,975 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import type { RuntimeConfig } from "../config";
import { errorLogSummary } from "../shared/errors";
import { log } from "../shared/logging";

type OriginScopedStringCacheOptions = {
	cachePrefix: string;
	ttlSec: number;
	payloadKey: string;
	logLabel: string;
	l1MaxEntries?: number;
};

type OriginScopedStringCachePayload = Record<string, unknown> & {
	created_at_ms?: unknown;
};

function geminiOrigin(cfg: RuntimeConfig): string {
	return (cfg.gemini_origin || "https://gemini.google.com").replace(/\/$/, "");
}

function geminiCacheScope(cfg: RuntimeConfig): string {
	return geminiOrigin(cfg);
}

function workerCache(): Cache | null {
	if (typeof caches === "undefined") return null;
	const cacheStorage = caches as CacheStorage & { default?: Cache };
	return cacheStorage.default || null;
}

export function createOriginScopedStringCache(
	options: OriginScopedStringCacheOptions,
) {
	const refreshes = new Map<string, Promise<string>>();
	const l1 = new Map<string, { value: string; expiresAt: number }>();
	const l1MaxEntries = positiveInt(options.l1MaxEntries, 32);

	const cacheKey = (scope: string): Request =>
		new Request(`${options.cachePrefix}${encodeURIComponent(scope)}`);

	const setL1 = (
		scope: string,
		value: string,
		now: number = Date.now(),
	): void => {
		l1.delete(scope);
		l1.set(scope, {
			value,
			expiresAt: now + options.ttlSec * 1000,
		});
		while (l1.size > l1MaxEntries) {
			const oldestScope = l1.keys().next().value;
			if (oldestScope === undefined) break;
			l1.delete(oldestScope);
		}
	};

	const clearL1 = (scope?: string): void => {
		if (scope) l1.delete(scope);
		else l1.clear();
	};

	const put = (
		cfg: RuntimeConfig,
		scope: string,
		value: string,
		now: number,
	): Promise<void> => {
		const cache = workerCache();
		if (!cache) return Promise.resolve();
		return cache
			.put(
				cacheKey(scope),
				new Response(
					JSON.stringify({
						[options.payloadKey]: value,
						created_at_ms: now,
					}),
					{
						headers: {
							"Content-Type": "application/json",
							"Cache-Control": `public, max-age=${options.ttlSec}`,
						},
					},
				),
			)
			.catch((e) => {
				logCacheError(cfg, `failed to cache ${options.logLabel}`, e);
			});
	};

	const getCached = async (cfg: RuntimeConfig): Promise<string> => {
		const scope = geminiCacheScope(cfg);
		const now = Date.now();
		const cached = l1.get(scope);
		if (cached && cached.expiresAt > now) {
			l1.delete(scope);
			l1.set(scope, cached);
			return cached.value;
		}
		clearL1(scope);
		const cache = workerCache();
		if (!cache) return "";
		try {
			const resp = await cache.match(cacheKey(scope));
			if (!resp) return "";
			const data = (await resp
				.json()
				.catch(() => null)) as OriginScopedStringCachePayload | null;
			const value = validString(data?.[options.payloadKey]);
			const createdAt = Number(data?.created_at_ms);
			if (!value || !Number.isFinite(createdAt)) return "";
			if (now - createdAt > options.ttlSec * 1000) {
				await cache.delete(cacheKey(scope)).catch(() => false);
				return "";
			}
			setL1(scope, value, createdAt);
			return value;
		} catch (e) {
			logCacheError(cfg, `failed to read cached ${options.logLabel}`, e);
			return "";
		}
	};

	const deleteCached = async (cfg: RuntimeConfig): Promise<void> => {
		const scope = geminiCacheScope(cfg);
		clearL1(scope);
		const cache = workerCache();
		if (!cache) return;
		await cache.delete(cacheKey(scope)).catch(() => false);
	};

	const setCached = async (
		cfg: RuntimeConfig,
		rawValue: string,
	): Promise<void> => {
		const value = validString(rawValue);
		if (!value) return;
		const scope = geminiCacheScope(cfg);
		const now = Date.now();
		setL1(scope, value, now);
		const write = put(cfg, scope, value, now);
		if (cfg.execution_ctx) {
			cfg.execution_ctx.waitUntil(write);
			return;
		}
		await write;
	};

	const getFresh = async (
		cfg: RuntimeConfig,
		fetchFresh: (cfg: RuntimeConfig) => Promise<string>,
	): Promise<string> => {
		const refreshKey = geminiCacheScope(cfg);
		const pending = refreshes.get(refreshKey);
		if (pending) return pending;

		const refresh = (async () => {
			const value = validString(await fetchFresh(cfg));
			if (value) await setCached(cfg, value);
			return value;
		})();
		refreshes.set(refreshKey, refresh);
		try {
			return await refresh;
		} finally {
			refreshes.delete(refreshKey);
		}
	};

	return {
		getCached,
		setCached,
		deleteCached,
		getFresh,
		reset(): void {
			clearL1();
			refreshes.clear();
		},
	};
}

function validString(value: unknown): string {
	const text = typeof value === "string" ? value.trim() : "";
	return text ? text : "";
}

function positiveInt(value: number | undefined, fallback: number): number {
	return Number.isInteger(value) && Number(value) > 0
		? Number(value)
		: fallback;
}

function logCacheError(
	cfg: RuntimeConfig,
	prefix: string,
	error: unknown,
): void {
	log(cfg, `${prefix} ${errorLogSummary(error)}`);
}