import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { HostConfig } from "../types.js";
import { logError } from "../utils/errors.js";
import { SSHConnectionPoolImpl } from "./ssh-pool.js";
import { SSHService } from "./ssh-service.js";
const runBenchmarks = process.env.RUN_SSH_BENCHMARKS === "true";
const describeBenchmark = runBenchmarks ? describe : describe.skip;
describeBenchmark("SSH Connection Pool Performance Benchmarks", () => {
// Create pool and service for benchmarks
const pool = new SSHConnectionPoolImpl();
const sshService = new SSHService(pool);
const testHost: HostConfig = {
name: "benchmark-host",
host: "localhost",
protocol: "ssh",
sshUser: process.env.USER || "root",
};
beforeAll(async () => {
// Warm up pool
try {
await sshService.executeSSHCommand(testHost, "echo warmup");
} catch {
// Ignore if SSH not available
}
});
afterAll(async () => {
await pool.closeAll();
});
it("should demonstrate significant performance improvement with pooling", async () => {
const iterations = 10;
const command = "echo test";
// Test with pooling (reuse connections)
const pooledStart = Date.now();
for (let i = 0; i < iterations; i++) {
try {
await sshService.executeSSHCommand(testHost, command);
} catch {
return;
}
}
const pooledDuration = Date.now() - pooledStart;
const stats = pool.getStats();
// Verify connection reuse
expect(stats.poolMisses).toBeLessThan(iterations);
expect(stats.poolHits).toBeGreaterThan(0);
// Expected improvement:
// Without pooling: ~250ms * 10 = 2500ms
// With pooling: ~50ms (first) + ~5ms * 9 = ~95ms
// Improvement: ~26x faster
// In test environment with mocks, should be even faster
// Verify average operation time is reasonable
const avgTime = pooledDuration / iterations;
expect(avgTime).toBeLessThan(100); // Should be < 100ms per operation with pooling
});
it("should maintain performance under concurrent load", async () => {
const concurrentRequests = 20;
const command = "echo concurrent";
const start = Date.now();
const promises = Array.from({ length: concurrentRequests }, (_, i) =>
sshService.executeSSHCommand(testHost, `${command} ${i}`).catch((error) => {
logError(error, {
operation: "benchmark",
metadata: { commandIndex: i, command },
});
return null;
})
);
await Promise.allSettled(promises);
const _duration = Date.now() - start;
const stats = pool.getStats();
// With concurrent requests, pool creates connections as needed
// First batch creates up to concurrentRequests connections (20)
// Subsequent requests would reuse connections (pool hits)
expect(stats.totalConnections).toBeLessThanOrEqual(concurrentRequests);
expect(stats.totalConnections).toBeGreaterThan(0);
});
it("should show pool statistics", () => {
const stats = pool.getStats();
expect(stats).toBeDefined();
});
});