mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 11:48:43 +00:00
fix(ai-usage): resolve code review feedback for concurrency upsert and timeframe window
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { aiUsageService } from './ai-usage'
|
||||
@@ -151,8 +151,8 @@ describe('AiUsageService', () => {
|
||||
|
||||
const now = new Date()
|
||||
|
||||
// 30 minutes ago (within 1h)
|
||||
const recent = new Date(now.getTime() - 30 * 60 * 1000)
|
||||
// 5 minutes ago (within current 1h bucket)
|
||||
const recent = new Date(now.getTime() - 5 * 60 * 1000)
|
||||
// 2 hours ago (within 24h, outside 1h)
|
||||
const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000)
|
||||
// 3 days ago (within 7d, outside 24h)
|
||||
@@ -224,4 +224,84 @@ describe('AiUsageService', () => {
|
||||
}),
|
||||
).rejects.toThrow(HTTPException)
|
||||
})
|
||||
|
||||
it('targets only current hour bucket for 1h timeframe instead of including previous hour bucket', async () => {
|
||||
const { team, user } = await createTestTeamAndUser()
|
||||
|
||||
// 10:15 AM (previous hour)
|
||||
const prevHour = new Date('2026-07-23T10:15:00Z')
|
||||
// 11:10 AM (current hour)
|
||||
const currHour = new Date('2026-07-23T11:10:00Z')
|
||||
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
totalTokens: 100,
|
||||
cost: 0.001,
|
||||
timestamp: prevHour,
|
||||
})
|
||||
|
||||
await aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 50,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
totalTokens: 50,
|
||||
cost: 0.0005,
|
||||
timestamp: currHour,
|
||||
})
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-07-23T11:15:00Z'))
|
||||
|
||||
try {
|
||||
const stats1h = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '1h',
|
||||
})
|
||||
expect(stats1h.team?.inputTokens).toBe(50)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('handles concurrent recordUsage calls for the same team and user without duplication or race errors', async () => {
|
||||
const { team, user } = await createTestTeamAndUser()
|
||||
const now = new Date()
|
||||
|
||||
await Promise.all([
|
||||
aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 10,
|
||||
totalTokens: 150,
|
||||
cost: 0.001,
|
||||
timestamp: now,
|
||||
}),
|
||||
aiUsageService.recordUsage({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
inputTokens: 200,
|
||||
outputTokens: 100,
|
||||
cacheReadTokens: 20,
|
||||
totalTokens: 300,
|
||||
cost: 0.002,
|
||||
timestamp: now,
|
||||
}),
|
||||
])
|
||||
|
||||
const stats = await aiUsageService.getTeamUsageStats({
|
||||
teamId: team.id,
|
||||
timeframe: '1h',
|
||||
})
|
||||
|
||||
expect(stats.team?.inputTokens).toBe(300)
|
||||
expect(stats.team?.outputTokens).toBe(150)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -30,28 +30,24 @@ export class AiUsageService {
|
||||
totalTokens: number
|
||||
cost: number
|
||||
}): Promise<void> {
|
||||
const existing = await prisma.aiUsage.findFirst({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
periodStart: params.periodStart,
|
||||
},
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
await prisma.aiUsage.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
if (params.userId !== null) {
|
||||
await prisma.aiUsage.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
teamId_userId_periodStart: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
periodStart: params.periodStart,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
inputTokens: { increment: params.inputTokens },
|
||||
outputTokens: { increment: params.outputTokens },
|
||||
cacheReadTokens: { increment: params.cacheReadTokens },
|
||||
totalTokens: { increment: params.totalTokens },
|
||||
cost: { increment: params.cost },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await prisma.aiUsage.create({
|
||||
data: {
|
||||
create: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
periodStart: params.periodStart,
|
||||
@@ -62,6 +58,66 @@ export class AiUsageService {
|
||||
cost: params.cost,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const existing = await prisma.aiUsage.findFirst({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
userId: null,
|
||||
periodStart: params.periodStart,
|
||||
},
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
await prisma.aiUsage.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
inputTokens: { increment: params.inputTokens },
|
||||
outputTokens: { increment: params.outputTokens },
|
||||
cacheReadTokens: { increment: params.cacheReadTokens },
|
||||
totalTokens: { increment: params.totalTokens },
|
||||
cost: { increment: params.cost },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
try {
|
||||
await prisma.aiUsage.create({
|
||||
data: {
|
||||
teamId: params.teamId,
|
||||
userId: null,
|
||||
periodStart: params.periodStart,
|
||||
inputTokens: params.inputTokens,
|
||||
outputTokens: params.outputTokens,
|
||||
cacheReadTokens: params.cacheReadTokens,
|
||||
totalTokens: params.totalTokens,
|
||||
cost: params.cost,
|
||||
},
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
if (
|
||||
err &&
|
||||
typeof err === 'object' &&
|
||||
'code' in err &&
|
||||
(err as { code: string }).code === 'P2002'
|
||||
) {
|
||||
await prisma.aiUsage.updateMany({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
userId: null,
|
||||
periodStart: params.periodStart,
|
||||
},
|
||||
data: {
|
||||
inputTokens: { increment: params.inputTokens },
|
||||
outputTokens: { increment: params.outputTokens },
|
||||
cacheReadTokens: { increment: params.cacheReadTokens },
|
||||
totalTokens: { increment: params.totalTokens },
|
||||
cost: { increment: params.cost },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +125,6 @@ export class AiUsageService {
|
||||
const timestamp = params.timestamp ?? new Date()
|
||||
const periodStart = new Date(timestamp)
|
||||
periodStart.setMinutes(0, 0, 0)
|
||||
periodStart.setMilliseconds(0)
|
||||
|
||||
// 1. Update/create Team Total record (userId = null)
|
||||
await this.incrementBucket({
|
||||
@@ -104,21 +159,23 @@ export class AiUsageService {
|
||||
|
||||
switch (params.timeframe) {
|
||||
case '1h':
|
||||
since.setHours(since.getHours() - 1)
|
||||
// For 1h, target the current 1h bucket floored to start of current hour
|
||||
since.setMinutes(0, 0, 0)
|
||||
break
|
||||
case '24h':
|
||||
since.setDate(since.getDate() - 1)
|
||||
since.setMinutes(0, 0, 0)
|
||||
break
|
||||
case '7d':
|
||||
since.setDate(since.getDate() - 7)
|
||||
since.setMinutes(0, 0, 0)
|
||||
break
|
||||
case '30d':
|
||||
since.setDate(since.getDate() - 30)
|
||||
since.setMinutes(0, 0, 0)
|
||||
break
|
||||
}
|
||||
|
||||
since.setMinutes(0, 0, 0)
|
||||
|
||||
if (!params.userId) {
|
||||
// Return Team-Level Usage (userId = null)
|
||||
const teamRecords = await prisma.aiUsage.findMany({
|
||||
@@ -150,7 +207,7 @@ export class AiUsageService {
|
||||
outputTokens,
|
||||
cacheReadTokens,
|
||||
totalTokens,
|
||||
cost: Math.round(cost * 1000000) / 1000000,
|
||||
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
@@ -201,7 +258,7 @@ export class AiUsageService {
|
||||
outputTokens,
|
||||
cacheReadTokens,
|
||||
totalTokens,
|
||||
cost: Math.round(cost * 1000000) / 1000000,
|
||||
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[team_id,user_id,period_start]` on the table `ai_usages` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ai_usages_team_id_user_id_period_start_key" ON "ai_usages"("team_id", "user_id", "period_start");
|
||||
@@ -834,6 +834,7 @@ model AiUsage {
|
||||
user User? @relation("UserToAiUsage", fields: [userId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@map("ai_usages")
|
||||
@@unique([teamId, userId, periodStart])
|
||||
@@index([teamId, periodStart])
|
||||
@@index([teamId, userId, periodStart])
|
||||
}
|
||||
|
||||
+3
-3
File diff suppressed because one or more lines are too long
+8
-1
@@ -304,6 +304,7 @@ export type AiUsageOrderByWithRelationInput = {
|
||||
|
||||
export type AiUsageWhereUniqueInput = Prisma.AtLeast<{
|
||||
id?: string
|
||||
teamId_userId_periodStart?: Prisma.AiUsageTeamIdUserIdPeriodStartCompoundUniqueInput
|
||||
AND?: Prisma.AiUsageWhereInput | Prisma.AiUsageWhereInput[]
|
||||
OR?: Prisma.AiUsageWhereInput[]
|
||||
NOT?: Prisma.AiUsageWhereInput | Prisma.AiUsageWhereInput[]
|
||||
@@ -319,7 +320,7 @@ export type AiUsageWhereUniqueInput = Prisma.AtLeast<{
|
||||
updatedAt?: Prisma.DateTimeFilter<"AiUsage"> | Date | string
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
user?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
|
||||
}, "id">
|
||||
}, "id" | "teamId_userId_periodStart">
|
||||
|
||||
export type AiUsageOrderByWithAggregationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
@@ -463,6 +464,12 @@ export type AiUsageOrderByRelationAggregateInput = {
|
||||
_count?: Prisma.SortOrder
|
||||
}
|
||||
|
||||
export type AiUsageTeamIdUserIdPeriodStartCompoundUniqueInput = {
|
||||
teamId: string
|
||||
userId: string
|
||||
periodStart: Date | string
|
||||
}
|
||||
|
||||
export type AiUsageCountOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
|
||||
Reference in New Issue
Block a user