Skip to content

Commit 6a4e738

Browse files
committed
pass logger into balance calculator
1 parent 072d4cd commit 6a4e738

File tree

11 files changed

+182
-112
lines changed

11 files changed

+182
-112
lines changed

backend/src/__tests__/usage-calculation.test.ts

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,16 @@ import {
77
import { afterAll, beforeAll, describe, expect, it } from 'bun:test'
88

99
import type { GrantType } from '@codebuff/common/db/schema'
10+
import type { Logger } from '@codebuff/types/logger'
1011

1112
describe('Usage Calculation System', () => {
13+
const logger: Logger = {
14+
debug: () => {},
15+
error: () => {},
16+
info: () => {},
17+
warn: () => {},
18+
}
19+
1220
beforeAll(() => {
1321
// Mock the database module before importing the function
1422
mockModule('@codebuff/common/db', () => ({
@@ -22,17 +30,6 @@ describe('Usage Calculation System', () => {
2230
}),
2331
},
2432
}))
25-
26-
// Mock logger
27-
mockModule('@codebuff/common/util/logger', () => ({
28-
logger: {
29-
debug: () => {},
30-
error: () => {},
31-
info: () => {},
32-
warn: () => {},
33-
},
34-
withLoggerContext: async (context: any, fn: () => Promise<any>) => fn(),
35-
}))
3633
})
3734

3835
afterAll(() => {
@@ -76,11 +73,12 @@ describe('Usage Calculation System', () => {
7673
},
7774
}))
7875

79-
const { usageThisCycle } = await calculateUsageAndBalance(
80-
'test-user',
81-
new Date('2024-01-01'),
82-
new Date('2024-01-15'), // Pass current time when grants are active
83-
)
76+
const { usageThisCycle } = await calculateUsageAndBalance({
77+
userId: 'test-user',
78+
quotaResetDate: new Date('2024-01-01'),
79+
now: new Date('2024-01-15'), // Pass current time when grants are active
80+
logger,
81+
})
8482

8583
expect(usageThisCycle).toBe(400) // 200 + 200 = 400 total usage
8684
})
@@ -112,11 +110,12 @@ describe('Usage Calculation System', () => {
112110
},
113111
}))
114112

115-
const { balance, usageThisCycle } = await calculateUsageAndBalance(
116-
'test-user',
117-
new Date('2024-01-01'),
118-
new Date('2024-01-16'), // Current time after expiry
119-
)
113+
const { balance, usageThisCycle } = await calculateUsageAndBalance({
114+
userId: 'test-user',
115+
quotaResetDate: new Date('2024-01-01'),
116+
now: new Date('2024-01-16'), // Current time after expiry
117+
logger,
118+
})
120119

121120
expect(balance.totalRemaining).toBe(0) // Expired grant doesn't count
122121
expect(balance.totalDebt).toBe(0)
@@ -158,11 +157,12 @@ describe('Usage Calculation System', () => {
158157
},
159158
}))
160159

161-
const { balance } = await calculateUsageAndBalance(
162-
'test-user',
163-
new Date('2024-01-01'),
164-
new Date('2024-01-15'), // Pass current time when grants are active
165-
)
160+
const { balance } = await calculateUsageAndBalance({
161+
userId: 'test-user',
162+
quotaResetDate: new Date('2024-01-01'),
163+
now: new Date('2024-01-15'), // Pass current time when grants are active
164+
logger,
165+
})
166166

167167
expect(balance.totalRemaining).toBe(0)
168168
expect(balance.totalDebt).toBe(100)
@@ -213,11 +213,12 @@ describe('Usage Calculation System', () => {
213213
},
214214
}))
215215

216-
const { balance, usageThisCycle } = await calculateUsageAndBalance(
217-
'test-user',
218-
new Date('2024-01-01'),
219-
new Date('2024-01-15'), // Pass current time when grants are active
220-
)
216+
const { balance, usageThisCycle } = await calculateUsageAndBalance({
217+
userId: 'test-user',
218+
quotaResetDate: new Date('2024-01-01'),
219+
now: new Date('2024-01-15'), // Pass current time when grants are active
220+
logger,
221+
})
221222

222223
// Settlement: 100 positive balance - 50 debt = 50 remaining
223224
expect(balance.totalRemaining).toBe(50)

backend/src/llm-apis/message-cost-tracker.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -540,7 +540,11 @@ async function updateUserCycleUsage(
540540
return result
541541
} else {
542542
// Consume from personal credits
543-
const result = await consumeCredits(userId, creditsUsed)
543+
const result = await consumeCredits({
544+
userId,
545+
creditsToConsume: creditsUsed,
546+
logger,
547+
})
544548

545549
if (VERBOSE) {
546550
logger.debug(

backend/src/websockets/middleware.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -345,10 +345,11 @@ protec.use(async (action, clientSessionId, ws, userInfo) => {
345345
// Continue execution to check remaining balance
346346
}
347347

348-
const { usageThisCycle, balance } = await calculateUsageAndBalance(
348+
const { usageThisCycle, balance } = await calculateUsageAndBalance({
349349
userId,
350-
user?.next_quota_reset ?? new Date(0),
351-
)
350+
quotaResetDate: user?.next_quota_reset ?? new Date(0),
351+
logger,
352+
})
352353

353354
// Check if we have enough remaining credits
354355
if (balance.totalRemaining <= 0) {

backend/src/websockets/websocket-action.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,11 @@ export async function genUsageResponse(params: {
104104
try {
105105
// Get the usage data
106106
const { balance: balanceDetails, usageThisCycle } =
107-
await calculateUsageAndBalance(userId, new Date())
107+
await calculateUsageAndBalance({
108+
userId,
109+
quotaResetDate: new Date(),
110+
logger,
111+
})
108112

109113
return {
110114
type: 'usage-response' as const,
@@ -428,10 +432,7 @@ export async function requestFiles(params: {
428432
* @param filePath - The path of the file to request
429433
* @returns Promise resolving to the file contents or null if not found
430434
*/
431-
export async function requestFile(params: {
432-
ws: WebSocket
433-
filePath: string
434-
}) {
435+
export async function requestFile(params: { ws: WebSocket; filePath: string }) {
435436
const { ws, filePath } = params
436437
const files = await requestFiles({ ws, filePaths: [filePath] })
437438
return files[filePath] ?? null

packages/billing/src/auto-topup.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,10 +233,10 @@ export async function checkAndTriggerAutoTopup(params: {
233233
}
234234

235235
// Calculate balance
236-
const { balance } = await calculateUsageAndBalance(
237-
userId,
238-
user.next_quota_reset ?? new Date(0),
239-
)
236+
const { balance } = await calculateUsageAndBalance({
237+
...params,
238+
quotaResetDate: user.next_quota_reset ?? new Date(0),
239+
})
240240

241241
if (
242242
balance.totalRemaining >= user.auto_topup_threshold &&

0 commit comments

Comments
 (0)