| 192 | } |
| 193 | |
| 194 | export async function postChatCompletions(params: { |
| 195 | req: NextRequest |
| 196 | getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 197 | logger: Logger |
| 198 | loggerWithContext: LoggerWithContextFn |
| 199 | trackEvent: TrackEventFn |
| 200 | getUserUsageData: GetUserUsageDataFn |
| 201 | getAgentRunFromId: GetAgentRunFromIdFn |
| 202 | fetch: typeof globalThis.fetch |
| 203 | insertMessageBigquery: InsertMessageBigqueryFn |
| 204 | insertChatCompletionTraceBigquery?: InsertChatCompletionTraceBigqueryFn |
| 205 | ensureSubscriberBlockGrant?: (params: { |
| 206 | userId: string |
| 207 | logger: Logger |
| 208 | }) => Promise<BlockGrantResult | null> |
| 209 | getUserPreferences?: GetUserPreferencesFn |
| 210 | /** Optional override for the freebuff waiting-room gate. Defaults to the |
| 211 | * real check backed by Postgres; tests inject a no-op. */ |
| 212 | checkSessionAdmissible?: CheckSessionAdmissibleFn |
| 213 | /** Optional override for the free-mode rate limiter. Tests inject this to |
| 214 | * avoid coupling to process-global limiter state. */ |
| 215 | checkFreeModeRateLimit?: CheckFreeModeRateLimitFn |
| 216 | /** Optional override for country/cache checks. Tests inject this to avoid |
| 217 | * coupling to Postgres-backed cache state. */ |
| 218 | resolveFreeModeCountryAccess?: ResolveFreeModeCountryAccessFn |
| 219 | /** Optional override for releasing stale waiting-room rows on hard blocks. */ |
| 220 | endFreebuffSession?: EndUserSessionFn |
| 221 | }) { |
| 222 | const { |
| 223 | req, |
| 224 | getUserInfoFromApiKey, |
| 225 | loggerWithContext, |
| 226 | getUserUsageData, |
| 227 | getAgentRunFromId, |
| 228 | fetch, |
| 229 | insertMessageBigquery, |
| 230 | insertChatCompletionTraceBigquery, |
| 231 | ensureSubscriberBlockGrant, |
| 232 | getUserPreferences, |
| 233 | checkSessionAdmissible: checkSession = checkSessionAdmissible, |
| 234 | checkFreeModeRateLimit = defaultCheckFreeModeRateLimit, |
| 235 | resolveFreeModeCountryAccess, |
| 236 | endFreebuffSession = endUserSession, |
| 237 | } = params |
| 238 | let { logger } = params |
| 239 | let { trackEvent } = params |
| 240 | const resolveCountryAccess: ResolveFreeModeCountryAccessFn = |
| 241 | resolveFreeModeCountryAccess ?? |
| 242 | ((userId, req, options) => |
| 243 | getCachedFreeModeCountryAccess({ userId, req, options, logger })) |
| 244 | |
| 245 | try { |
| 246 | // Parse request body |
| 247 | let body: Record<string, unknown> |
| 248 | try { |
| 249 | body = await req.json() |
| 250 | } catch (error) { |
| 251 | trackEvent({ |