The best way to control Claude Code, Codex and more from any computer or phone

main
ts 57 lines 1.83 KB
Raw
1 /**
2 * Deploy-time Cloudflare KV sink for prerender seed.
3 *
4 * Runtime Workers use {@link kvAdapter} (`env.VINEXT_KV_CACHE` binding).
5 * Deploy cannot call that binding — it talks the distilled KV HTTP API
6 * with `accountId` + `namespaceId` from the Worker env. Both write the
7 * same {@link DataCacheStore} shape (`putText`) so Redis / S3 / KV seed
8 * through one function.
9 */
10 import * as kv from "@distilled.cloud/cloudflare/kv";
11 import { vinextCacheNamespaceFromEnv } from "../PrerenderCache.ts";
12 import type { SeedSink } from "./seed.ts";
13
14 /** Cloudflare KV rejects expirationTtl below 60 seconds. */
15 const MIN_KV_TTL_SECONDS = 60;
16
17 export type KvHttpNamespace = {
18 readonly accountId: string;
19 readonly namespaceId: string;
20 };
21
22 export const kvHttpNamespaceFromEnv = (
23 env: Record<string, unknown>,
24 ): KvHttpNamespace | undefined => {
25 const namespace = vinextCacheNamespaceFromEnv(env);
26 if (namespace === undefined || namespace.accountId === undefined) {
27 return undefined;
28 }
29 return {
30 accountId: namespace.accountId,
31 namespaceId: namespace.namespaceId,
32 };
33 };
34
35 const ttlSeconds = (ttlMs: number | undefined): number | undefined => {
36 if (ttlMs === undefined || ttlMs <= 0) return undefined;
37 return Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1000));
38 };
39
40 /**
41 * Effect sink over distilled `putNamespaceValue`. Requires the Worker
42 * provider's Cloudflare KV layer (same as the previous inline seed).
43 */
44 export const kvHttpSink = (
45 namespace: KvHttpNamespace,
46 ): SeedSink<kv.PutNamespaceValueError, kv.CloudflareOpContext> => ({
47 putText: (key, value, ttlMs) => {
48 const expirationTtl = ttlSeconds(ttlMs);
49 return kv.putNamespaceValue({
50 accountId: namespace.accountId,
51 namespaceId: namespace.namespaceId,
52 keyName: key,
53 value,
54 ...(expirationTtl !== undefined ? { expirationTtl } : {}),
55 });
56 },
57 });