diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index 63cdef6..70b4057 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -79,26 +79,33 @@ app.use('*', async (c, next) => { if (path === '/health' || path.startsWith('/ui')) return try { + const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000 + const cutoff = Date.now() - SEVEN_DAYS_MS c.executionCtx.waitUntil( - 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(), + Promise.all([ + c.env.DB.prepare( + 'INSERT INTO request_logs (method, path, api_key_id, api_key_name, status_code, error, duration_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', ) - .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 { // executionCtx not available in test, skip