import express from 'express'; import { createClient } from '@supabase/supabase-js'; import type { Database } from './types/database'; import { ScreenshareBot } from './bots/ScreenshareBot'; const app = express(); const PORT = parseInt(process.env.PORT || '3001', 10); // Supabase configuration const SUPABASE_URL = process.env.SUPABASE_URL || ''; const SUPABASE_KEY = process.env.SUPABASE_KEY || ''; // Initialize Supabase client (only if properly configured) let supabase: ReturnType> | null = null; try { if (SUPABASE_URL && SUPABASE_KEY) { supabase = createClient(SUPABASE_URL, SUPABASE_KEY); } } catch (error) { console.warn('Supabase client initialization failed:', error instanceof Error ? error.message : 'Unknown error'); } app.use(express.json()); /** * Health check endpoint * Tests Supabase connection and returns service status */ app.get('/health', (_req, res) => { void (async () => { try { const timestamp = new Date().toISOString(); // Check if Supabase client is initialized if (!supabase) { console.warn(`[${timestamp}] Supabase client not configured`); return res.status(200).json({ status: 'healthy', timestamp, bots_active: 0, python_version: process.env.PYTHON_VERSION || 'unknown', service: 'bot-spawner', node_version: process.version, supabase_configured: false, message: 'Service running but Supabase not configured' }); } // Test Supabase connection by querying active_bots count (exclude stopped bots) const { count, error } = await supabase .from('active_bots') .select('*', { count: 'exact', head: true }) .neq('status', 'stopped'); if (error) { console.error(`[${timestamp}] Supabase health check failed:`, error); return res.status(503).json({ status: 'unhealthy', timestamp, error: 'Database connection failed', details: error.message }); } // Get Python version from environment const pythonVersion = process.env.PYTHON_VERSION || 'unknown'; console.log(`[${timestamp}] Health check successful - Active bots: ${count}`); return res.json({ status: 'healthy', timestamp, bots_active: count || 0, python_version: pythonVersion, service: 'bot-spawner', node_version: process.version, supabase_configured: true }); } catch (error) { const timestamp = new Date().toISOString(); console.error(`[${timestamp}] Health check error:`, error); return res.status(503).json({ status: 'unhealthy', timestamp, error: 'Health check failed', details: error instanceof Error ? error.message : 'Unknown error' }); } })(); }); /** * Spawn screenshare bot endpoint * Receives spawn request and starts a new ScreenshareBot instance */ app.post('/api/bots/screenshare/spawn-livekit', (req, res) => { void (async () => { try { const timestamp = new Date().toISOString(); const { room_name, deck_url, session_id, screenshare_token } = req.body; console.log(`[${timestamp}] [BOT_SPAWNER] Spawn request received:`, { session_id, room_name, deck_url: deck_url ? deck_url.substring(0, 50) + '...' : undefined, has_token: !!screenshare_token, }); // Validate required fields if (!room_name || !deck_url || !session_id || !screenshare_token) { console.error(`[${timestamp}] [BOT_SPAWNER] Validation failed: missing required fields`); return res.status(400).json({ error: 'Validation failed', details: 'Missing required fields: room_name, deck_url, session_id, screenshare_token', }); } // Validate deck_url format if (!deck_url.startsWith('http://') && !deck_url.startsWith('https://') && !deck_url.startsWith('file://')) { console.error(`[${timestamp}] [BOT_SPAWNER] Validation failed: invalid deck_url format`); return res.status(400).json({ error: 'Validation failed', details: 'Invalid deck_url format. Must be an HTTP(S) or file:// URL', }); } // Validate session_id format (UUID) const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; if (!uuidRegex.test(session_id)) { console.error(`[${timestamp}] [BOT_SPAWNER] Validation failed: invalid session_id format`); return res.status(400).json({ error: 'Validation failed', details: 'Invalid session_id format. Must be a valid UUID', }); } // Check required env vars const livekitUrl = process.env.LIVEKIT_URL; if (!livekitUrl) { console.error(`[${timestamp}] [BOT_SPAWNER] Configuration error: LIVEKIT_URL not set`); return res.status(500).json({ error: 'Server configuration error', details: 'LIVEKIT_URL not configured', }); } // Check if Supabase is configured if (!supabase) { console.error(`[${timestamp}] [BOT_SPAWNER] Configuration error: Supabase not initialized`); return res.status(500).json({ error: 'Server configuration error', details: 'Supabase client not configured', }); } // Check if bot already exists for this session const { data: existingBots } = await supabase .from('active_bots') .select('*') .eq('session_id', session_id) .in('status', ['spawning', 'running']); if (existingBots && existingBots.length > 0) { const existingBot = existingBots[0]; console.log(`[${timestamp}] [BOT_SPAWNER] Bot already exists: ${existingBot.bot_id}`); return res.status(409).json({ error: 'Bot already exists', details: `A bot is already active for session ${session_id}`, bot_id: existingBot.bot_id, status: existingBot.status, }); } // Generate bot ID const { v4: uuidv4 } = await import('uuid'); const botId = uuidv4(); console.log(`[${timestamp}] [BOT_SPAWNER] Spawning bot ${botId}...`); // Create ScreenshareBot instance const botConfig = { botId, sessionId: session_id, roomName: room_name, livekitUrl, screenshareToken: screenshare_token, deckUrl: deck_url, }; const bot = new ScreenshareBot(botConfig); // Store bot metadata in Supabase before starting const { error: insertError } = await supabase .from('active_bots') .insert({ bot_id: botId, bot_type: 'screenshare_livekit', session_id, room_url: `${livekitUrl}/${room_name}`, deck_url, status: 'spawning', pid: process.pid, }); if (insertError) { console.error(`[${timestamp}] [BOT_SPAWNER] Failed to store bot in database:`, insertError); throw new Error(`Failed to store bot metadata: ${insertError.message}`); } // Start bot asynchronously (don't await - let it run in background) bot.start() .then(() => { console.log(`[${timestamp}] [BOT_SPAWNER] Bot ${botId} started successfully`); // Update status to running return supabase .from('active_bots') .update({ status: 'running' }) .eq('bot_id', botId); }) .catch((error) => { console.error(`[${timestamp}] [BOT_SPAWNER] Bot ${botId} start failed:`, error); // Update status to stopped (not just error) return supabase .from('active_bots') .update({ status: 'stopped', stopped_at: new Date().toISOString(), error_message: error instanceof Error ? error.message : 'Unknown error', }) .eq('bot_id', botId); }); console.log(`[${timestamp}] [BOT_SPAWNER] Bot ${botId} spawn initiated successfully`); return res.status(200).json({ bot_id: botId, status: 'spawning', estimated_join_time: '5s', message: `LiveKit bot spawned successfully for session ${session_id}`, }); } catch (error) { const timestamp = new Date().toISOString(); console.error(`[${timestamp}] [BOT_SPAWNER] Error spawning bot:`, error); return res.status(500).json({ error: 'Failed to spawn LiveKit bot', details: error instanceof Error ? error.message : 'Unknown error', }); } })(); }); /** * Cleanup stale bots endpoint * Marks bots stuck in spawning/error state for >5 minutes as stopped * Runs automatically on startup and every hour */ app.post('/api/bots/cleanup', (_req, res) => { void (async () => { try { const timestamp = new Date().toISOString(); if (!supabase) { return res.status(500).json({ error: 'Supabase not configured' }); } console.log(`[${timestamp}] [BOT_CLEANUP] Starting cleanup of stale bots...`); // Calculate cutoff time (5 minutes ago) const cutoffTime = new Date(Date.now() - 5 * 60 * 1000).toISOString(); // Mark spawning bots older than 5 minutes as stopped const { data: spawningBots, error: spawningError } = await supabase .from('active_bots') .update({ status: 'stopped', stopped_at: timestamp, error_message: 'Bot failed to start (timeout)' }) .eq('status', 'spawning') .lt('created_at', cutoffTime) .select('bot_id'); if (spawningError) { console.error(`[${timestamp}] [BOT_CLEANUP] Error cleaning spawning bots:`, spawningError); } else { console.log(`[${timestamp}] [BOT_CLEANUP] Cleaned ${spawningBots?.length || 0} spawning bots`); } // Mark error bots without stopped_at as stopped const { data: errorBots, error: errorError } = await supabase .from('active_bots') .update({ status: 'stopped', stopped_at: timestamp }) .eq('status', 'error') .is('stopped_at', null) .select('bot_id'); if (errorError) { console.error(`[${timestamp}] [BOT_CLEANUP] Error cleaning error bots:`, errorError); } else { console.log(`[${timestamp}] [BOT_CLEANUP] Cleaned ${errorBots?.length || 0} error bots`); } const totalCleaned = (spawningBots?.length || 0) + (errorBots?.length || 0); return res.json({ success: true, cleaned: totalCleaned, timestamp }); } catch (error) { const timestamp = new Date().toISOString(); console.error(`[${timestamp}] [BOT_CLEANUP] Cleanup failed:`, error); return res.status(500).json({ error: 'Cleanup failed', details: error instanceof Error ? error.message : 'Unknown error' }); } })(); }); /** * Root endpoint - basic service info */ app.get('/', (_req, res) => { res.json({ service: 'bot-spawner', version: '1.0.0', status: 'running', endpoints: { health: '/health', spawnScreenshare: '/api/bots/screenshare/spawn-livekit', cleanup: '/api/bots/cleanup' } }); }); /** * Cleanup stale bots automatically */ async function cleanupStaleBots(): Promise { if (!supabase) return; const timestamp = new Date().toISOString(); const cutoffTime = new Date(Date.now() - 5 * 60 * 1000).toISOString(); try { // Mark spawning bots older than 5 minutes as stopped const { data: spawningBots } = await supabase .from('active_bots') .update({ status: 'stopped', stopped_at: timestamp, error_message: 'Bot failed to start (timeout)' }) .eq('status', 'spawning') .lt('created_at', cutoffTime) .select('bot_id'); // Mark error bots without stopped_at as stopped const { data: errorBots } = await supabase .from('active_bots') .update({ status: 'stopped', stopped_at: timestamp }) .eq('status', 'error') .is('stopped_at', null) .select('bot_id'); const totalCleaned = (spawningBots?.length || 0) + (errorBots?.length || 0); if (totalCleaned > 0) { console.log(`[${timestamp}] [AUTO_CLEANUP] Cleaned ${totalCleaned} stale bots`); } } catch (error) { console.error(`[${timestamp}] [AUTO_CLEANUP] Failed:`, error); } } app.listen(PORT, () => { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] Bot Spawner service listening on port ${PORT}`); console.log(`[${timestamp}] Node version: ${process.version}`); console.log(`[${timestamp}] Supabase URL: ${SUPABASE_URL ? 'configured' : 'NOT configured'}`); console.log(`[${timestamp}] Health endpoint available at: http://localhost:${PORT}/health`); // Run cleanup on startup void cleanupStaleBots(); // Run cleanup every hour setInterval(() => { void cleanupStaleBots(); }, 60 * 60 * 1000); });