Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

google-docs.ts

168 lines4.8 KB

1/**
2 * docs.cloud.google.com answers 429 to Workers egress from every colo
3 * (issue #517). One response is enough to stop: the rest of this poll
4 * reads what KV already has. A stored parse outlives the six-hour fresh
5 * window so the listing can still succeed while the host is refusing us.
6 * That serve is reported on the poll (`googleDocsFailures`). A load that
7 * only returned stored pages is not written back as a fresh hit, so the
8 * next poll after cooling probes again. A 429 with nothing stored still
9 * fails the poll. Any other status fails closed and does not count as
10 * this limit.
11 */
12import { errorMessage } from '#/server/errors.ts'
13import { getJson, putJson } from '#/server/kv.ts'
14​
15import { cachedDocs, DOCS_TTL_SECONDS, docsCacheKey } from './model-facts.ts'
16import type { DocsFailures } from './types.ts'
17​
18const HOST = 'docs.cloud.google.com'
19/** Long enough that the next 15-minute poll is the next probe. */
20const COOLING_MS = 15 * 60 * 1000
21/** Past the fresh window, still short enough to drop a retired page. */
22const STALE_TTL_SECONDS = 7 * 24 * 60 * 60
23/** Same cap as a poll's `docsFailures.first`. */
24const SERVES_KEPT = 5
25​
26let coolingUntil = 0
27/** Stored pages handed back during the current provider's listing. */
28let staleServes = 0
29let failed = 0
30let skipped = 0
31let first: DocsFailures['first'] = []
32​
33/** Drop this provider's serve list. Cooling stays, so the next provider in the same run still skips the host. */
34export function beginGoogleDocsPoll(): void {
35 staleServes = 0
36 failed = 0
37 skipped = 0
38 first = []
40​
41export function resetGoogleDocsLimit(): void {
42 coolingUntil = 0
43 beginGoogleDocsPoll()
45​
46/** What this provider's listing served from storage after a 429 or a cooling skip. Zeros clear `docs-failing`. */
47export function googleDocsFailures(): DocsFailures {
48 return { failed, skipped, first: first.slice() }
50​
51function staleKey(url: string): string {
52 return `docs-stale:${docsCacheKey(url).slice('docs:'.length)}`
54​
55function isDocsHost(url: string): boolean {
56 try {
57 return new URL(url).hostname === HOST
58 } catch {
59 return false
60 }
62​
63/** A fetch skipped because this host already answered 429. */
64class GoogleDocsCooling extends Error {
65 constructor(url: string) {
66 super(`google docs cooling: ${url}`)
67 this.name = 'GoogleDocsCooling'
68 }
70​
71function isDocs429(error: unknown): boolean {
72 return (
73 error instanceof Error &&
74 error.message.includes(HOST) &&
75 error.message.includes('→ 429')
76 )
78​
79function hostLimited(error: unknown): boolean {
80 return error instanceof GoogleDocsCooling || isDocs429(error)
82​
83function noteLimit(): void {
84 coolingUntil = Date.now() + COOLING_MS
86​
87function noteServe(url: string, error: unknown, elapsedMs: number): void {
88 staleServes += 1
89 // `first` is failures only. poll-models computes `failed - first.length`,
90 // so a cooling skip in that list makes the remainder negative.
91 if (error instanceof GoogleDocsCooling) {
92 skipped += 1
93 return
94 }
95 failed += 1
96 if (first.length >= SERVES_KEPT) return
97 first.push({
98 source: url,
99 error: errorMessage(error),
100 elapsedMs,
101 })
103​
104async function rememberStale<T>(
105 kv: KVNamespace,
106 url: string,
107 value: T,
108): Promise<void> {
109 const key = staleKey(url)
110 if ((await kv.get(key, 'text')) !== null) return
111 await putJson(kv, key, value, { expirationTtl: STALE_TTL_SECONDS })
113​
114async function staleOrThrow<T>(
115 kv: KVNamespace | undefined,
116 url: string,
117 error: unknown,
118 elapsedMs: number,
119): Promise<T> {
120 if (kv) {
121 const stale = await getJson<T>(kv, staleKey(url))
122 if (stale !== null) {
123 noteServe(url, error, elapsedMs)
124 return stale
125 }
126 }
127 throw error
129​
130/**
131 * `cachedDocs` for a docs.cloud.google.com page. Other URLs are unchanged.
132 * While the host is cooling, a miss is not fetched. A `load` that was
133 * satisfied by stored pages does not refresh this key.
134 */
135export async function cachedGoogleDocs<T>(
136 kv: KVNamespace | undefined,
137 url: string,
138 load: () => Promise<T>,
139): Promise<T> {
140 if (!isDocsHost(url)) return cachedDocs(kv, url, load)
141 const freshKey = docsCacheKey(url)
142 if (kv) {
143 const hit = await getJson<T>(kv, freshKey)
144 if (hit !== null) {
145 await rememberStale(kv, url, hit)
146 return hit
147 }
148 }
149 if (Date.now() < coolingUntil) {
150 return staleOrThrow(kv, url, new GoogleDocsCooling(url), 0)
151 }
152 const before = staleServes
153 const started = Date.now()
154 try {
155 const value = await load()
156 if (kv && staleServes === before) {
157 await putJson(kv, freshKey, value, { expirationTtl: DOCS_TTL_SECONDS })
158 await putJson(kv, staleKey(url), value, {
159 expirationTtl: STALE_TTL_SECONDS,
160 })
161 }
162 return value
163 } catch (error) {
164 if (!hostLimited(error)) throw error
165 if (isDocs429(error)) noteLimit()
166 return staleOrThrow(kv, url, error, Date.now() - started)
167 }