Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2024-03-24 - Database Roundtrip Optimization in Serverless Environments
**Learning:** In Cloudflare D1 and similar serverless SQL databases, sequential `db.prepare(...).first()` calls create a severe N+1 latency bottleneck because each statement requires a discrete HTTP request over the network.
**Action:** Always combine sequential, unrelated scalar queries into a single `db.batch()` request. For aggregate stats, use conditional aggregation (`SUM(CASE WHEN...)`) to gather multiple metrics in a single table scan inside that batch.
## 2024-07-24 - Admin Stats Concurrent DB Queries
**Learning:** Sequential, independent database queries inside Cloudflare D1 edge functions (like `db.prepare().first()`) can cause unnecessary N+1 network latency delays on dashboard routes.
**Action:** When multiple independent stats or metrics need to be fetched, group them into a single `Promise.all([db.prepare().first().catch(...)])` block to execute concurrently, ensuring to maintain individual `.catch` handlers so one failure doesn't crash the entire batch.
81 changes: 40 additions & 41 deletions src/app/api/admin/[[...slug]]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,56 +201,55 @@ export async function GET(request: Request, context: { params: Promise<{ slug?:
let forwardCount = 0;

if (db) {
try {
const fileStats: any = await db.prepare(`
// Bolt: Execute queries concurrently to eliminate N+1 network latency
await Promise.all([
db.prepare(`
SELECT COUNT(*) as total_files, COALESCE(SUM(file_size), 0) as total_bytes
FROM vault_files
`).first();
if (fileStats) {
fileCount = Number(fileStats.total_files || 0);
totalCapacity = Number(fileStats.total_bytes || 0);
}
} catch (e: any) {
logger.error("ADMIN_STATS: Failed to query vault_files.", e.message);
}

try {
const emailStats: any = await db.prepare(`
`).first()
.then((fileStats: any) => {
if (fileStats) {
fileCount = Number(fileStats.total_files || 0);
totalCapacity = Number(fileStats.total_bytes || 0);
}
})
.catch((e: any) => logger.error("ADMIN_STATS: Failed to query vault_files.", e.message)),

db.prepare(`
SELECT COUNT(*) as total_aliases, COALESCE(SUM(forward_count), 0) as total_forwards
FROM relay_aliases
`).first();
if (emailStats) {
aliasCount = Number(emailStats.total_aliases || 0);
forwardCount = Number(emailStats.total_forwards || 0);
}
} catch (e: any) {
logger.error("ADMIN_STATS: Failed to query relay_aliases.", e.message);
}

try {
const userStats: any = await db.prepare(`
`).first()
.then((emailStats: any) => {
if (emailStats) {
aliasCount = Number(emailStats.total_aliases || 0);
forwardCount = Number(emailStats.total_forwards || 0);
}
})
.catch((e: any) => logger.error("ADMIN_STATS: Failed to query relay_aliases.", e.message)),

db.prepare(`
SELECT COUNT(DISTINCT user_id) as total_users
FROM vault_users
`).first();
if (userStats) {
userCount = Number(userStats.total_users || 0);
}
} catch (e: any) {
logger.error("ADMIN_STATS: Failed to query vault_users.", e.message);
}

try {
const secretStats: any = await db.prepare(`
`).first()
.then((userStats: any) => {
if (userStats) {
userCount = Number(userStats.total_users || 0);
}
})
.catch((e: any) => logger.error("ADMIN_STATS: Failed to query vault_users.", e.message)),

db.prepare(`
SELECT COUNT(*) as active_secrets
FROM stealth_secrets
WHERE is_viewed = 0 AND expires_at > datetime('now')
`).first();
if (secretStats) {
secretCount = Number(secretStats.active_secrets || 0);
}
} catch (e: any) {
logger.error("ADMIN_STATS: Failed to query stealth_secrets.", e.message);
}
`).first()
.then((secretStats: any) => {
if (secretStats) {
secretCount = Number(secretStats.active_secrets || 0);
}
})
.catch((e: any) => logger.error("ADMIN_STATS: Failed to query stealth_secrets.", e.message))
]);
}

return NextResponse.json({
Expand Down