-
Notifications
You must be signed in to change notification settings - Fork 255
feat: cache eviction strategy #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import * as fs from 'node:fs/promises' | ||
import * as path from 'node:path' | ||
import { exec } from 'node:child_process' | ||
import { promisify } from 'node:util' | ||
import { env } from './env.js' | ||
const execAsync = promisify(exec) | ||
|
||
async function deleteOldFolders() { | ||
const now = Date.now() | ||
const ttlInMillis = env.CACHE_TTL * 60 * 60 * 1000 | ||
|
||
try { | ||
const folders = await fs.readdir(env.CACHE_PATH) | ||
for (const folder of folders) { | ||
const folderPath = path.join(env.CACHE_PATH, folder) | ||
const stats = await fs.stat(folderPath) | ||
|
||
if (stats.isDirectory() && now - stats.mtimeMs > ttlInMillis) { | ||
await fs.rm(folderPath, { recursive: true, force: true }) | ||
console.log(`Deleted folder: ${folderPath}`) | ||
} | ||
} | ||
} catch (err) { | ||
console.error('Failed to delete old folders:', err) | ||
} | ||
} | ||
|
||
async function scriptAlreadyRan() { | ||
try { | ||
const lastRun = parseInt(await fs.readFile(env.CACHE_TIMESTAMP_FILE, 'utf8')) | ||
const now = Math.floor(Date.now() / 1000) | ||
const diff = now - lastRun | ||
return diff < env.CACHE_SCHEDULE_INTERVAL * 60 * 60 * 1000 | ||
} catch (err) { | ||
// File does not exist | ||
if (err instanceof Error && 'code' in err && err.code === 'ENOENT') { | ||
return false | ||
} | ||
throw err | ||
} | ||
} | ||
|
||
async function updateTimestampFile() { | ||
const now = Math.floor(Date.now() / 1000).toString() | ||
await fs.writeFile(env.CACHE_TIMESTAMP_FILE, now) | ||
} | ||
|
||
/** | ||
* Get the disk usage of the root directory | ||
*/ | ||
async function getDiskUsage() { | ||
// awk 'NR==2 {print $5}' prints the 5th column of the df command which contains the percentage of the total disk space used | ||
// sed 's/%//' removes the % from the output | ||
const command = `df / | awk 'NR==2 {print $5}' | sed 's/%//'` | ||
const { stdout } = await execAsync(command) | ||
return parseInt(stdout.trim(), 10) | ||
} | ||
|
||
async function getFoldersByModificationTime() { | ||
const folders = await fs.readdir(env.CACHE_PATH, { withFileTypes: true }) | ||
const folderStats = await Promise.all( | ||
folders | ||
.filter((dirent) => dirent.isDirectory()) | ||
.map(async (dirent) => { | ||
const fullPath = path.join(env.CACHE_PATH, dirent.name) | ||
const stats = await fs.stat(fullPath) | ||
return { path: fullPath, mtime: stats.mtime.getTime() } | ||
}) | ||
) | ||
return folderStats.sort((a, b) => a.mtime - b.mtime).map((folder) => folder.path) | ||
} | ||
|
||
export async function deleteCache() { | ||
if (await scriptAlreadyRan()) { | ||
console.log(`Script already ran in the last ${env.CACHE_SCHEDULE_INTERVAL} hours, skipping.`) | ||
return | ||
} | ||
|
||
await updateTimestampFile() | ||
|
||
// Always delete old folders based on TTL | ||
await deleteOldFolders() | ||
|
||
let diskUsage = await getDiskUsage() | ||
|
||
// If disk usage exceeds the threshold, delete additional old folders | ||
if (diskUsage >= env.CACHE_DISK_USAGE_THRESHOLD) { | ||
console.log( | ||
`Disk usage is at ${diskUsage}%, which is above the threshold of ${env.CACHE_DISK_USAGE_THRESHOLD}%.` | ||
) | ||
|
||
const folders = await getFoldersByModificationTime() | ||
|
||
// Loop through the folders and delete them one by one until disk usage is below the threshold | ||
for (const folder of folders) { | ||
console.log(`Deleting folder: ${folder}`) | ||
await fs.rm(folder, { recursive: true, force: true }) | ||
|
||
diskUsage = await getDiskUsage() | ||
if (diskUsage < env.CACHE_DISK_USAGE_THRESHOLD) { | ||
console.log(`Disk usage is now at ${diskUsage}%, which is below the threshold.`) | ||
break | ||
} | ||
} | ||
} else { | ||
console.log( | ||
`Disk usage is at ${diskUsage}%, which is below the threshold of ${env.CACHE_DISK_USAGE_THRESHOLD}%.` | ||
) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { z } from 'zod' | ||
|
||
export const env = z | ||
.object({ | ||
AWS_ACCESS_KEY_ID: z.string(), | ||
AWS_ENDPOINT_URL_S3: z.string(), | ||
AWS_S3_BUCKET: z.string(), | ||
AWS_SECRET_ACCESS_KEY: z.string(), | ||
AWS_REGION: z.string(), | ||
CACHE_DISK_USAGE_THRESHOLD: z.string().transform((val) => parseInt(val, 10)), | ||
CACHE_PATH: z.string(), | ||
CACHE_SCHEDULE_INTERVAL: z.string().transform((val) => parseInt(val, 10)), | ||
CACHE_TIMESTAMP_FILE: z.string(), | ||
CACHE_TTL: z.string().transform((val) => parseInt(val, 10)), | ||
DATA_MOUNT: z.string(), | ||
S3FS_MOUNT: z.string(), | ||
SUPABASE_SERVICE_ROLE_KEY: z.string(), | ||
SUPABASE_URL: z.string(), | ||
WILDCARD_DOMAIN: z.string(), | ||
}) | ||
.parse(process.env) | ||
jgoux marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.