Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,15 @@ coverage/
.claude
.mcp.json
CLAUDE.md
.swarm
.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/
136 changes: 117 additions & 19 deletions backend/src/modules/auctions/bot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand All @@ -31,8 +34,12 @@ interface BotState {
export class BotService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(BotService.name);
private activeBots = new Map<string, BotState>();
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<UserDocument>,
@InjectModel(Auction.name) private auctionModel: Model<AuctionDocument>,
@InjectModel(Bid.name) private bidModel: Model<BidDocument>,
Expand All @@ -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<void> {
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<void> {
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<void> {
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<void> {
if (this.activeBots.has(auctionId)) {
return;
}
Expand Down Expand Up @@ -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<void> {
try {
const activeAuctions = await this.auctionModel.find({
Expand Down
Loading
Loading