|
1 | | -import bin from "../../intel.bin" |
2 | 1 | import { IntelDb } from "./lib/intel" |
3 | 2 |
|
4 | | -const db = new IntelDb(bin as ArrayBuffer) |
5 | | -db.lookup("8.8.8.8") // warm v4 path |
6 | | -db.lookup("2606:4700:4700::1111") // warm v6 path |
| 3 | +type Env = { INTEL: KVNamespace; INTEL_KEY?: string } |
| 4 | + |
| 5 | +let db: IntelDb | null = null |
| 6 | +let loading: Promise<IntelDb> | null = null |
| 7 | + |
| 8 | +async function getDb(env: Env): Promise<IntelDb> { |
| 9 | + if (db) return db |
| 10 | + if (!loading) loading = load(env) |
| 11 | + return loading |
| 12 | +} |
| 13 | + |
| 14 | +async function load(env: Env): Promise<IntelDb> { |
| 15 | + const buffer = await env.INTEL.get(env.INTEL_KEY || "intel.bin", "arrayBuffer") |
| 16 | + if (!buffer) throw new Error("intel.bin missing from KV") |
| 17 | + const loaded = new IntelDb(buffer) |
| 18 | + loaded.lookup("8.8.8.8") // warm v4 path |
| 19 | + loaded.lookup("2606:4700:4700::1111") // warm v6 path |
| 20 | + db = loaded |
| 21 | + return loaded |
| 22 | +} |
7 | 23 |
|
8 | 24 | export default { |
9 | | - async fetch(request: Request, _env: unknown, ctx: ExecutionContext): Promise<Response> { |
| 25 | + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
10 | 26 | const url = new URL(request.url) |
11 | 27 | const queryIp = url.searchParams.get("ip") |
12 | 28 | const ip = queryIp || request.headers.get("CF-Connecting-IP") || "" |
13 | 29 | if (!ip) return json({ error: "no ip" }, 400, "no-store") |
14 | 30 |
|
15 | | - if (!queryIp) return json(db.lookup(ip), 200, "private, max-age=3600") |
| 31 | + const intel = await getDb(env) |
| 32 | + if (!queryIp) return json(intel.lookup(ip), 200, "private, max-age=3600") |
16 | 33 |
|
17 | 34 | const cached = await caches.default.match(request) |
18 | 35 | if (cached) return cached |
19 | 36 |
|
20 | | - const response = json(db.lookup(ip), 200, "public, max-age=3600") |
| 37 | + const response = json(intel.lookup(ip), 200, "public, max-age=3600") |
21 | 38 | ctx.waitUntil(caches.default.put(request, response.clone())) |
22 | 39 | return response |
23 | 40 | }, |
|
0 commit comments