MCPcopy Index your code
hub / github.com/CodebuffAI/codebuff / admitFromQueue

Function admitFromQueue

web/src/server/free-session/store.ts:405–484  ·  view source on GitHub ↗
(params: {
  model: string
  sessionLengthMs: number
  now: Date
  health: FireworksHealth
})

Source from the content-addressed store, hash-verified

403 * unhealthy means "upstream unreachable or saturated").
404 */
405export async function admitFromQueue(params: {
406 model: string
407 sessionLengthMs: number
408 now: Date
409 health: FireworksHealth
410}): Promise<{
411 admitted: InternalSessionRow[]
412 skipped: FireworksHealth | null
413}> {
414 const { model, sessionLengthMs, now, health } = params
415
416 if (health !== 'healthy') {
417 return { admitted: [], skipped: health }
418 }
419
420 return db.transaction(async (tx) => {
421 // Per-model lock: hashing the model into the lock id lets distinct model
422 // queues admit concurrently while still serializing within a single queue.
423 const modelLockId = FREEBUFF_ADMISSION_LOCK_ID + hashStringToInt32(model)
424 const lockResult = await tx.execute<{ acquired: unknown }>(
425 sql`SELECT pg_try_advisory_xact_lock(${modelLockId}) AS acquired`,
426 )
427 if (
428 !coerceBool(
429 (lockResult as unknown as Array<{ acquired: unknown }>)[0]?.acquired,
430 )
431 ) {
432 return { admitted: [], skipped: null }
433 }
434
435 const candidates = await tx
436 .select({ user_id: schema.freeSession.user_id })
437 .from(schema.freeSession)
438 .where(
439 and(
440 eq(schema.freeSession.status, 'queued'),
441 eq(schema.freeSession.model, model),
442 ),
443 )
444 .orderBy(
445 asc(schema.freeSession.queued_at),
446 asc(schema.freeSession.user_id),
447 )
448 .limit(1)
449 .for('update', { skipLocked: true })
450
451 const candidate = candidates[0]
452 if (!candidate) return { admitted: [], skipped: null }
453
454 const expiresAt = new Date(now.getTime() + sessionLengthMs)
455 const admitted = await tx
456 .update(schema.freeSession)
457 .set({
458 status: 'active',
459 admitted_at: now,
460 expires_at: expiresAt,
461 updated_at: now,
462 })

Callers

nothing calls this directly

Calls 5

coerceBoolFunction · 0.90
hashStringToInt32Function · 0.85
fromMethod · 0.80
setMethod · 0.80
insertMethod · 0.80

Tested by

no test coverage detected