11import { and , Database , eq , inArray , sql } from "@opencode-ai/console-core/drizzle/index.js"
2- import { ModelTpmLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js"
2+ import { ModelTpmRateLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js"
33import { UsageInfo } from "./provider/provider"
44
55export function createModelTpmLimiter ( providers : { id : string ; model : string ; tpmLimit ?: number } [ ] ) {
66 const ids = providers . filter ( ( p ) => p . tpmLimit ) . map ( ( p ) => `${ p . id } /${ p . model } ` )
77 if ( ids . length === 0 ) return
88
9- const yyyyMMddHHmm = new Date ( Date . now ( ) )
10- . toISOString ( )
11- . replace ( / [ ^ 0 - 9 ] / g, "" )
12- . substring ( 0 , 12 )
9+ const yyyyMMddHHmm = parseInt (
10+ new Date ( Date . now ( ) )
11+ . toISOString ( )
12+ . replace ( / [ ^ 0 - 9 ] / g, "" )
13+ . substring ( 0 , 12 ) ,
14+ )
1315
1416 return {
1517 check : async ( ) => {
1618 const data = await Database . use ( ( tx ) =>
1719 tx
1820 . select ( )
19- . from ( ModelTpmLimitTable )
20- . where (
21- inArray (
22- ModelTpmLimitTable . id ,
23- ids . map ( ( id ) => formatId ( id , yyyyMMddHHmm ) ) ,
24- ) ,
25- ) ,
21+ . from ( ModelTpmRateLimitTable )
22+ . where ( and ( inArray ( ModelTpmRateLimitTable . id , ids ) , eq ( ModelTpmRateLimitTable . interval , yyyyMMddHHmm ) ) ) ,
2623 )
2724
2825 // convert to map of model to count
@@ -41,14 +38,10 @@ export function createModelTpmLimiter(providers: { id: string; model: string; tp
4138 if ( usage <= 0 ) return
4239 await Database . use ( ( tx ) =>
4340 tx
44- . insert ( ModelTpmLimitTable )
45- . values ( { id : formatId ( id , yyyyMMddHHmm ) , count : usage } )
46- . onDuplicateKeyUpdate ( { set : { count : sql `${ ModelTpmLimitTable . count } + ${ usage } ` } } ) ,
41+ . insert ( ModelTpmRateLimitTable )
42+ . values ( { id, interval : yyyyMMddHHmm , count : usage } )
43+ . onDuplicateKeyUpdate ( { set : { count : sql `${ ModelTpmRateLimitTable . count } + ${ usage } ` } } ) ,
4744 )
4845 } ,
4946 }
50-
51- function formatId ( id : string , yyyyMMddHHmm : string ) {
52- return `${ id . substring ( 0 , 200 ) } /${ yyyyMMddHHmm } `
53- }
5447}
0 commit comments