import mysql, { type Pool, type ResultSetHeader } from 'mysql2/promise'; import type { Logger } from './logger.js'; import type { AppConfig } from './types.js'; const SCHEMA_VERSION = 1; export class Database { private pool: Pool; private log: Logger; constructor(mysqlConfig: AppConfig['mysql'], logger: Logger) { this.log = logger.child({ component: 'database' }); this.pool = mysql.createPool({ host: mysqlConfig.host, port: mysqlConfig.port, user: mysqlConfig.user, password: mysqlConfig.password, database: mysqlConfig.database, waitForConnections: true, connectionLimit: 10, enableKeepAlive: true, }); } async initialize(): Promise { await this.testConnection(); await this.migrate(); this.log.info('database initialized'); } private async testConnection(): Promise { const conn = await this.pool.getConnection(); conn.release(); this.log.info('database connected'); } private async migrate(): Promise { const version = await this.getSchemaVersion(); if (version >= SCHEMA_VERSION) return; this.log.info({ from: version, to: SCHEMA_VERSION }, 'running migrations'); if (version < 1) { await this.pool.execute(` CREATE TABLE IF NOT EXISTS games ( id INT AUTO_INCREMENT PRIMARY KEY, uri VARCHAR(512) NOT NULL UNIQUE, owner_did VARCHAR(256) NOT NULL, rkey VARCHAR(128) NOT NULL, white_did VARCHAR(256), black_did VARCHAR(256), status VARCHAR(32) NOT NULL DEFAULT 'waiting', result VARCHAR(16), result_reason VARCHAR(32), move_count INT, verified BOOLEAN DEFAULT FALSE, pgn TEXT, variant VARCHAR(32), starting_fen VARCHAR(200), created_at DATETIME, completed_at DATETIME, last_activity DATETIME, posted BOOLEAN DEFAULT FALSE, deleted BOOLEAN DEFAULT FALSE, INDEX idx_white_did (white_did), INDEX idx_black_did (black_did), INDEX idx_status (status), INDEX idx_last_activity (last_activity) ) `); await this.pool.execute(` CREATE TABLE IF NOT EXISTS players ( did VARCHAR(256) PRIMARY KEY, handle VARCHAR(256), last_game_at DATETIME ) `); await this.pool.execute(` CREATE TABLE IF NOT EXISTS challenges ( id INT AUTO_INCREMENT PRIMARY KEY, uri VARCHAR(512) NOT NULL UNIQUE, owner_did VARCHAR(256) NOT NULL, rkey VARCHAR(128) NOT NULL, opponent_did VARCHAR(256), game_uri VARCHAR(512), status VARCHAR(32) NOT NULL DEFAULT 'open', created_at DATETIME, deleted BOOLEAN DEFAULT FALSE, INDEX idx_opponent_did (opponent_did), INDEX idx_status (status) ) `); await this.pool.execute(` CREATE TABLE IF NOT EXISTS \`cursor\` ( \`key\` VARCHAR(64) PRIMARY KEY, value TEXT NOT NULL, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) `); await this.setSchemaVersion(1); } } private async getSchemaVersion(): Promise { try { await this.pool.execute( `CREATE TABLE IF NOT EXISTS \`cursor\` ( \`key\` VARCHAR(64) PRIMARY KEY, value TEXT NOT NULL, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )` ); const [rows] = await this.pool.execute( "SELECT value FROM `cursor` WHERE `key` = 'schema_version'" ); if (rows.length === 0) return 0; return parseInt(rows[0].value, 10); } catch { return 0; } } private async setSchemaVersion(version: number): Promise { await this.pool.execute( "INSERT INTO `cursor` (`key`, value) VALUES ('schema_version', ?) ON DUPLICATE KEY UPDATE value = ?", [String(version), String(version)] ); } // Cursor operations async getCursor(key: string): Promise { const [rows] = await this.pool.execute( 'SELECT value FROM `cursor` WHERE `key` = ?', [key] ); return rows.length > 0 ? rows[0].value : null; } async setCursor(key: string, value: string): Promise { await this.pool.execute( 'INSERT INTO `cursor` (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?', [key, value, value] ); } // Game operations async upsertGame(fields: { uri: string; ownerDid: string; rkey: string; whiteDid?: string; blackDid?: string; status: string; result?: string; resultReason?: string; moveCount?: number; pgn?: string; variant?: string; startingFen?: string; createdAt?: string; completedAt?: string; }): Promise { const now = new Date(); await this.pool.execute( `INSERT INTO games (uri, owner_did, rkey, white_did, black_did, status, result, result_reason, move_count, pgn, variant, starting_fen, created_at, completed_at, last_activity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE white_did = COALESCE(VALUES(white_did), white_did), black_did = COALESCE(VALUES(black_did), black_did), status = VALUES(status), result = COALESCE(VALUES(result), result), result_reason = COALESCE(VALUES(result_reason), result_reason), move_count = COALESCE(VALUES(move_count), move_count), pgn = COALESCE(VALUES(pgn), pgn), variant = COALESCE(VALUES(variant), variant), starting_fen = COALESCE(VALUES(starting_fen), starting_fen), completed_at = COALESCE(VALUES(completed_at), completed_at), last_activity = VALUES(last_activity)`, [ fields.uri, fields.ownerDid, fields.rkey, fields.whiteDid ?? null, fields.blackDid ?? null, fields.status, fields.result ?? null, fields.resultReason ?? null, fields.moveCount ?? null, fields.pgn ?? null, fields.variant ?? null, fields.startingFen ?? null, fields.createdAt ? new Date(fields.createdAt) : now, fields.completedAt ? new Date(fields.completedAt) : null, now, ] ); } async getGameByUri(uri: string): Promise { const [rows] = await this.pool.execute( 'SELECT * FROM games WHERE uri = ?', [uri] ); return rows.length > 0 ? rows[0] : null; } async getActiveBotGames(botDids: string[]): Promise { if (botDids.length === 0) return []; const placeholders = botDids.map(() => '?').join(','); const [rows] = await this.pool.execute( `SELECT * FROM games WHERE status IN ('waiting', 'active') AND deleted = FALSE AND (white_did IN (${placeholders}) OR black_did IN (${placeholders}))`, [...botDids, ...botDids] ); return rows; } async markGameDeleted(uri: string): Promise { await this.pool.execute( 'UPDATE games SET deleted = TRUE, last_activity = NOW() WHERE uri = ?', [uri] ); } async updateGameVerification(uri: string, verified: boolean, moveCount: number, result?: string, resultReason?: string): Promise { await this.pool.execute( 'UPDATE games SET verified = ?, move_count = ?, result = COALESCE(?, result), result_reason = COALESCE(?, result_reason) WHERE uri = ?', [verified, moveCount, result ?? null, resultReason ?? null, uri] ); } async markGamesPosted(uri: string): Promise { await this.pool.execute('UPDATE games SET posted = TRUE WHERE uri = ?', [uri]); } async markAllUnpostedAsPosted(): Promise { const [result] = await this.pool.execute( 'UPDATE games SET posted = TRUE WHERE posted = FALSE' ); return result.affectedRows; } // Player operations async upsertPlayer(did: string): Promise { await this.pool.execute( 'INSERT INTO players (did, last_game_at) VALUES (?, NOW()) ON DUPLICATE KEY UPDATE last_game_at = NOW()', [did] ); } // Challenge operations async upsertChallenge(fields: { uri: string; ownerDid: string; rkey: string; opponentDid?: string; gameUri?: string; status: string; createdAt?: string; }): Promise { await this.pool.execute( `INSERT INTO challenges (uri, owner_did, rkey, opponent_did, game_uri, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE opponent_did = COALESCE(VALUES(opponent_did), opponent_did), game_uri = COALESCE(VALUES(game_uri), game_uri), status = VALUES(status)`, [ fields.uri, fields.ownerDid, fields.rkey, fields.opponentDid ?? null, fields.gameUri ?? null, fields.status, fields.createdAt ? new Date(fields.createdAt) : new Date(), ] ); } async markChallengeDeleted(uri: string): Promise { await this.pool.execute( 'UPDATE challenges SET deleted = TRUE WHERE uri = ?', [uri] ); } // API queries async getActiveGames(limit = 50): Promise { const [rows] = await this.pool.execute( `SELECT * FROM games WHERE status IN ('waiting', 'active') AND deleted = FALSE ORDER BY last_activity DESC LIMIT ?`, [String(limit)] ); return rows; } async getRecentGames(limit = 50, offset = 0): Promise { const [rows] = await this.pool.execute( `SELECT * FROM games WHERE status = 'completed' AND deleted = FALSE ORDER BY completed_at DESC LIMIT ? OFFSET ?`, [String(limit), String(offset)] ); return rows; } async getGamesForPlayer(did: string, limit = 50): Promise { const [rows] = await this.pool.execute( `SELECT * FROM games WHERE (white_did = ? OR black_did = ?) AND deleted = FALSE ORDER BY last_activity DESC LIMIT ?`, [did, did, String(limit)] ); return rows; } async getPlayerStats(did: string): Promise<{ gamesPlayed: number; wins: number; losses: number; draws: number }> { const base = `FROM games WHERE (white_did = ? OR black_did = ?) AND status = 'completed' AND verified = TRUE AND deleted = FALSE`; const [totalRows] = await this.pool.execute( `SELECT COUNT(*) as count ${base}`, [did, did] ); const [winRows] = await this.pool.execute( `SELECT COUNT(*) as count ${base} AND ((white_did = ? AND result = '1-0') OR (black_did = ? AND result = '0-1'))`, [did, did, did, did] ); const [drawRows] = await this.pool.execute( `SELECT COUNT(*) as count ${base} AND result = '1/2-1/2'`, [did, did] ); const gamesPlayed = totalRows[0].count; const wins = winRows[0].count; const draws = drawRows[0].count; return { gamesPlayed, wins, losses: gamesPlayed - wins - draws, draws }; } async getOpenChallenges(): Promise { const [rows] = await this.pool.execute( `SELECT * FROM challenges WHERE status = 'open' AND deleted = FALSE ORDER BY created_at DESC` ); return rows; } // Anti-spam queries async hasPairPostedRecently(whiteDid: string, blackDid: string, hours: number): Promise { const [rows] = await this.pool.execute( `SELECT COUNT(*) as count FROM games WHERE ((white_did = ? AND black_did = ?) OR (white_did = ? AND black_did = ?)) AND posted = TRUE AND completed_at > DATE_SUB(NOW(), INTERVAL ? HOUR)`, [whiteDid, blackDid, blackDid, whiteDid, hours] ); return rows[0].count > 0; } async playerPostCountToday(did: string): Promise { const [rows] = await this.pool.execute( `SELECT COUNT(*) as count FROM games WHERE (white_did = ? OR black_did = ?) AND posted = TRUE AND completed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)`, [did, did] ); return rows[0].count; } // Health check async isHealthy(): Promise { try { const conn = await this.pool.getConnection(); conn.release(); return true; } catch { return false; } } async close(): Promise { await this.pool.end(); this.log.info('database connections closed'); } }