God Mode Valhalla: Initial Standalone Commit

This commit is contained in:
cawcenter
2025-12-14 19:19:14 -05:00
commit 153102b23e
127 changed files with 30781 additions and 0 deletions

55
src/lib/db/mechanic.ts Normal file
View File

@@ -0,0 +1,55 @@
import { query } from '../db';
export const MECHANIC_OPS = {
// 1. DIAGNOSTICS (The Stethoscope)
getHealth: async () => {
const connections = await query(`
SELECT count(*)::int as active, state
FROM pg_stat_activity
GROUP BY state;
`);
const size = await query(`
SELECT pg_size_pretty(pg_database_size(current_database())) as size;
`);
// Note: pg_statio_user_tables requires stats collection to be enabled (default on)
const cache = await query(`
SELECT
sum(heap_blks_read) as disk_read,
sum(heap_blks_hit) as mem_hit,
sum(heap_blks_hit) / NULLIF((sum(heap_blks_hit) + sum(heap_blks_read)), 0)::float as ratio
FROM pg_statio_user_tables;
`);
return {
connections: connections.rows,
size: size.rows[0]?.size || 'Unknown',
cache: cache.rows[0] || { ratio: 0 }
};
},
// 2. THE "RED BUTTON" COMMANDS (Fix It)
maintenance: {
vacuum: async () => {
// Cleans up dead rows and optimizes speed
await query('VACUUM (VERBOSE, ANALYZE);');
return "Vacuum Complete: DB optimized.";
},
reindex: async () => {
// Fixes corrupted or slow indexes
await query('REINDEX DATABASE directus;');
return "Reindex Complete: Indexes rebuilt.";
},
kill_locks: async () => {
// Kills any query running longer than 5 minutes
const res = await query(`
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'active'
AND (now() - query_start) > interval '5 minutes';
`);
return `Panic Protocol: Terminated ${res.rowCount} stuck processes.`;
}
}
};