usenet-indexer/app/services/NntpService.ts

73 lines
2.2 KiB
TypeScript

import nntpConfig from '#config/nntp'
import { NNTP } from "nntp-js";
class NntpService {
private readonly poolSize: number;
private allConnections: Set<any>;
private idleConnections: any[];
private waiters: ((conn: any) => void)[];
private createdCount: number;
constructor(poolSize = 10) {
this.poolSize = poolSize;
this.allConnections = new Set();
this.idleConnections = [];
this.waiters = [];
this.createdCount = 0;
console.log(`NNTP Pool initialized with size ${this.poolSize}`)
}
private async _createConnection() {
// This connection logic is based on the older, working pool implementation.
const conn = new NNTP(nntpConfig.host, nntpConfig.port);
await conn.connect();
if (nntpConfig.user) {
await conn.login(nntpConfig.user, nntpConfig.password?.release());
}
this.allConnections.add(conn);
return conn;
}
public async acquire() {
if (this.idleConnections.length > 0) {
console.log('Reusing existing connection from pool.');
return this.idleConnections.pop();
}
if (this.createdCount < this.poolSize) {
this.createdCount++;
console.log(`Creating new connection (${this.createdCount}/${this.poolSize}).`);
return this._createConnection();
}
console.log(`Pool maxed out at ${this.poolSize}. Waiting for a connection to become available.`);
return new Promise(resolve => this.waiters.push(resolve));
}
public release(conn: any) {
if (this.waiters.length > 0) {
console.log('Releasing connection directly to a waiting task.');
const resolve = this.waiters.shift();
if(resolve) resolve(conn);
} else {
console.log('Returning connection to the idle pool.');
this.idleConnections.push(conn);
}
}
public async shutdown() {
console.log('Shutting down all connections in the pool.');
const shutdownPromises: Promise<any>[] = [];
for (const conn of this.allConnections) {
shutdownPromises.push(conn.quit());
}
await Promise.all(shutdownPromises);
this.allConnections.clear();
this.idleConnections.length = 0;
this.waiters.length = 0;
this.createdCount = 0;
}
}
export default new NntpService();