forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-content-cache.server.ts
More file actions
578 lines (506 loc) · 14.8 KB
/
Copy pathgithub-content-cache.server.ts
File metadata and controls
578 lines (506 loc) · 14.8 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import { and, eq, lt, sql } from 'drizzle-orm'
import { db } from '~/db/client'
import {
docsArtifactCache,
githubContentCache,
type GithubContentCache,
} from '~/db/schema'
const POSITIVE_STALE_MS = 5 * 60 * 1000
const NEGATIVE_STALE_MS = 15 * 60 * 1000
// Internal sentinel paths used for non-file metadata (branch SHA lookup,
// recursive tree). Allowed alongside normal repo paths.
const SENTINEL_PATHS = new Set([
'__github_branch__',
'__github_recursive_tree__',
])
const REPO_PATTERN = /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/
// Git refs allow a fairly wide character set, but we restrict to the subset
// we actually publish from (branch names + tags). No spaces, no shell
// metacharacters, no path traversal.
const GIT_REF_PATTERN = /^[a-zA-Z0-9._/-]+$/
const PATH_SEGMENT_PATTERN = /^[a-zA-Z0-9._-]+$/
const MAX_REPO_LEN = 100
const MAX_GIT_REF_LEN = 100
const MAX_PATH_LEN = 512
export class InvalidCacheKeyError extends Error {
constructor(field: string, value: string) {
super(
`Refusing to cache: invalid ${field}=${JSON.stringify(value).slice(0, 80)}`,
)
this.name = 'InvalidCacheKeyError'
}
}
function assertValidRepo(repo: string) {
if (
repo.length === 0 ||
repo.length > MAX_REPO_LEN ||
!REPO_PATTERN.test(repo)
) {
throw new InvalidCacheKeyError('repo', repo)
}
}
function assertValidGitRef(gitRef: string) {
if (
gitRef.length === 0 ||
gitRef.length > MAX_GIT_REF_LEN ||
!GIT_REF_PATTERN.test(gitRef) ||
gitRef.includes('..') ||
gitRef.startsWith('/') ||
gitRef.endsWith('/') ||
gitRef.includes('//')
) {
throw new InvalidCacheKeyError('gitRef', gitRef)
}
}
function assertValidContentPath(path: string) {
if (path === '' || SENTINEL_PATHS.has(path)) {
return
}
if (path.length > MAX_PATH_LEN) {
throw new InvalidCacheKeyError('path', path)
}
if (
path.startsWith('/') ||
path.endsWith('/') ||
path.includes('//') ||
path.includes('..')
) {
throw new InvalidCacheKeyError('path', path)
}
for (const segment of path.split('/')) {
if (!PATH_SEGMENT_PATTERN.test(segment)) {
throw new InvalidCacheKeyError('path', path)
}
}
}
function assertValidCacheKey(opts: {
gitRef: string
path: string
repo: string
}) {
assertValidRepo(opts.repo)
assertValidGitRef(opts.gitRef)
assertValidContentPath(opts.path)
}
const pendingRefreshes = new Map<string, Promise<unknown>>()
type CachedValue<T> = T | null | undefined
function withPendingRefresh<T>(key: string, fn: () => Promise<T>) {
const pending = pendingRefreshes.get(key)
if (pending) {
return pending as Promise<T>
}
const promise = fn().finally(() => {
pendingRefreshes.delete(key)
})
pendingRefreshes.set(key, promise)
return promise
}
function createFreshnessWindow(isPresent: boolean) {
const now = Date.now()
const staleFor = isPresent ? POSITIVE_STALE_MS : NEGATIVE_STALE_MS
return {
staleAt: new Date(now + staleFor),
}
}
function isFresh(staleAt: Date) {
return staleAt.getTime() > Date.now()
}
// markGitHubContentStale / markDocsArtifactsStale set staleAt to the epoch
// (new Date(0)) as a sentinel for "forcibly invalidated" — an admin clicked
// the purge button or a push webhook fired. Natural TTL expiry and forced
// invalidation both refresh synchronously now. The row stays around so the
// bottom of getCachedGitHubContent / getCachedDocsArtifact can still fall back
// to it if GitHub is unreachable.
function isForciblyStale(staleAt: Date) {
return staleAt.getTime() <= 0
}
function readStoredTextValue(row: GithubContentCache | undefined) {
if (!row) {
return undefined
}
if (!row.isPresent) {
return null
}
return typeof row.textContent === 'string' ? row.textContent : undefined
}
function readStoredJsonValue<T>(
row: GithubContentCache | undefined,
isValue: (value: unknown) => value is T,
) {
if (!row) {
return undefined
}
if (!row.isPresent) {
return null
}
return isValue(row.jsonContent) ? row.jsonContent : undefined
}
async function findGithubContentRow(opts: {
contentKind: 'dir' | 'file'
gitRef: string
path: string
repo: string
}) {
return db.query.githubContentCache.findFirst({
where: and(
eq(githubContentCache.repo, opts.repo),
eq(githubContentCache.gitRef, opts.gitRef),
eq(githubContentCache.contentKind, opts.contentKind),
eq(githubContentCache.path, opts.path),
),
})
}
async function upsertGithubContent(opts: {
contentKind: 'dir' | 'file'
gitRef: string
path: string
repo: string
value: string | unknown | null
}) {
const now = new Date()
const isPresent = opts.value !== null
const freshness = createFreshnessWindow(isPresent)
await db
.insert(githubContentCache)
.values({
repo: opts.repo,
gitRef: opts.gitRef,
contentKind: opts.contentKind,
path: opts.path,
isPresent,
textContent:
opts.contentKind === 'file' && typeof opts.value === 'string'
? opts.value
: null,
jsonContent: opts.contentKind === 'dir' ? opts.value : null,
staleAt: freshness.staleAt,
updatedAt: now,
})
.onConflictDoUpdate({
target: [
githubContentCache.repo,
githubContentCache.gitRef,
githubContentCache.contentKind,
githubContentCache.path,
],
set: {
isPresent,
textContent:
opts.contentKind === 'file' && typeof opts.value === 'string'
? opts.value
: null,
jsonContent: opts.contentKind === 'dir' ? opts.value : null,
staleAt: freshness.staleAt,
updatedAt: now,
},
})
}
async function getCachedGitHubContent<T>(opts: {
cacheKey: string
contentKind: 'dir' | 'file'
gitRef: string
origin: () => Promise<T | null>
path: string
readStoredValue: (row: GithubContentCache | undefined) => CachedValue<T>
repo: string
}) {
assertValidCacheKey(opts)
const readRow = () =>
findGithubContentRow({
repo: opts.repo,
gitRef: opts.gitRef,
contentKind: opts.contentKind,
path: opts.path,
})
const persist = (value: T | null) =>
upsertGithubContent({
repo: opts.repo,
gitRef: opts.gitRef,
contentKind: opts.contentKind,
path: opts.path,
value,
})
const cachedRow = await readRow()
const storedValue = opts.readStoredValue(cachedRow)
const forciblyStale = !!cachedRow && isForciblyStale(cachedRow.staleAt)
if (storedValue !== undefined && !forciblyStale) {
if (cachedRow && isFresh(cachedRow.staleAt)) {
return storedValue
}
}
return withPendingRefresh(opts.cacheKey, async () => {
const latestRow = await readRow()
const latestValue = opts.readStoredValue(latestRow)
const latestForciblyStale =
!!latestRow && isForciblyStale(latestRow.staleAt)
if (
latestValue !== undefined &&
latestRow &&
!latestForciblyStale &&
isFresh(latestRow.staleAt)
) {
return latestValue
}
try {
const value = await opts.origin()
await persist(value)
return value
} catch (error) {
if (latestValue !== undefined && latestValue !== null) {
console.warn(`[GitHub Cache] Serving stale value ${opts.cacheKey}`)
return latestValue
}
throw error
}
})
}
async function upsertDocsArtifact(opts: {
artifactKey: string
artifactType: string
docsRoot: string
gitRef: string
payload: unknown
repo: string
}) {
const now = new Date()
const freshness = createFreshnessWindow(true)
await db
.insert(docsArtifactCache)
.values({
repo: opts.repo,
gitRef: opts.gitRef,
docsRoot: opts.docsRoot,
artifactType: opts.artifactType,
artifactKey: opts.artifactKey,
payload: opts.payload,
staleAt: freshness.staleAt,
updatedAt: now,
})
.onConflictDoUpdate({
target: [
docsArtifactCache.repo,
docsArtifactCache.gitRef,
docsArtifactCache.docsRoot,
docsArtifactCache.artifactType,
docsArtifactCache.artifactKey,
],
set: {
payload: opts.payload,
staleAt: freshness.staleAt,
updatedAt: now,
},
})
}
export async function getCachedGitHubTextFile(opts: {
gitRef: string
origin: () => Promise<string | null>
path: string
repo: string
}) {
return getCachedGitHubContent({
...opts,
cacheKey: `github:file:${opts.repo}:${opts.gitRef}:${opts.path}`,
contentKind: 'file',
readStoredValue: readStoredTextValue,
})
}
export async function getCachedGitHubJsonContent<T>(opts: {
gitRef: string
isValue: (value: unknown) => value is T
origin: () => Promise<T | null>
path: string
repo: string
}) {
return getCachedGitHubContent({
...opts,
cacheKey: `github:dir:${opts.repo}:${opts.gitRef}:${opts.path}`,
contentKind: 'dir',
readStoredValue: (row) => readStoredJsonValue(row, opts.isValue),
})
}
export async function getCachedDocsArtifact<T>(opts: {
artifactKey: string
artifactType: string
build: () => Promise<T>
docsRoot: string
gitRef: string
isValue: (value: unknown) => value is T
repo: string
}) {
assertValidRepo(opts.repo)
assertValidGitRef(opts.gitRef)
assertValidContentPath(opts.docsRoot)
const cacheKey = `docs-artifact:${opts.repo}:${opts.gitRef}:${opts.docsRoot}:${opts.artifactType}:${opts.artifactKey}`
const readRow = () =>
db.query.docsArtifactCache.findFirst({
where: and(
eq(docsArtifactCache.repo, opts.repo),
eq(docsArtifactCache.gitRef, opts.gitRef),
eq(docsArtifactCache.docsRoot, opts.docsRoot),
eq(docsArtifactCache.artifactType, opts.artifactType),
eq(docsArtifactCache.artifactKey, opts.artifactKey),
),
})
const cachedRow = await readRow()
const storedValue =
cachedRow && opts.isValue(cachedRow.payload) ? cachedRow.payload : undefined
const forciblyStale = !!cachedRow && isForciblyStale(cachedRow.staleAt)
if (storedValue !== undefined && !forciblyStale) {
if (cachedRow && isFresh(cachedRow.staleAt)) {
return storedValue
}
}
return withPendingRefresh(cacheKey, async () => {
const latestRow = await readRow()
const latestValue =
latestRow && opts.isValue(latestRow.payload)
? latestRow.payload
: undefined
const latestForciblyStale =
!!latestRow && isForciblyStale(latestRow.staleAt)
if (
latestValue !== undefined &&
latestRow &&
!latestForciblyStale &&
isFresh(latestRow.staleAt)
) {
return latestValue
}
try {
const payload = await opts.build()
await upsertDocsArtifact({ ...opts, payload })
return payload
} catch (error) {
if (latestValue !== undefined) {
console.warn(`[GitHub Cache] Serving stale artifact ${cacheKey}`)
return latestValue
}
throw error
}
})
}
const DEFAULT_PRUNE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
// Negative cache rows (404s) only need to live long enough to absorb a
// short burst of repeated requests for a missing path. After that they're
// pure bloat — every scraper, broken backlink, and probe leaves a row.
const DEFAULT_NEGATIVE_PRUNE_MAX_AGE_MS = 24 * 60 * 60 * 1000
export async function pruneStaleCacheRows(
opts: {
maxAgeMs?: number
negativeMaxAgeMs?: number
} = {},
) {
const maxAgeMs = opts.maxAgeMs ?? DEFAULT_PRUNE_MAX_AGE_MS
const negativeMaxAgeMs =
opts.negativeMaxAgeMs ?? DEFAULT_NEGATIVE_PRUNE_MAX_AGE_MS
const cutoff = new Date(Date.now() - maxAgeMs)
const negativeCutoff = new Date(Date.now() - negativeMaxAgeMs)
const [contentByAge, contentNegatives, artifactDeleted] = await Promise.all([
db
.delete(githubContentCache)
.where(lt(githubContentCache.updatedAt, cutoff))
.returning({ id: githubContentCache.id }),
db
.delete(githubContentCache)
.where(
and(
eq(githubContentCache.isPresent, false),
lt(githubContentCache.updatedAt, negativeCutoff),
),
)
.returning({ id: githubContentCache.id }),
db
.delete(docsArtifactCache)
.where(lt(docsArtifactCache.updatedAt, cutoff))
.returning({ id: docsArtifactCache.id }),
])
return {
cutoff,
negativeCutoff,
githubContentDeleted: contentByAge.length + contentNegatives.length,
githubContentNegativesDeleted: contentNegatives.length,
docsArtifactDeleted: artifactDeleted.length,
}
}
export async function markGitHubContentStale(
opts: {
gitRef?: string
repo?: string
} = {},
) {
const whereConditions = []
if (opts.repo) {
whereConditions.push(eq(githubContentCache.repo, opts.repo))
}
if (opts.gitRef) {
whereConditions.push(eq(githubContentCache.gitRef, opts.gitRef))
}
const whereClause =
whereConditions.length > 0 ? and(...whereConditions) : undefined
const [countRow] = whereClause
? await db
.select({ count: sql<number>`count(*)::int` })
.from(githubContentCache)
.where(whereClause)
: await db
.select({ count: sql<number>`count(*)::int` })
.from(githubContentCache)
const rowCount = countRow?.count ?? 0
if (rowCount === 0) {
return 0
}
// Only set staleAt — do NOT bump updatedAt. updatedAt tracks last
// upsert (i.e. last access/refresh) and is the signal our GC uses to
// decide what to prune. Bumping it here would mask every cached row
// as "freshly used" on every webhook invalidation.
const updateData = {
staleAt: new Date(0),
}
if (whereClause) {
await db.update(githubContentCache).set(updateData).where(whereClause)
} else {
await db.update(githubContentCache).set(updateData)
}
return rowCount
}
export async function markDocsArtifactsStale(
opts: {
gitRef?: string
repo?: string
} = {},
) {
const whereConditions = []
if (opts.repo) {
whereConditions.push(eq(docsArtifactCache.repo, opts.repo))
}
if (opts.gitRef) {
whereConditions.push(eq(docsArtifactCache.gitRef, opts.gitRef))
}
const whereClause =
whereConditions.length > 0 ? and(...whereConditions) : undefined
const [countRow] = whereClause
? await db
.select({ count: sql<number>`count(*)::int` })
.from(docsArtifactCache)
.where(whereClause)
: await db
.select({ count: sql<number>`count(*)::int` })
.from(docsArtifactCache)
const rowCount = countRow?.count ?? 0
if (rowCount === 0) {
return 0
}
// Only set staleAt — do NOT bump updatedAt. updatedAt tracks last
// upsert (i.e. last access/refresh) and is the signal our GC uses to
// decide what to prune. Bumping it here would mask every cached row
// as "freshly used" on every webhook invalidation.
const updateData = {
staleAt: new Date(0),
}
if (whereClause) {
await db.update(docsArtifactCache).set(updateData).where(whereClause)
} else {
await db.update(docsArtifactCache).set(updateData)
}
return rowCount
}