perf(metrics): send all seven queries in one D1 batch

Avoid seven sequential network round trips and read totals, breakdowns and recent failures in one consistent transaction. Reuse the failed-send statement and row mapping while retaining group scoping.
This commit is contained in:
翅膀 committed 2026-10-17 17:08:31 +08:00
1 parent 244b5c6ffe
commit 6cdcedde92
4 files changed
+86 -56

No files matched your search

+10
View File
@@ -50,6 +50,7 @@ function createMetricsDB(rowsBySql: Record<string, unknown[]>): D1Database {
}
return { results: [] };
};
let batches = 0;
return {
prepare: (sql: string) => ({
all: all(sql),
@@ -58,6 +59,13 @@ function createMetricsDB(rowsBySql: Record<string, unknown[]>): D1Database {
run: async () => ({ success: true }),
}),
}),
batch: async (statements: Array<{ all: () => Promise<unknown> }>) => {
batches++;
return Promise.all(statements.map((s) => s.all()));
},
get batches(): number {
return batches;
},
} as unknown as D1Database;
}
@@ -102,6 +110,8 @@ describe("delivery metrics", () => {
"COUNT(*) AS total": [{ total: 10, ok: 8 }],
});
const m = await getDeliveryMetrics(db);
// Every query goes out in a single batch (one D1 round trip).
expect((db as unknown as { batches: number }).batches).toBe(1);
expect(m.total).toBe(10);
expect(m.ok).toBe(8);
expect(m.failed).toBe(2);