import { ClientConnection } from "./connection.js";
import type { ReconnectOptions } from "./reconnect.js";
import type { ServerConfig } from "../config/schema.js";
import type { ConnectionStatus } from "../types.js";
import logger from "../utils/logger.js";
export class ServerManager {
private connections = new Map<string, ClientConnection>();
private groups: Record<string, string[]>;
constructor(
servers: Record<string, ServerConfig>,
groups: Record<string, string[]>,
reconnectOptions: ReconnectOptions,
idleTimeoutMs = 0
) {
this.groups = groups;
for (const [id, config] of Object.entries(servers)) {
this.connections.set(id, new ClientConnection(id, config, reconnectOptions, idleTimeoutMs));
}
}
getConnection(id: string): ClientConnection | undefined {
return this.connections.get(id);
}
getConnections(ids?: string[]): Map<string, ClientConnection> {
if (!ids) {
return new Map(this.connections);
}
const filtered = new Map<string, ClientConnection>();
for (const id of ids) {
const conn = this.connections.get(id);
if (conn) {
filtered.set(id, conn);
}
}
return filtered;
}
getGroupConnections(groupId: string): Map<string, ClientConnection> | undefined {
const memberIds = this.groups[groupId];
if (!memberIds) return undefined;
return this.getConnections(memberIds);
}
getGroupIds(): string[] {
return Object.keys(this.groups);
}
getServerIds(): string[] {
return [...this.connections.keys()];
}
getAllStatuses(): ConnectionStatus[] {
return [...this.connections.values()].map((c) => c.status);
}
async closeAll(): Promise<void> {
logger.info("Closing all server connections...");
await Promise.allSettled(
[...this.connections.values()].map((conn) => conn.close())
);
logger.info("All connections closed");
}
}