-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.ts
71 lines (63 loc) · 1.98 KB
/
cache.ts
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
import { cron } from "https://deno.land/x/[email protected]/cron.ts"
export async function cacheHandler() {
try {
await Deno.stat("cache")
}
catch (_error) {
console.log("Cache not found, generating...")
await Deno.mkdir("cache")
}
}
export async function checkCache(inputHashName:string, pageValue:string): Promise<Uint8Array | false> {
try {
return await Deno.readFile(`./cache/${inputHashName}-${pageValue}.jpg`)
}
catch {
return Promise.resolve(false)
}
}
export function cacheSizeController() {
async function checkCacheSize() {
let returnCacheSize = 0
const itemNames = []
let cacheCount = 0
for await (const dirEntry of Deno.readDir("./cache/")) {
itemNames[cacheCount] = dirEntry.name
cacheCount ++
}
const accessTimeArray = []
for (let i = 0; i < cacheCount; i++) {
const { size, atime } = await Deno.stat(`./cache/${itemNames[i]}`)
returnCacheSize += size
accessTimeArray[i] = atime
}
return {
returnCacheSize, cacheCount, itemNames, accessTimeArray
}
}
async function limitCache(){
const cacheLimit = Number(Deno.env.get("CACHE_SIZE")) ?? 100000000
const { returnCacheSize } = await checkCacheSize()
let cacheSize = returnCacheSize
while (cacheSize > cacheLimit){
const { cacheCount, itemNames, accessTimeArray } = await checkCacheSize()
let oldestAccess = accessTimeArray[0]
let arrayPosition = 0
for (let i = 0; i < cacheCount; i++) {
if (oldestAccess! > accessTimeArray[i]!){
oldestAccess = accessTimeArray[i]
arrayPosition = i
}
}
await Deno.remove(`./cache/${itemNames[arrayPosition]}`)
const { returnCacheSize } = await checkCacheSize()
cacheSize = returnCacheSize
}
console.log("Cache cleanup complete!")
}
const cronEnv = Deno.env.get("CRON_TIMING") ?? "*,*,*,*,*"
const cronTiming = cronEnv.replaceAll(',', ' ')
cron(cronTiming, () => {
limitCache()
})
}