feat: auto-cleanup logs older than 7 days

Request logs and reaction logs are automatically pruned on each request
via waitUntil. Zero-cost async cleanup, no cron needed.

小橘 🍊(NEKO Team)
This commit is contained in:
小橘 2026-04-13 08:57:19 +00:00
parent cc9f3eb88f
commit 8702e8b1c3

View File

@ -79,26 +79,33 @@ app.use('*', async (c, next) => {
if (path === '/health' || path.startsWith('/ui')) return if (path === '/health' || path.startsWith('/ui')) return
try { try {
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000
const cutoff = Date.now() - SEVEN_DAYS_MS
c.executionCtx.waitUntil( c.executionCtx.waitUntil(
c.env.DB.prepare( Promise.all([
'INSERT INTO request_logs (method, path, api_key_id, api_key_name, status_code, error, duration_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', c.env.DB.prepare(
) 'INSERT INTO request_logs (method, path, api_key_id, api_key_name, status_code, error, duration_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
.bind(
c.req.method,
path,
c.get('apiKeyId') || null,
c.get('apiKeyName') || null,
c.res.status,
c.res.status >= 400
? await c.res
.clone()
.text()
.catch(() => null)
: null,
duration,
Date.now(),
) )
.run(), .bind(
c.req.method,
path,
c.get('apiKeyId') || null,
c.get('apiKeyName') || null,
c.res.status,
c.res.status >= 400
? await c.res
.clone()
.text()
.catch(() => null)
: null,
duration,
Date.now(),
)
.run(),
// Cleanup logs older than 7 days
c.env.DB.prepare('DELETE FROM request_logs WHERE created_at < ?').bind(cutoff).run(),
c.env.DB.prepare('DELETE FROM reaction_logs WHERE created_at < ?').bind(cutoff).run(),
]),
) )
} catch { } catch {
// executionCtx not available in test, skip // executionCtx not available in test, skip