Files
botfights/server/src/routes/fights.ts
T

292 lines
9.1 KiB
TypeScript
Raw Normal View History

import { Hono } from 'hono'
import { streamSSE } from 'hono/streaming'
import { db, schema } from '../db/index.js'
import { eq, desc } from 'drizzle-orm'
import { ARENAS } from '../engine/arenas.js'
import { runMockFight } from '../engine/mock.js'
import { runFight, runFightAsync } from '../engine/orchestrator.js'
import { fightEvents } from '../engine/events.js'
export const fightsRouter = new Hono()
// List recent fights (with bot names)
fightsRouter.get('/', async (c) => {
const rows = await db.select()
.from(schema.fights)
.orderBy(desc(schema.fights.createdAt))
.limit(20)
// Resolve bot names
const botIds = new Set<string>()
for (const f of rows) {
botIds.add(f.botAId)
botIds.add(f.botBId)
if (f.winnerId) botIds.add(f.winnerId)
}
const botMap = new Map<string, { name: string; avatarSeed: string; eloRating: number; tier: number }>()
for (const id of botIds) {
const bot = await db.select({
name: schema.bots.name,
avatarSeed: schema.bots.avatarSeed,
eloRating: schema.bots.eloRating,
tier: schema.bots.tier,
}).from(schema.bots).where(eq(schema.bots.id, id)).limit(1)
if (bot[0]) botMap.set(id, bot[0])
}
const enriched = rows.map(f => {
const arena = ARENAS.find(a => a.id === f.arena)
return {
...f,
botA: botMap.get(f.botAId) || null,
botB: botMap.get(f.botBId) || null,
winner: f.winnerId ? botMap.get(f.winnerId) || null : null,
arenaInfo: arena ? { name: arena.name, description: arena.description } : null,
}
})
return c.json(enriched)
})
// Get a single fight with rounds and bot details
fightsRouter.get('/:id', async (c) => {
const id = c.req.param('id')
const fightRows = await db.select()
.from(schema.fights)
.where(eq(schema.fights.id, id))
.limit(1)
if (fightRows.length === 0) {
return c.json({ error: 'Fight not found.' }, 404)
}
const fight = fightRows[0]
const botFields = {
id: schema.bots.id,
name: schema.bots.name,
avatarSeed: schema.bots.avatarSeed,
archetype: schema.bots.archetype,
profilePicUrl: schema.bots.profilePicUrl,
eloRating: schema.bots.eloRating,
wins: schema.bots.wins,
losses: schema.bots.losses,
tier: schema.bots.tier,
}
const [botARows, botBRows] = await Promise.all([
db.select(botFields).from(schema.bots).where(eq(schema.bots.id, fight.botAId)).limit(1),
db.select(botFields).from(schema.bots).where(eq(schema.bots.id, fight.botBId)).limit(1),
])
const roundRows = await db.select()
.from(schema.rounds)
.where(eq(schema.rounds.fightId, id))
.orderBy(schema.rounds.roundNumber)
const arena = ARENAS.find(a => a.id === fight.arena)
return c.json({
...fight,
botA: botARows[0] || null,
botB: botBRows[0] || null,
arenaInfo: arena || null,
rounds: roundRows,
})
})
// Trigger a mock fight between two random bots (dev/testing)
fightsRouter.post('/mock', async (c) => {
const allBots = await db.select({ id: schema.bots.id }).from(schema.bots)
if (allBots.length < 2) {
return c.json({ error: 'Need at least 2 registered bots.' }, 400)
}
const shuffled = [...allBots].sort(() => Math.random() - 0.5)
const fightId = await runMockFight(shuffled[0].id, shuffled[1].id)
return c.json({ fightId, message: 'Mock fight completed.' })
})
// Trigger a mock fight for a specific bot against a random opponent
fightsRouter.post('/mock/:botId', async (c) => {
const botId = c.req.param('botId')
const botRows = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(schema.bots.id, botId))
.limit(1)
if (botRows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
const opponents = await db.select({ id: schema.bots.id })
.from(schema.bots)
const others = opponents.filter(b => b.id !== botId)
if (others.length === 0) {
return c.json({ error: 'No opponents available.' }, 400)
}
const opponent = others[Math.floor(Math.random() * others.length)]
const fightId = await runMockFight(botId, opponent.id)
return c.json({ fightId, message: 'Mock fight completed.' })
})
// Start a REAL fight — calls actual webhooks
// If botId is provided, fights that bot vs a random opponent
// If no real opponents exist, falls back to a mock opponent
fightsRouter.post('/fight/:botId', async (c) => {
const botId = c.req.param('botId')
const botRows = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
.from(schema.bots)
.where(eq(schema.bots.id, botId))
.limit(1)
if (botRows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
// Find a real opponent (any other bot with a non-mock webhook)
const allBots = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
.from(schema.bots)
const realOpponents = allBots.filter(b => b.id !== botId && !b.webhookUrl.startsWith('http://mock.local'))
const mockOpponents = allBots.filter(b => b.id !== botId && b.webhookUrl.startsWith('http://mock.local'))
let opponentId: string
let useMock = false
if (realOpponents.length > 0) {
// Prefer real opponents
opponentId = realOpponents[Math.floor(Math.random() * realOpponents.length)].id
} else if (mockOpponents.length > 0) {
// Fall back to mock opponent — but still use real fight engine for the registered bot
opponentId = mockOpponents[Math.floor(Math.random() * mockOpponents.length)].id
useMock = true
} else {
return c.json({ error: 'No opponents available.' }, 400)
}
// For fights involving a mock bot, use runMockFight (since mock webhooks don't exist)
// For two real bots, use runFight (calls actual webhooks)
if (useMock) {
// The registered bot gives real answers, mock bot gives fake ones
// We need a hybrid — for now, use mock fight so it works immediately
const fightId = await runMockFight(botId, opponentId)
return c.json({ fightId, message: 'Fight completed (opponent was a mock bot).' })
}
// Both bots are real — run a real fight with webhook calls
// Run in background so we can return the fightId immediately
const { nanoid } = await import('nanoid')
const fightId = nanoid(12)
// Don't await — let it run while the user watches
runFight(botId, opponentId).then(id => {
console.log(`[botfights] real fight ${id} completed`)
}).catch(err => {
console.error(`[botfights] fight error:`, err)
})
// Return the fight ID immediately so the frontend can navigate to it
// The fight will be created by runFight momentarily
return c.json({ fightId: 'pending', botId, opponentId, message: 'Real fight starting...' })
})
// SSE stream for live fight events
fightsRouter.get('/:id/stream', (c) => {
const fightId = c.req.param('id')
return streamSSE(c, async (stream) => {
const cleanup = fightEvents.on(fightId, (event) => {
stream.writeSSE({
event: event.type,
data: JSON.stringify(event.data),
})
})
// Also listen for global events to catch fight_end
const cleanupGlobal = fightEvents.onAll((event) => {
if (event.fightId === fightId && event.type === 'fight_end') {
stream.writeSSE({
event: 'fight_end',
data: JSON.stringify(event.data),
})
}
})
// Keep alive until fight ends or client disconnects
try {
while (true) {
await stream.writeSSE({ event: 'ping', data: '' })
await stream.sleep(5000)
// Check if fight is done
const fight = await db.select({ status: schema.fights.status })
.from(schema.fights)
.where(eq(schema.fights.id, fightId))
.limit(1)
if (fight.length > 0 && fight[0].status === 'finished') break
}
} catch {
// Client disconnected
} finally {
cleanup()
cleanupGlobal()
}
})
})
// Instant matchmaking — find an opponent and start a fight NOW
fightsRouter.post('/matchmake/:botId', async (c) => {
const botId = c.req.param('botId')
const botRows = await db.select()
.from(schema.bots)
.where(eq(schema.bots.id, botId))
.limit(1)
if (botRows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
const bot = botRows[0]
// Find all other active bots, prefer close elo
const allBots = await db.select()
.from(schema.bots)
const opponents = allBots.filter(b => b.id !== botId)
if (opponents.length === 0) {
return c.json({ error: 'No opponents available.' }, 400)
}
// Sort by closest elo for fair matchmaking, with some randomness
opponents.sort((a, b) => {
const diffA = Math.abs(a.eloRating - bot.eloRating) + Math.random() * 200
const diffB = Math.abs(b.eloRating - bot.eloRating) + Math.random() * 200
return diffA - diffB
})
const opponent = opponents[0]
const isRealOpponent = !opponent.webhookUrl.startsWith('http://mock.local')
const isMockBot = bot.webhookUrl.startsWith('http://mock.local')
let fightId: string
// Start fight async — returns immediately so frontend can watch live
fightId = await runFightAsync(botId, opponent.id)
return c.json({
fightId,
opponent: { id: opponent.id, name: opponent.name },
message: 'Fight started.',
})
})