brackt/server/socket.ts
Chris Parsons 1ba50828f7
Claude/redesign autodraft queue c4 kp r (#40)
* Redesign autodraft queue system with three-state control and queue-only constraint

Core Logic & Database:
- Add `queue_only` boolean column to `autodraft_settings` (migration 0031)
- Rename autodraft UI states: Off / Next Pick / All Picks (while_on mode maps to All Picks)
- `autoPickForTeam`: respects new `queueOnly` param — skips EV fallback when enabled
- `executeAutoPick`: auto-disables autodraft + emits socket event when queue empties with queueOnly ON (AC3)
- `autodraft-updated` socket event now includes `queueOnly` field

Mobile UI Overhaul:
- Rename "Lobby" tab → "Available" (AC6)
- Add new "Queue" tab to mobile bottom nav with drag-reorder, per-item Draft buttons, and autodraft controls (AC5)
- Controls tab retains commissioner tools, notifications, exit; queue controls moved to Queue tab
- Turn indicator appears on both Available and Queue tabs

Components:
- `AutodraftSettings`: replaces toggle+radio with three-state button group (Off | Next Pick | All Picks) + "Only autodraft from queue" switch (AC1, AC2)
- `QueueSection`: adds `canPick` prop + per-item Draft buttons for instant drafting when on the clock

Desktop (AC4):
- Sidebar QueueSection unchanged in position; gains same three-state controls and Draft buttons

Tests (AC7):
- `autodraft.test.ts`: updated for queueOnly field and socket event shape
- `timer-autodraft.test.ts`: new tests for queue-only constraint, auto-shutoff transitions, and all three autodraft states

https://claude.ai/code/session_01PYhJicAStoJ2u6q6dV1naB

* fix: remove erroneous ?? fallbacks in autodraft socket emissions and add autoPickForTeam tests

- Remove `?? true` default on queueOnly in queue-empty auto-disable socket emit
  (line 488) — was dead code since the column is NOT NULL, but semantically wrong
  and would have caused client-side UI desync if the type ever relaxed
- Remove `?? false` default on the next_pick auto-disable path for consistency
- Add app/models/__tests__/auto-pick.test.ts with 6 tests covering the queueOnly
  constraint: empty queue, all items drafted, partial queue skip, and EV fallback

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add missing queueOnly prop to AutodraftSettings test fixtures

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: rewrite AutodraftSettings tests for three-state button group UI

The component was redesigned from a switch + radio buttons to Off/Next Pick/All Picks
buttons with a separate queue-only Switch toggle. Updated 17 stale tests and added 5
new tests covering the queue-only toggle and the All Picks/Off button interactions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 22:16:26 -08:00

244 lines
8.5 KiB
TypeScript

import { Server as SocketIOServer, Socket } from "socket.io";
import type { Server as HTTPServer } from "http";
import { drizzle } from "drizzle-orm/postgres-js";
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "~/database/schema";
import { eq, and } from "drizzle-orm";
// Lazy-initialized DB for socket-level validation queries (team ownership checks)
let _socketDb: PostgresJsDatabase<typeof schema> | null = null;
function getSocketDb(): PostgresJsDatabase<typeof schema> {
if (!_socketDb) {
const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is required");
_socketDb = drizzle(postgres(url), { schema });
}
return _socketDb;
}
// Socket event types
interface ServerToClientEvents {
"test-message": (data: {
originalMessage: any;
serverResponse: string;
serverTimestamp: string;
socketId: string;
}) => void;
"pick-made": (data: any) => void;
"draft-started": (data: { seasonId: string; currentPickNumber: number }) => void;
"draft-completed": () => void;
"timer-update": (data: {
seasonId: string;
teamId: string;
timeRemaining: number;
currentPickNumber: number;
}) => void;
"autodraft-updated": (data: {
teamId: string;
isEnabled: boolean;
mode: "next_pick" | "while_on";
queueOnly: boolean;
}) => void;
"team-connected": (data: { teamId: string }) => void;
"team-disconnected": (data: { teamId: string }) => void;
"connected-teams-list": (data: { teamIds: string[] }) => void;
"draft-paused": (data: { seasonId: string; paused: boolean }) => void;
"draft-resumed": (data: { seasonId: string; paused: boolean }) => void;
"participant-removed-from-queues": (data: { participantId: string }) => void;
}
interface ClientToServerEvents {
"join-draft": (seasonId: string, teamId?: string) => void;
"leave-draft": (seasonId: string) => void;
"test-event": (data: any) => void;
}
// Global type augmentation
declare global {
var __socketIO: SocketIOServer | undefined;
}
let io: SocketIOServer<ClientToServerEvents, ServerToClientEvents> | null = null;
// Track connected teams per season (in-memory, single-instance only).
// If the server restarts or runs as multiple instances this map resets.
// For multi-instance deployments, replace with a Redis-backed Socket.IO adapter.
const connectedTeams = new Map<string, Set<string>>(); // seasonId -> Set<teamId>
/**
* Initialize Socket.IO server
*/
export function initializeSocketIO(httpServer: HTTPServer): SocketIOServer {
if (io) {
console.log("Socket.IO already initialized");
return io;
}
// Create typed Socket.IO server
io = new SocketIOServer<ClientToServerEvents, ServerToClientEvents>(httpServer, {
// Faster dead-connection detection than the defaults (20s/25s).
// pingTimeout: how long to wait for a pong before declaring the connection dead.
// pingInterval: how often to send a ping.
// Together these detect a crashed server in ~15s instead of ~45s.
// Trade-off: more heartbeat traffic at scale; revisit if server load becomes a concern.
pingTimeout: 5000,
pingInterval: 10000,
cors: process.env.NODE_ENV === "production" && process.env.APP_URL
? {
origin: process.env.APP_URL,
credentials: true,
}
: undefined,
});
// Connection handling
io.on("connection", (socket: Socket<ClientToServerEvents, ServerToClientEvents>) => {
console.log("Client connected:", socket.id);
// Store team ID for this socket
let currentTeamId: string | undefined;
let currentSeasonId: string | undefined;
socket.on("join-draft", async (seasonId: string, teamId?: string) => {
if (!seasonId) {
console.error("No seasonId provided for join-draft");
return;
}
socket.join(`draft-${seasonId}`);
currentSeasonId = seasonId;
console.log(`Socket ${socket.id} joined draft-${seasonId}`);
// If teamId provided, validate it belongs to this season before tracking
if (teamId) {
try {
const db = getSocketDb();
const team = await db.query.teams.findFirst({
where: and(eq(schema.teams.id, teamId), eq(schema.teams.seasonId, seasonId)),
});
if (!team) {
console.warn(`[Socket] join-draft rejected: team ${teamId} does not belong to season ${seasonId}`);
return;
}
} catch (err) {
console.error("[Socket] join-draft team validation failed:", err);
return;
}
currentTeamId = teamId;
socket.join(`team-${teamId}`);
// Initialize the season's connected teams set if it doesn't exist
if (!connectedTeams.has(seasonId)) {
connectedTeams.set(seasonId, new Set());
}
// Get current connected teams for this season
const seasonConnectedTeams = connectedTeams.get(seasonId)!;
// Send the list of already-connected teams to this socket
socket.emit("connected-teams-list", { teamIds: Array.from(seasonConnectedTeams) });
// Add this team to the connected teams set
seasonConnectedTeams.add(teamId);
// Broadcast to everyone else that this team connected
io!.to(`draft-${seasonId}`).emit("team-connected", { teamId });
console.log(`Team ${teamId} connected to draft-${seasonId}. Total connected: ${seasonConnectedTeams.size}`);
}
});
socket.on("leave-draft", (seasonId: string) => {
if (!seasonId) return;
socket.leave(`draft-${seasonId}`);
console.log(`Socket ${socket.id} left draft-${seasonId}`);
// Emit disconnection event if team was tracked
if (currentTeamId) {
socket.leave(`team-${currentTeamId}`);
// Remove team from connected teams tracking
const seasonConnectedTeams = connectedTeams.get(seasonId);
if (seasonConnectedTeams) {
seasonConnectedTeams.delete(currentTeamId);
console.log(`Team ${currentTeamId} removed from tracking. Remaining: ${seasonConnectedTeams.size}`);
// Clean up empty sets
if (seasonConnectedTeams.size === 0) {
connectedTeams.delete(seasonId);
}
}
io!.to(`draft-${seasonId}`).emit("team-disconnected", { teamId: currentTeamId });
console.log(`Team ${currentTeamId} disconnected from draft-${seasonId}`);
}
});
socket.on("test-event", (data: any) => {
console.log("📨 Received test-event from client:", socket.id, data);
socket.emit("test-message", {
originalMessage: data,
serverResponse: "Hello from server!",
serverTimestamp: new Date().toISOString(),
socketId: socket.id,
});
console.log("✅ Sent test-message response to client:", socket.id);
});
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
// Emit disconnection event if team was tracked
if (currentTeamId && currentSeasonId) {
// Remove team from connected teams tracking
const seasonConnectedTeams = connectedTeams.get(currentSeasonId);
if (seasonConnectedTeams) {
seasonConnectedTeams.delete(currentTeamId);
console.log(`Team ${currentTeamId} removed from tracking on disconnect. Remaining: ${seasonConnectedTeams.size}`);
// Clean up empty sets
if (seasonConnectedTeams.size === 0) {
connectedTeams.delete(currentSeasonId);
}
}
io!.to(`draft-${currentSeasonId}`).emit("team-disconnected", { teamId: currentTeamId });
console.log(`Team ${currentTeamId} disconnected from draft-${currentSeasonId}`);
}
});
});
// Store globally for route handlers
global.__socketIO = io;
console.log("Socket.IO initialized");
// Start the draft timer system (async import but don't await)
import("./timer").then(({ startDraftTimerSystem }) => {
startDraftTimerSystem();
}).catch((error) => {
console.error("Failed to start timer system:", error);
});
// Start the daily snapshot system
import("./snapshots").then(({ startSnapshotSystem }) => {
startSnapshotSystem();
}).catch((error) => {
console.error("Failed to start snapshot system:", error);
});
return io;
}
/**
* Get the Socket.IO server instance
*/
export function getSocketIO(): SocketIOServer {
const instance = io || global.__socketIO;
if (!instance) {
throw new Error("Socket.IO not initialized. Call initializeSocketIO first.");
}
return instance;
}