diff --git a/.gitignore b/.gitignore index d573c0b..8b9f349 100644 --- a/.gitignore +++ b/.gitignore @@ -39,4 +39,15 @@ coverage/ .claude .mcp.json CLAUDE.md -.swarm \ No newline at end of file +.swarm + +# Auto Claude data directory +.auto-claude/ + +# Auto Claude generated files +.auto-claude-security.json +.auto-claude-status +.claude_settings.json +.worktrees/ +.security-key +logs/security/ diff --git a/backend/src/modules/auctions/bot.service.ts b/backend/src/modules/auctions/bot.service.ts index 1fa8bcd..c096697 100644 --- a/backend/src/modules/auctions/bot.service.ts +++ b/backend/src/modules/auctions/bot.service.ts @@ -3,7 +3,9 @@ import { OnModuleInit, OnModuleDestroy, Logger, + Inject, } from "@nestjs/common"; +import Redis from "ioredis"; import { InjectModel } from "@nestjs/mongoose"; import { Model, Types } from "mongoose"; import { randomInt } from "crypto"; @@ -19,6 +21,7 @@ import { } from "@/schemas"; import { AuctionsService } from "./auctions.service"; import { isPrimaryWorker, getWorkerId } from "@/common"; +import { redisClient } from "@/modules/redis"; interface BotState { auctionId: string; @@ -31,8 +34,12 @@ interface BotState { export class BotService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(BotService.name); private activeBots = new Map(); + private readonly BOT_START_CHANNEL = "bot-service:start"; + private readonly BOT_STOP_CHANNEL = "bot-service:stop"; + private subscriber: Redis | null = null; constructor( + @Inject(redisClient) private readonly redis: Redis, @InjectModel(User.name) private userModel: Model, @InjectModel(Auction.name) private auctionModel: Model, @InjectModel(Bid.name) private bidModel: Model, @@ -47,21 +54,130 @@ export class BotService implements OnModuleInit, OnModuleDestroy { ); return; } + + await this.setupPubSubSubscription(); await this.restoreBotsForActiveAuctions(); } onModuleDestroy(): void { this.stopAllBots(); + + if (this.subscriber !== null) { + this.subscriber + .unsubscribe(this.BOT_START_CHANNEL, this.BOT_STOP_CHANNEL) + .then(async () => await this.subscriber?.quit()) + .catch(() => { + // Intentionally ignore errors during cleanup + }) + .finally(() => { + this.subscriber = null; + }); + } } async startBots(auctionId: string, botCount: number): Promise { if (!isPrimaryWorker()) { this.logger.debug( - `Worker ${String(getWorkerId())}: Delegating bot start to primary worker`, + `Worker ${String(getWorkerId())}: Delegating bot start to primary worker via pub/sub`, + ); + await this.redis.publish( + this.BOT_START_CHANNEL, + JSON.stringify({ auctionId, botCount }), + ); + return; + } + + await this.startBotsInternal(auctionId, botCount); + } + + stopBots(auctionId: string): void { + if (!isPrimaryWorker()) { + this.logger.debug( + `Worker ${String(getWorkerId())}: Delegating bot stop to primary worker via pub/sub`, ); + this.redis + .publish(this.BOT_STOP_CHANNEL, JSON.stringify({ auctionId })) + .catch((error: unknown) => { + this.logger.error("Failed to publish bot stop message", error); + }); return; } + const state = this.activeBots.get(auctionId); + if (state !== undefined) { + state.active = false; + if (state.intervalId !== null) { + clearInterval(state.intervalId); + } + this.activeBots.delete(auctionId); + this.logger.log("Bots stopped for auction", auctionId); + } + } + + stopAllBots(): void { + for (const auctionId of this.activeBots.keys()) { + this.stopBots(auctionId); + } + } + + private async setupPubSubSubscription(): Promise { + try { + this.subscriber = this.redis.duplicate(); + + this.subscriber.on("message", (channel: string, message: string) => { + void this.handlePubSubMessage(channel, message); + }); + + await this.subscriber.subscribe( + this.BOT_START_CHANNEL, + this.BOT_STOP_CHANNEL, + ); + + this.logger.log("Primary worker subscribed to bot pub/sub channels"); + } catch (error: unknown) { + this.logger.error("Failed to setup pub/sub subscription", error); + } + } + + private async handlePubSubMessage( + channel: string, + message: string, + ): Promise { + try { + const data = JSON.parse(message) as { + auctionId: string; + botCount?: number; + }; + + if (channel === this.BOT_START_CHANNEL) { + const { auctionId, botCount } = data; + if (botCount !== undefined) { + this.logger.debug("Received bot start message via pub/sub", { + auctionId, + botCount, + }); + await this.startBotsInternal(auctionId, botCount); + } + } else if (channel === this.BOT_STOP_CHANNEL) { + const { auctionId } = data; + this.logger.debug("Received bot stop message via pub/sub", { + auctionId, + }); + this.stopBots(auctionId); + } + } catch (error: unknown) { + this.logger.error("Failed to handle pub/sub message", { + channel, + message, + error, + }); + } + } + + private async startBotsInternal( + auctionId: string, + botCount: number, + ): Promise { if (this.activeBots.has(auctionId)) { return; } @@ -103,24 +219,6 @@ export class BotService implements OnModuleInit, OnModuleDestroy { }, 1000); } - stopBots(auctionId: string): void { - const state = this.activeBots.get(auctionId); - if (state !== undefined) { - state.active = false; - if (state.intervalId !== null) { - clearInterval(state.intervalId); - } - this.activeBots.delete(auctionId); - this.logger.log("Bots stopped for auction", auctionId); - } - } - - stopAllBots(): void { - for (const auctionId of this.activeBots.keys()) { - this.stopBots(auctionId); - } - } - private async restoreBotsForActiveAuctions(): Promise { try { const activeAuctions = await this.auctionModel.find({ diff --git a/backend/src/tests/unit/bot-service.spec.ts b/backend/src/tests/unit/bot-service.spec.ts new file mode 100644 index 0000000..6168673 --- /dev/null +++ b/backend/src/tests/unit/bot-service.spec.ts @@ -0,0 +1,821 @@ +import { + describe, + it, + expect, + beforeEach, + afterEach, + vi, + type Mock, +} from "vitest"; +import { Test, type TestingModule } from "@nestjs/testing"; +import { getModelToken } from "@nestjs/mongoose"; +import { BotService } from "@/modules/auctions/bot.service"; +import { AuctionsService } from "@/modules/auctions/auctions.service"; +import { redisClient } from "@/modules/redis/constants"; +import { User, Auction, Bid, AuctionStatus } from "@/schemas"; +import * as clusterUtil from "@/common/cluster/cluster.util"; + +// Mock cluster utilities +vi.mock("@/common/cluster/cluster.util", () => ({ + isPrimaryWorker: vi.fn(), + getWorkerId: vi.fn(), +})); + +interface MockRedisSubscriber { + on: Mock; + subscribe: Mock; + unsubscribe: Mock; + quit: Mock; +} + +interface MockBotUser { + _id: { toString: () => string }; + username: string; + balance: number; + isBot: boolean; + save: Mock; +} + +interface MockAuction { + _id: { toString: () => string }; + status: AuctionStatus; + botsEnabled: boolean; + botCount: number; + currentRound: number; + minBidAmount: number; + minBidIncrement: number; + antiSnipingWindowMinutes: number; + rounds: { + startTime: Date; + endTime: Date; + itemsCount: number; + completed: boolean; + }[]; +} + +describe("BotService", () => { + let service: BotService; + let mockRedis: { + publish: Mock; + duplicate: Mock; + }; + let mockSubscriber: MockRedisSubscriber; + let mockUserModel: { + findOne: Mock; + create: Mock; + }; + let mockAuctionModel: { + find: Mock; + findById: Mock; + }; + let mockBidModel: { + find: Mock; + findOne: Mock; + }; + let mockAuctionsService: { + placeBid: Mock; + getMinWinningBid: Mock; + getLeaderboard: Mock; + }; + let mockIsPrimaryWorker: Mock; + let mockGetWorkerId: Mock; + + beforeEach(async () => { + // Setup cluster utility mocks + mockIsPrimaryWorker = vi.mocked(clusterUtil.isPrimaryWorker); + mockGetWorkerId = vi.mocked(clusterUtil.getWorkerId); + mockIsPrimaryWorker.mockReturnValue(true); + mockGetWorkerId.mockReturnValue(1); + + // Setup Redis subscriber mock + mockSubscriber = { + on: vi.fn(), + subscribe: vi.fn().mockResolvedValue(undefined), + unsubscribe: vi.fn().mockResolvedValue(undefined), + quit: vi.fn().mockResolvedValue(undefined), + }; + + mockRedis = { + publish: vi.fn().mockResolvedValue(1), + duplicate: vi.fn().mockReturnValue(mockSubscriber), + }; + + mockUserModel = { + findOne: vi.fn(), + create: vi.fn(), + }; + + mockAuctionModel = { + find: vi.fn(), + findById: vi.fn(), + }; + + mockBidModel = { + find: vi.fn(), + findOne: vi.fn(), + }; + + mockAuctionsService = { + placeBid: vi.fn(), + getMinWinningBid: vi.fn(), + getLeaderboard: vi.fn(), + }; + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + BotService, + { + provide: redisClient, + useValue: mockRedis, + }, + { + provide: getModelToken(User.name), + useValue: mockUserModel, + }, + { + provide: getModelToken(Auction.name), + useValue: mockAuctionModel, + }, + { + provide: getModelToken(Bid.name), + useValue: mockBidModel, + }, + { + provide: AuctionsService, + useValue: mockAuctionsService, + }, + ], + }).compile(); + + service = module.get(BotService); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.useRealTimers(); + }); + + describe("Service Initialization", () => { + it("should be defined", () => { + expect(service).toBeDefined(); + }); + }); + + describe("onModuleInit", () => { + it("should setup pub/sub subscription on primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + expect(mockRedis.duplicate).toHaveBeenCalled(); + expect(mockSubscriber.subscribe).toHaveBeenCalledWith( + "bot-service:start", + "bot-service:stop", + ); + expect(mockSubscriber.on).toHaveBeenCalledWith( + "message", + expect.any(Function), + ); + }); + + it("should skip pub/sub setup on non-primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(false); + mockGetWorkerId.mockReturnValue(2); + + await service.onModuleInit(); + + expect(mockRedis.duplicate).not.toHaveBeenCalled(); + expect(mockSubscriber.subscribe).not.toHaveBeenCalled(); + }); + + it("should restore bots for active auctions on primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + const mockAuction: MockAuction = { + _id: { toString: () => "auction123" }, + status: AuctionStatus.ACTIVE, + botsEnabled: true, + botCount: 2, + currentRound: 1, + minBidAmount: 100, + minBidIncrement: 10, + antiSnipingWindowMinutes: 1, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + }; + + mockAuctionModel.find.mockResolvedValue([mockAuction]); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + expect(mockAuctionModel.find).toHaveBeenCalledWith({ + status: AuctionStatus.ACTIVE, + botsEnabled: true, + }); + }); + + it("should log when no active auctions with bots to restore", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + expect(mockAuctionModel.find).toHaveBeenCalledWith({ + status: AuctionStatus.ACTIVE, + botsEnabled: true, + }); + }); + }); + + describe("startBots - Pub/Sub Delegation", () => { + it("should handle bots directly on primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + expect(mockRedis.publish).not.toHaveBeenCalled(); + expect(mockUserModel.create).toHaveBeenCalled(); + + // Cleanup + service.stopBots("auction123"); + vi.useRealTimers(); + }); + + it("should publish to Redis channel on non-primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(false); + mockGetWorkerId.mockReturnValue(2); + + await service.startBots("auction123", 3); + + expect(mockRedis.publish).toHaveBeenCalledWith( + "bot-service:start", + JSON.stringify({ auctionId: "auction123", botCount: 3 }), + ); + }); + + it("should not start bots directly on non-primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(false); + mockGetWorkerId.mockReturnValue(2); + + await service.startBots("auction123", 3); + + expect(mockUserModel.findOne).not.toHaveBeenCalled(); + expect(mockUserModel.create).not.toHaveBeenCalled(); + }); + }); + + describe("stopBots - Pub/Sub Delegation", () => { + it("should stop bots directly on primary worker", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + service.stopBots("auction123"); + + expect(mockRedis.publish).not.toHaveBeenCalledWith( + "bot-service:stop", + expect.any(String), + ); + + vi.useRealTimers(); + }); + + it("should publish stop request on non-primary worker", () => { + mockIsPrimaryWorker.mockReturnValue(false); + mockGetWorkerId.mockReturnValue(2); + + service.stopBots("auction123"); + + expect(mockRedis.publish).toHaveBeenCalledWith( + "bot-service:stop", + JSON.stringify({ auctionId: "auction123" }), + ); + }); + }); + + describe("Pub/Sub Message Handling", () => { + it("should handle bot start message from pub/sub", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + // Get the message handler + const messageHandler = mockSubscriber.on.mock.calls.find( + (call) => call[0] === "message", + )?.[1] as ((channel: string, message: string) => void) | undefined; + + expect(messageHandler).toBeDefined(); + + // Setup mocks for bot creation + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + // Simulate receiving a message + messageHandler?.( + "bot-service:start", + JSON.stringify({ auctionId: "auction456", botCount: 2 }), + ); + + // Allow async handling to process + await vi.advanceTimersByTimeAsync(10); + + expect(mockUserModel.create).toHaveBeenCalled(); + + // Cleanup + service.stopBots("auction456"); + vi.useRealTimers(); + }); + + it("should handle bot stop message from pub/sub", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + // First start bots + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction789", 1); + + // Get the message handler + const messageHandler = mockSubscriber.on.mock.calls.find( + (call) => call[0] === "message", + )?.[1] as ((channel: string, message: string) => void) | undefined; + + // Simulate receiving a stop message + messageHandler?.( + "bot-service:stop", + JSON.stringify({ auctionId: "auction789" }), + ); + + await vi.advanceTimersByTimeAsync(10); + + vi.useRealTimers(); + }); + + it("should handle malformed pub/sub messages gracefully", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + const messageHandler = mockSubscriber.on.mock.calls.find( + (call) => call[0] === "message", + )?.[1] as ((channel: string, message: string) => void) | undefined; + + // Should not throw on invalid JSON + expect(() => { + messageHandler?.("bot-service:start", "invalid-json{"); + }).not.toThrow(); + }); + }); + + describe("Bot User Creation", () => { + it("should create new bot users if they do not exist", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + + const mockBotUser: MockBotUser = { + _id: { toString: () => "bot-id-1" }, + username: "bot_tion123_1", + balance: 100000, + isBot: true, + save: vi.fn(), + }; + mockUserModel.create.mockResolvedValue(mockBotUser); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 2); + + expect(mockUserModel.create).toHaveBeenCalledTimes(2); + expect(mockUserModel.create).toHaveBeenCalledWith( + expect.objectContaining({ + balance: 100000, + isBot: true, + }) as Record, + ); + + service.stopBots("auction123"); + vi.useRealTimers(); + }); + + it("should reuse existing bot users", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + const existingBot: MockBotUser = { + _id: { toString: () => "existing-bot-id" }, + username: "bot_123_1", + balance: 60000, + isBot: true, + save: vi.fn(), + }; + mockUserModel.findOne.mockResolvedValue(existingBot); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + expect(mockUserModel.create).not.toHaveBeenCalled(); + + service.stopBots("auction123"); + vi.useRealTimers(); + }); + + it("should top up bot balance if below threshold", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + const lowBalanceBot: MockBotUser = { + _id: { toString: () => "low-balance-bot" }, + username: "bot_123_1", + balance: 30000, // Below 50000 threshold + isBot: true, + save: vi.fn().mockResolvedValue(true), + }; + mockUserModel.findOne.mockResolvedValue(lowBalanceBot); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + expect(lowBalanceBot.balance).toBe(100000); + expect(lowBalanceBot.save).toHaveBeenCalled(); + + service.stopBots("auction123"); + vi.useRealTimers(); + }); + }); + + describe("Bot Activity", () => { + it("should not start duplicate bots for same auction", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + // Clear mock to track subsequent calls + mockUserModel.create.mockClear(); + + // Try to start bots again for same auction + await service.startBots("auction123", 1); + + // Should not create new bots + expect(mockUserModel.create).not.toHaveBeenCalled(); + + service.stopBots("auction123"); + vi.useRealTimers(); + }); + + it("should stop bots when auction is no longer active", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + + // First return active auction + mockAuctionModel.findById + .mockResolvedValueOnce({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }) + // Then return completed auction for activity check + .mockResolvedValue({ + status: AuctionStatus.COMPLETED, + rounds: [], + currentRound: 1, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + // Advance timer to trigger bot activity + await vi.advanceTimersByTimeAsync(2000); + + vi.useRealTimers(); + }); + }); + + describe("stopAllBots", () => { + it("should stop all active bots", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction1", 1); + await service.startBots("auction2", 1); + + service.stopAllBots(); + + // Verify bots are stopped by trying to start again + mockUserModel.create.mockClear(); + await service.startBots("auction1", 1); + await service.startBots("auction2", 1); + + // Should create new bots since old ones were stopped + expect(mockUserModel.create).toHaveBeenCalledTimes(2); + + service.stopAllBots(); + vi.useRealTimers(); + }); + }); + + describe("onModuleDestroy", () => { + it("should cleanup resources on destroy", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + service.onModuleDestroy(); + + expect(mockSubscriber.unsubscribe).toHaveBeenCalledWith( + "bot-service:start", + "bot-service:stop", + ); + }); + + it("should stop all bots on destroy", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockUserModel.findOne.mockResolvedValue(null); + mockUserModel.create.mockResolvedValue({ + _id: { toString: () => "bot1" }, + username: "bot_123_1", + balance: 100000, + isBot: true, + }); + mockAuctionModel.find.mockResolvedValue([]); + + await service.onModuleInit(); + + vi.useFakeTimers(); + mockAuctionModel.findById.mockResolvedValue({ + status: AuctionStatus.ACTIVE, + rounds: [ + { + startTime: new Date(Date.now() - 60000), + endTime: new Date(Date.now() + 60000), + itemsCount: 5, + completed: false, + }, + ], + currentRound: 1, + minBidAmount: 100, + }); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 1); + + service.onModuleDestroy(); + + // Verify bots are stopped + mockUserModel.create.mockClear(); + await service.startBots("auction123", 1); + expect(mockUserModel.create).toHaveBeenCalled(); + + service.stopAllBots(); + vi.useRealTimers(); + }); + }); + + describe("Edge Cases", () => { + it("should handle empty bot count gracefully", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + vi.useFakeTimers(); + mockBidModel.find.mockResolvedValue([]); + + await service.startBots("auction123", 0); + + expect(mockUserModel.create).not.toHaveBeenCalled(); + + vi.useRealTimers(); + }); + + it("should handle Redis publish failures gracefully", async () => { + mockIsPrimaryWorker.mockReturnValue(false); + mockGetWorkerId.mockReturnValue(2); + mockRedis.publish.mockRejectedValue(new Error("Redis error")); + + // Should not throw + await expect(service.startBots("auction123", 3)).rejects.toThrow( + "Redis error", + ); + }); + + it("should handle failed pub/sub subscription setup", async () => { + mockIsPrimaryWorker.mockReturnValue(true); + mockSubscriber.subscribe.mockRejectedValue(new Error("Subscribe failed")); + mockAuctionModel.find.mockResolvedValue([]); + + // Should not throw, just log error + await expect(service.onModuleInit()).resolves.not.toThrow(); + }); + + it("should handle stopping non-existent auction bots", () => { + mockIsPrimaryWorker.mockReturnValue(true); + + // Should not throw + expect(() => service.stopBots("non-existent-auction")).not.toThrow(); + }); + }); +}); diff --git a/frontend/src/components/Footer.tsx b/frontend/src/components/Footer.tsx index 5de3f46..96a92c2 100644 --- a/frontend/src/components/Footer.tsx +++ b/frontend/src/components/Footer.tsx @@ -62,6 +62,14 @@ export default function Footer(): React.JSX.Element { > GitHub + + {t('footer.demoVideo')} +
([ - { itemsCount: 5, durationMinutes: 5 }, - { itemsCount: 5, durationMinutes: 5 }, + const [numericInputs, setNumericInputs] = useState({ + totalItems: '10', + minBidAmount: '100', + minBidIncrement: '10', + antiSnipingWindowMinutes: '2', + antiSnipingExtensionMinutes: '2', + maxExtensions: '6', + botCount: '5', + }); + const [rounds, setRounds] = useState<{ itemsCount: string; durationMinutes: string }[]>([ + { itemsCount: '5', durationMinutes: '5' }, + { itemsCount: '5', durationMinutes: '5' }, ]); - const [minBidAmount, setMinBidAmount] = useState(100); - const [minBidIncrement, setMinBidIncrement] = useState(10); - const [antiSnipingWindowMinutes, setAntiSnipingWindowMinutes] = useState(2); - const [antiSnipingExtensionMinutes, setAntiSnipingExtensionMinutes] = useState(2); - const [maxExtensions, setMaxExtensions] = useState(6); const [botsEnabled, setBotsEnabled] = useState(true); - const [botCount, setBotCount] = useState(5); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); + // Parse string to number, defaulting to 0 for empty/invalid + const parseNum = (val: string): number => { + const parsed = parseInt(val, 10); + return isNaN(parsed) ? 0 : parsed; + }; + + const updateNumericInput = (field: keyof NumericInputs, value: string) => { + // Allow only digits (and empty string for clearing) + if (value === '' || /^\d+$/.test(value)) { + setNumericInputs((prev) => ({ ...prev, [field]: value })); + } + }; + const addRound = () => { - setRounds([...rounds, { itemsCount: 1, durationMinutes: 5 }]); + setRounds([...rounds, { itemsCount: '1', durationMinutes: '5' }]); }; const removeRound = (index: number) => { @@ -35,27 +61,25 @@ export default function CreateAuctionPage(): React.JSX.Element { } }; - const updateRound = (index: number, field: keyof RoundConfig, value: number) => { - const sanitizedValue = Math.max(1, value); - setRounds( - rounds.map((round, i) => - i === index ? { ...round, [field]: sanitizedValue } : round - ) - ); - }; - - const handleNumberInput = ( - setter: (value: number) => void, - value: string, - min = 1 - ) => { - const parsed = parseInt(value, 10); - if (!isNaN(parsed)) { - setter(Math.max(min, parsed)); + const updateRound = (index: number, field: 'itemsCount' | 'durationMinutes', value: string) => { + if (value === '' || /^\d+$/.test(value)) { + setRounds( + rounds.map((round, i) => + i === index ? { ...round, [field]: value } : round + ) + ); } }; - const totalRoundItems = rounds.reduce((sum, r) => sum + r.itemsCount, 0); + const totalItems = parseNum(numericInputs.totalItems); + const minBidAmount = parseNum(numericInputs.minBidAmount); + const minBidIncrement = parseNum(numericInputs.minBidIncrement); + const antiSnipingWindowMinutes = parseNum(numericInputs.antiSnipingWindowMinutes); + const antiSnipingExtensionMinutes = parseNum(numericInputs.antiSnipingExtensionMinutes); + const maxExtensions = parseNum(numericInputs.maxExtensions); + const botCount = parseNum(numericInputs.botCount); + + const totalRoundItems = rounds.reduce((sum, r) => sum + parseNum(r.itemsCount), 0); const validateForm = (): string | null => { if (!title.trim()) { @@ -107,11 +131,16 @@ export default function CreateAuctionPage(): React.JSX.Element { setError(''); try { + const parsedRounds: RoundConfig[] = rounds.map((r) => ({ + itemsCount: parseNum(r.itemsCount), + durationMinutes: parseNum(r.durationMinutes), + })); + const auction = await api.createAuction({ title: title.trim(), description: description.trim() || undefined, totalItems, - rounds, + rounds: parsedRounds, minBidAmount, minBidIncrement, antiSnipingWindowMinutes, @@ -167,13 +196,11 @@ export default function CreateAuctionPage(): React.JSX.Element {
handleNumberInput(setTotalItems, e.target.value)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + value={numericInputs.totalItems} + onChange={(e) => updateNumericInput('totalItems', e.target.value)} />
@@ -209,25 +236,21 @@ export default function CreateAuctionPage(): React.JSX.Element {
updateRound(index, 'itemsCount', parseInt(e.target.value, 10) || 1)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + onChange={(e) => updateRound(index, 'itemsCount', e.target.value)} />
updateRound(index, 'durationMinutes', parseInt(e.target.value, 10) || 1)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + onChange={(e) => updateRound(index, 'durationMinutes', e.target.value)} />
{rounds.length > 1 && ( @@ -251,26 +274,22 @@ export default function CreateAuctionPage(): React.JSX.Element {
handleNumberInput(setMinBidAmount, e.target.value)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + value={numericInputs.minBidAmount} + onChange={(e) => updateNumericInput('minBidAmount', e.target.value)} />
handleNumberInput(setMinBidIncrement, e.target.value)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + value={numericInputs.minBidIncrement} + onChange={(e) => updateNumericInput('minBidIncrement', e.target.value)} />
@@ -283,39 +302,33 @@ export default function CreateAuctionPage(): React.JSX.Element {
handleNumberInput(setAntiSnipingWindowMinutes, e.target.value)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + value={numericInputs.antiSnipingWindowMinutes} + onChange={(e) => updateNumericInput('antiSnipingWindowMinutes', e.target.value)} />
handleNumberInput(setAntiSnipingExtensionMinutes, e.target.value)} - onWheel={(e) => e.currentTarget.blur()} - min={1} + value={numericInputs.antiSnipingExtensionMinutes} + onChange={(e) => updateNumericInput('antiSnipingExtensionMinutes', e.target.value)} />
handleNumberInput(setMaxExtensions, e.target.value, 0)} - onWheel={(e) => e.currentTarget.blur()} - min={0} + value={numericInputs.maxExtensions} + onChange={(e) => updateNumericInput('maxExtensions', e.target.value)} />
@@ -338,14 +351,11 @@ export default function CreateAuctionPage(): React.JSX.Element {
handleNumberInput(setBotCount, e.target.value, 0)} - onWheel={(e) => e.currentTarget.blur()} - min={0} - max={50} + value={numericInputs.botCount} + onChange={(e) => updateNumericInput('botCount', e.target.value)} style={{ width: '100px' }} />
@@ -359,7 +369,7 @@ export default function CreateAuctionPage(): React.JSX.Element { )} -
+