-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathgithub-content-cache.server.ts
More file actions
450 lines (388 loc) · 10.8 KB
/
github-content-cache.server.ts
File metadata and controls
450 lines (388 loc) · 10.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
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 = 24 * 60 * 60 * 1000
const NEGATIVE_STALE_MS = 15 * 60 * 1000
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()
}
function queueRefresh(key: string, fn: () => Promise<unknown>) {
void withPendingRefresh(key, fn).catch((error) => {
console.error(`[GitHub Cache] Failed to refresh ${key}:`, error)
})
}
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
}) {
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)
if (storedValue !== undefined) {
if (cachedRow && isFresh(cachedRow.staleAt)) {
return storedValue
}
if (storedValue !== null) {
queueRefresh(opts.cacheKey, async () => {
const value = await opts.origin()
await persist(value)
})
return storedValue
}
}
return withPendingRefresh(opts.cacheKey, async () => {
const latestRow = await readRow()
const latestValue = opts.readStoredValue(latestRow)
if (latestValue !== undefined && latestRow && 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
}) {
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
if (storedValue !== undefined) {
if (cachedRow && isFresh(cachedRow.staleAt)) {
return storedValue
}
queueRefresh(cacheKey, async () => {
const payload = await opts.build()
await upsertDocsArtifact({ ...opts, payload })
})
return storedValue
}
return withPendingRefresh(cacheKey, async () => {
const latestRow = await readRow()
const latestValue =
latestRow && opts.isValue(latestRow.payload)
? latestRow.payload
: undefined
if (latestValue !== undefined && latestRow && 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
}
})
}
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
}
const updateData = {
staleAt: new Date(0),
updatedAt: new Date(),
}
if (whereClause) {
await db.update(githubContentCache).set(updateData).where(whereClause)
} else {
await db.update(githubContentCache).set(updateData)
}
return rowCount
}
export async function pruneOldCacheEntries(olderThanMs: number) {
const threshold = new Date(Date.now() - olderThanMs)
const [contentDeleted, artifactDeleted] = await Promise.all([
db
.delete(githubContentCache)
.where(lt(githubContentCache.updatedAt, threshold))
.returning({ repo: githubContentCache.repo }),
db
.delete(docsArtifactCache)
.where(lt(docsArtifactCache.updatedAt, threshold))
.returning({ repo: docsArtifactCache.repo }),
])
return {
contentDeleted: contentDeleted.length,
artifactDeleted: artifactDeleted.length,
threshold,
}
}
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
}
const updateData = {
staleAt: new Date(0),
updatedAt: new Date(),
}
if (whereClause) {
await db.update(docsArtifactCache).set(updateData).where(whereClause)
} else {
await db.update(docsArtifactCache).set(updateData)
}
return rowCount
}