Skip to content

Commit 8d6ddae

Browse files
authored
fix(配额): 批量统计改为单语句聚合,消除用户配额页无界并发打爆连接池准入 (#1511) (#1512)
- 带 costResetAt 的用户/Key 总消费由逐实体 Promise.all 单查改为 VALUES JOIN 一次聚合(按 1000 分片),保留 reset 与 maxAge cutoff 取较晚值、无效 reset 日期按无重置处理等原语义 - 用户配额页逐用户 getUserLimitUsage 改用 mapWithConcurrency 限并发 6 - 更新 statistics-reset-at 测试并新增多 reset 实体仅一条聚合语句的回归用例;生产只读对账新旧 SQL 结果逐分一致
1 parent 9604ee5 commit 8d6ddae

3 files changed

Lines changed: 180 additions & 37 deletions

File tree

‎src/app/[locale]/dashboard/quotas/users/page.tsx‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { QuotaToolbar } from "@/components/quota/quota-toolbar";
66
import { Alert, AlertDescription } from "@/components/ui/alert";
77
import { Link, redirect } from "@/i18n/routing";
88
import { getSession } from "@/lib/auth";
9+
import { mapWithConcurrency } from "@/lib/provider-balance/concurrency";
910
import { resolveKeyCostResetAt } from "@/lib/rate-limit/cost-reset-utils";
1011
import { sumKeyTotalCostBatchByIds, sumUserTotalCostBatch } from "@/repository/statistics";
1112
import { getSystemSettings } from "@/repository/system-config";
@@ -17,6 +18,11 @@ import { UsersQuotaClient } from "./_components/users-quota-client";
1718
// Force dynamic rendering (this page needs real-time data and auth)
1819
export const dynamic = "force-dynamic";
1920

21+
// Per-user limit usage still issues a few sequential queries per user, so cap
22+
// how many users are in flight at once. An unbounded Promise.all over all
23+
// users can exceed the database pool admission limit (issue #1511).
24+
const USER_QUOTA_QUERY_CONCURRENCY = 6;
25+
2026
async function getUsersWithQuotas(): Promise<UserQuotaWithUsage[]> {
2127
const collectedUsers: UserDisplay[] = [];
2228
const MAX_USERS_FOR_QUOTAS = 2000;
@@ -66,9 +72,10 @@ async function getUsersWithQuotas(): Promise<UserQuotaWithUsage[]> {
6672
}
6773
}
6874

69-
// 3 queries total instead of N+M individual SUM queries
75+
// Total costs are batched aggregations; per-user limit usage runs with
76+
// bounded concurrency instead of an N-way fan-out.
7077
const [quotaResults, userCostMap, keyCostMap] = await Promise.all([
71-
Promise.all(users.map((u) => getUserLimitUsage(u.id))),
78+
mapWithConcurrency(users, USER_QUOTA_QUERY_CONCURRENCY, (u) => getUserLimitUsage(u.id)),
7279
sumUserTotalCostBatch(
7380
allUserIds,
7481
Infinity,

‎src/repository/statistics.ts‎

Lines changed: 108 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,81 @@ export async function sumUserTotalCost(
559559
return Number(result[0]?.total || 0);
560560
}
561561

562+
function isValidResetAt(resetAt: Date | null | undefined): resetAt is Date {
563+
return resetAt instanceof Date && !Number.isNaN(resetAt.getTime());
564+
}
565+
566+
/**
567+
* Resolve the effective lower bound for a total-cost query: the later of the
568+
* max-age cutoff and a valid reset timestamp. Returns null for all-time.
569+
*/
570+
function resolveTotalCostCutoff(maxAgeDays: number, resetAt?: Date | null): Date | null {
571+
const maxAgeCutoff =
572+
Number.isFinite(maxAgeDays) && maxAgeDays > 0
573+
? new Date(Date.now() - Math.floor(maxAgeDays) * 24 * 60 * 60 * 1000)
574+
: null;
575+
if (isValidResetAt(resetAt)) {
576+
return maxAgeCutoff && maxAgeCutoff > resetAt ? maxAgeCutoff : resetAt;
577+
}
578+
return maxAgeCutoff;
579+
}
580+
581+
// Keep each VALUES-join statement well below the driver parameter limit.
582+
const TOTAL_COST_CUTOFF_CHUNK_SIZE = 1000;
583+
584+
interface TotalCostCutoffEntry {
585+
entityKey: number | string;
586+
cutoff: Date;
587+
}
588+
589+
/**
590+
* Total cost for entities that each carry their own cutoff, aggregated in a
591+
* single SQL statement (per chunk) instead of one query per entity.
592+
*
593+
* A per-entity Promise.all fan-out here can exceed the database pool
594+
* admission limit on fan-out pages such as the user quota list (issue #1511).
595+
* Returns Map of String(entityKey) -> totalCost. Duplicate entity keys keep
596+
* the last cutoff, matching the previous per-entity overwrite order.
597+
*/
598+
async function sumTotalCostWithCutoffs(
599+
entityType: "user" | "key",
600+
entries: readonly TotalCostCutoffEntry[]
601+
): Promise<Map<string, number>> {
602+
const totals = new Map<string, number>();
603+
const entityColumn = entityType === "user" ? usageLedger.userId : usageLedger.key;
604+
605+
const deduped = new Map<string, TotalCostCutoffEntry>();
606+
for (const entry of entries) {
607+
deduped.set(String(entry.entityKey), entry);
608+
}
609+
const uniqueEntries = [...deduped.values()];
610+
611+
for (let start = 0; start < uniqueEntries.length; start += TOTAL_COST_CUTOFF_CHUNK_SIZE) {
612+
const chunk = uniqueEntries.slice(start, start + TOTAL_COST_CUTOFF_CHUNK_SIZE);
613+
const valueRows = chunk.map((entry) =>
614+
entityType === "user"
615+
? sql`(${entry.entityKey as number}::int, ${entry.cutoff.toISOString()}::timestamptz)`
616+
: sql`(${entry.entityKey as string}::text, ${entry.cutoff.toISOString()}::timestamptz)`
617+
);
618+
619+
const rows = await db.execute(sql`
620+
SELECT c.entity_id AS entity_id, COALESCE(SUM(${usageLedger.costUsd}), 0) AS total
621+
FROM (VALUES ${sql.join(valueRows, sql`, `)}) AS c(entity_id, cutoff)
622+
LEFT JOIN ${usageLedger}
623+
ON ${entityColumn} = c.entity_id
624+
AND ${usageLedger.createdAt} >= c.cutoff
625+
AND ${LEDGER_BILLING_CONDITION}
626+
GROUP BY c.entity_id
627+
`);
628+
629+
for (const row of Array.from(rows) as Array<{ entity_id: unknown; total: unknown }>) {
630+
totals.set(String(row.entity_id), Number(row.total || 0));
631+
}
632+
}
633+
634+
return totals;
635+
}
636+
562637
/**
563638
* Batch query: total cost grouped by user_id (single SQL query)
564639
* @param userIds - Array of user IDs
@@ -574,26 +649,29 @@ export async function sumUserTotalCostBatch(
574649
if (userIds.length === 0) return result;
575650
for (const id of userIds) result.set(id, 0);
576651

577-
// Split users: those with costResetAt need individual queries
578-
const resetUserIds: number[] = [];
652+
// Split users: those with a valid costResetAt carry their own cutoff and
653+
// are aggregated in a single statement. An invalid reset date behaves
654+
// like no reset, matching sumUserTotalCost.
655+
const resetEntries: Array<{ id: number; cutoff: Date }> = [];
579656
const batchUserIds: number[] = [];
580657
for (const id of userIds) {
581-
if (resetAtMap?.has(id)) {
582-
resetUserIds.push(id);
658+
const resetAt = resetAtMap?.get(id);
659+
if (isValidResetAt(resetAt)) {
660+
// A valid reset always yields a cutoff (at least the reset itself).
661+
resetEntries.push({ id, cutoff: resolveTotalCostCutoff(maxAgeDays, resetAt) as Date });
583662
} else {
584663
batchUserIds.push(id);
585664
}
586665
}
587666

588-
// Individual queries for users with costResetAt
589-
if (resetUserIds.length > 0) {
590-
const resetResults = await Promise.all(
591-
resetUserIds.map(async (id) => ({
592-
id,
593-
total: await sumUserTotalCost(id, maxAgeDays, resetAtMap!.get(id)),
594-
}))
667+
if (resetEntries.length > 0) {
668+
const resetTotals = await sumTotalCostWithCutoffs(
669+
"user",
670+
resetEntries.map(({ id, cutoff }) => ({ entityKey: id, cutoff }))
595671
);
596-
for (const { id, total } of resetResults) result.set(id, total);
672+
for (const { id } of resetEntries) {
673+
result.set(id, resetTotals.get(String(id)) ?? 0);
674+
}
597675
}
598676

599677
// Batch query for users without costResetAt
@@ -643,34 +721,35 @@ export async function sumKeyTotalCostBatchByIds(
643721
.where(inArray(keys.id, keyIds));
644722

645723
const keyStringToId = new Map(keyMappings.map((k) => [k.key, k.id]));
646-
const idToKeyString = new Map(keyMappings.map((k) => [k.id, k.key]));
647724
const keyStrings = keyMappings.map((k) => k.key);
648725
if (keyStrings.length === 0) return result;
649726

650-
// Split keys: those with costResetAt need individual queries
651-
const resetKeyIds: number[] = [];
727+
// Split keys: those with a valid costResetAt carry their own cutoff and
728+
// are aggregated in a single statement. An invalid reset date behaves
729+
// like no reset, matching sumKeyTotalCost.
730+
const resetEntries: Array<{ id: number; keyString: string; cutoff: Date }> = [];
652731
const batchKeyStrings: string[] = [];
653732
for (const mapping of keyMappings) {
654-
if (resetAtMap?.has(mapping.id)) {
655-
resetKeyIds.push(mapping.id);
733+
const resetAt = resetAtMap?.get(mapping.id);
734+
if (isValidResetAt(resetAt)) {
735+
resetEntries.push({
736+
id: mapping.id,
737+
keyString: mapping.key,
738+
cutoff: resolveTotalCostCutoff(maxAgeDays, resetAt) as Date,
739+
});
656740
} else {
657741
batchKeyStrings.push(mapping.key);
658742
}
659743
}
660744

661-
// Individual queries for keys with costResetAt
662-
if (resetKeyIds.length > 0) {
663-
const resetResults = await Promise.all(
664-
resetKeyIds.map(async (id) => {
665-
const keyString = idToKeyString.get(id);
666-
if (!keyString) return { id, total: 0 };
667-
return {
668-
id,
669-
total: await sumKeyTotalCost(keyString, maxAgeDays, resetAtMap!.get(id)),
670-
};
671-
})
745+
if (resetEntries.length > 0) {
746+
const resetTotals = await sumTotalCostWithCutoffs(
747+
"key",
748+
resetEntries.map(({ keyString, cutoff }) => ({ entityKey: keyString, cutoff }))
672749
);
673-
for (const { id, total } of resetResults) result.set(id, total);
750+
for (const { id, keyString } of resetEntries) {
751+
result.set(id, resetTotals.get(keyString) ?? 0);
752+
}
674753
}
675754

676755
// Step 2: Batch aggregate for keys without costResetAt

‎tests/unit/repository/statistics-reset-at.test.ts‎

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,16 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
33
// dbResultMock controls what every DB chain resolves to when awaited
44
const dbResultMock = vi.fn<[], unknown>().mockReturnValue([{ total: 0 }]);
55

6+
// db.execute (raw SQL) resolves from the same programmable result queue
7+
const dbExecuteMock = vi.fn(async () => dbResultMock());
8+
69
// Build a chainable mock that resolves to dbResultMock() on await
710
function chain(): Record<string, unknown> {
811
const obj: Record<string, unknown> = {};
912
for (const method of ["select", "from", "where", "groupBy", "limit"]) {
1013
obj[method] = vi.fn(() => chain());
1114
}
15+
obj.execute = dbExecuteMock;
1216
// Make it thenable so `await db.select().from().where()` works
1317
// biome-ignore lint/suspicious/noThenProperty: thenable mock for drizzle query chain
1418
obj.then = (resolve: (v: unknown) => void, reject: (e: unknown) => void) => {
@@ -110,19 +114,54 @@ describe("statistics resetAt parameter", () => {
110114
});
111115

112116
describe("sumUserTotalCostBatch", () => {
113-
test("with resetAtMap -- splits users: individual queries for reset users", async () => {
117+
test("with resetAtMap -- aggregates reset users in one statement, batch for the rest", async () => {
114118
const resetAtMap = new Map([[10, new Date("2026-02-15T00:00:00Z")]]);
115-
// Calls: 1) individual sumUserTotalCost(10) => where => [{ total: 25 }]
119+
// Calls: 1) VALUES-join aggregation for reset user 10 (db.execute)
116120
// 2) batch for user 20 => groupBy => [{ userId: 20, total: 50 }]
117121
dbResultMock
118-
.mockReturnValueOnce([{ total: 25.0 }])
122+
.mockReturnValueOnce([{ entity_id: 10, total: 25.0 }])
119123
.mockReturnValueOnce([{ userId: 20, total: 50.0 }]);
120124

121125
const { sumUserTotalCostBatch } = await import("@/repository/statistics");
122126
const result = await sumUserTotalCostBatch([10, 20], 365, resetAtMap);
123127

124128
expect(result.get(10)).toBe(25.0);
125129
expect(result.get(20)).toBe(50.0);
130+
expect(dbExecuteMock).toHaveBeenCalledTimes(1);
131+
});
132+
133+
test("many reset users -- still a single aggregation statement (regression #1511)", async () => {
134+
const userIds = Array.from({ length: 50 }, (_, i) => i + 1);
135+
const resetAtMap = new Map(userIds.map((id) => [id, new Date("2026-02-15T00:00:00Z")]));
136+
dbResultMock.mockReturnValue(userIds.map((id) => ({ entity_id: id, total: id })));
137+
138+
const { sumUserTotalCostBatch } = await import("@/repository/statistics");
139+
const result = await sumUserTotalCostBatch(userIds, Infinity, resetAtMap);
140+
141+
expect(dbExecuteMock).toHaveBeenCalledTimes(1);
142+
expect(result.get(1)).toBe(1);
143+
expect(result.get(50)).toBe(50);
144+
});
145+
146+
test("reset user missing from aggregation rows -- defaults to 0", async () => {
147+
const resetAtMap = new Map([[10, new Date("2026-02-15T00:00:00Z")]]);
148+
dbResultMock.mockReturnValueOnce([]);
149+
150+
const { sumUserTotalCostBatch } = await import("@/repository/statistics");
151+
const result = await sumUserTotalCostBatch([10], 365, resetAtMap);
152+
153+
expect(result.get(10)).toBe(0);
154+
});
155+
156+
test("with invalid reset date -- treated as batch user, no cutoff aggregation", async () => {
157+
const resetAtMap = new Map([[10, new Date("invalid")]]);
158+
dbResultMock.mockReturnValue([{ userId: 10, total: 33.0 }]);
159+
160+
const { sumUserTotalCostBatch } = await import("@/repository/statistics");
161+
const result = await sumUserTotalCostBatch([10], 365, resetAtMap);
162+
163+
expect(result.get(10)).toBe(33.0);
164+
expect(dbExecuteMock).not.toHaveBeenCalled();
126165
});
127166

128167
test("with empty resetAtMap -- single batch query for all users", async () => {
@@ -147,16 +186,16 @@ describe("statistics resetAt parameter", () => {
147186
});
148187

149188
describe("sumKeyTotalCostBatchByIds", () => {
150-
test("with resetAtMap -- splits keys into individual vs batch", async () => {
189+
test("with resetAtMap -- aggregates reset keys in one statement, batch for the rest", async () => {
151190
const resetAtMap = new Map([[1, new Date("2026-02-15T00:00:00Z")]]);
152191
dbResultMock
153192
// 1) PK lookup: key strings
154193
.mockReturnValueOnce([
155194
{ id: 1, key: "sk-a" },
156195
{ id: 2, key: "sk-b" },
157196
])
158-
// 2) individual sumKeyTotalCost for key 1
159-
.mockReturnValueOnce([{ total: 10.0 }])
197+
// 2) VALUES-join aggregation for reset key 1 (db.execute)
198+
.mockReturnValueOnce([{ entity_id: "sk-a", total: 10.0 }])
160199
// 3) batch for key 2
161200
.mockReturnValueOnce([{ key: "sk-b", total: 20.0 }]);
162201

@@ -165,6 +204,24 @@ describe("statistics resetAt parameter", () => {
165204

166205
expect(result.get(1)).toBe(10.0);
167206
expect(result.get(2)).toBe(20.0);
207+
expect(dbExecuteMock).toHaveBeenCalledTimes(1);
208+
});
209+
210+
test("many reset keys -- still a single aggregation statement (regression #1511)", async () => {
211+
const keyIds = Array.from({ length: 40 }, (_, i) => i + 1);
212+
const resetAtMap = new Map(keyIds.map((id) => [id, new Date("2026-02-15T00:00:00Z")]));
213+
dbResultMock
214+
// 1) PK lookup: key strings
215+
.mockReturnValueOnce(keyIds.map((id) => ({ id, key: `sk-${id}` })))
216+
// 2) VALUES-join aggregation for all reset keys (db.execute)
217+
.mockReturnValueOnce(keyIds.map((id) => ({ entity_id: `sk-${id}`, total: id })));
218+
219+
const { sumKeyTotalCostBatchByIds } = await import("@/repository/statistics");
220+
const result = await sumKeyTotalCostBatchByIds(keyIds, Infinity, resetAtMap);
221+
222+
expect(dbExecuteMock).toHaveBeenCalledTimes(1);
223+
expect(result.get(1)).toBe(1);
224+
expect(result.get(40)).toBe(40);
168225
});
169226

170227
test("empty keyIds -- returns empty map immediately", async () => {

0 commit comments

Comments
 (0)