Compare commits

...

8 Commits

6 changed files with 94 additions and 25 deletions

View File

@ -1,5 +1,30 @@
# Changelog # Changelog
## 2025-02-21 - 3.9.3 - fix(PortProxy)
Fix handling of optional outgoing socket in PortProxy
- Refactored the cleanUpSockets function to correctly handle cases where the outgoing socket may be undefined.
- Ensured correct handling of socket events with non-null assertions where applicable.
- Improved robustness in connection establishment and cleanup processes.
## 2025-02-21 - 3.9.2 - fix(PortProxy)
Improve timeout handling for port proxy connections
- Added console logging for both incoming and outgoing side timeouts in the PortProxy class.
- Updated the timeout event handlers to ensure proper cleanup of connections.
## 2025-02-21 - 3.9.1 - fix(dependencies)
Ensure correct ordering of dependencies and improve logging format.
- Reorder dependencies in package.json for better readability.
- Use pretty-ms for displaying time durations in logs.
## 2025-02-21 - 3.9.0 - feat(smartproxy.portproxy)
Add logging of connection durations to PortProxy
- Track start times for incoming and outgoing connections.
- Log duration of longest running incoming and outgoing connections every 10 seconds.
## 2025-02-21 - 3.8.1 - fix(plugins) ## 2025-02-21 - 3.8.1 - fix(plugins)
Simplified plugin import structure across codebase Simplified plugin import structure across codebase

View File

@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartproxy", "name": "@push.rocks/smartproxy",
"version": "3.8.1", "version": "3.9.3",
"private": false, "private": false,
"description": "a proxy for handling high workloads of proxying", "description": "a proxy for handling high workloads of proxying",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
@ -29,10 +29,11 @@
"@push.rocks/smartrequest": "^2.0.23", "@push.rocks/smartrequest": "^2.0.23",
"@push.rocks/smartstring": "^4.0.15", "@push.rocks/smartstring": "^4.0.15",
"@tsclass/tsclass": "^4.4.0", "@tsclass/tsclass": "^4.4.0",
"@types/minimatch": "^5.1.2",
"@types/ws": "^8.5.14", "@types/ws": "^8.5.14",
"ws": "^8.18.0",
"minimatch": "^9.0.3", "minimatch": "^9.0.3",
"@types/minimatch": "^5.1.2" "pretty-ms": "^9.2.0",
"ws": "^8.18.0"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",

3
pnpm-lock.yaml generated
View File

@ -35,6 +35,9 @@ importers:
minimatch: minimatch:
specifier: ^9.0.3 specifier: ^9.0.3
version: 9.0.5 version: 9.0.5
pretty-ms:
specifier: ^9.2.0
version: 9.2.0
ws: ws:
specifier: ^8.18.0 specifier: ^8.18.0
version: 8.18.0 version: 8.18.0

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartproxy', name: '@push.rocks/smartproxy',
version: '3.8.1', version: '3.9.3',
description: 'a proxy for handling high workloads of proxying' description: 'a proxy for handling high workloads of proxying'
} }

View File

@ -22,8 +22,9 @@ import * as smartstring from '@push.rocks/smartstring';
export { lik, smartdelay, smartrequest, smartpromise, smartstring }; export { lik, smartdelay, smartrequest, smartpromise, smartstring };
// third party scope // third party scope
import prettyMs from 'pretty-ms';
import * as ws from 'ws'; import * as ws from 'ws';
import wsDefault from 'ws'; import wsDefault from 'ws';
import { minimatch } from 'minimatch'; import { minimatch } from 'minimatch';
export { wsDefault, ws, minimatch }; export { prettyMs, ws, wsDefault, minimatch };

View File

@ -117,6 +117,10 @@ export class PortProxy {
settings: IProxySettings; settings: IProxySettings;
// Track active incoming connections // Track active incoming connections
private activeConnections: Set<plugins.net.Socket> = new Set(); private activeConnections: Set<plugins.net.Socket> = new Set();
// Record start times for incoming connections
private incomingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
// Record start times for outgoing connections
private outgoingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
private connectionLogger: NodeJS.Timeout | null = null; private connectionLogger: NodeJS.Timeout | null = null;
constructor(settings: IProxySettings) { constructor(settings: IProxySettings) {
@ -127,15 +131,18 @@ export class PortProxy {
} }
public async start() { public async start() {
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => { // Adjusted cleanUpSockets to allow an optional outgoing socket.
const cleanUpSockets = (from: plugins.net.Socket, to?: plugins.net.Socket) => {
from.end(); from.end();
to.end();
from.removeAllListeners(); from.removeAllListeners();
to.removeAllListeners();
from.unpipe(); from.unpipe();
to.unpipe();
from.destroy(); from.destroy();
to.destroy(); if (to) {
to.end();
to.removeAllListeners();
to.unpipe();
to.destroy();
}
}; };
const normalizeIP = (ip: string): string[] => { const normalizeIP = (ip: string): string[] => {
@ -168,6 +175,11 @@ export class PortProxy {
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => { this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
const remoteIP = socket.remoteAddress || ''; const remoteIP = socket.remoteAddress || '';
// Record start time for the incoming connection.
this.activeConnections.add(socket);
this.incomingConnectionTimes.set(socket, Date.now());
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
// Flag to detect if we've received the first data chunk. // Flag to detect if we've received the first data chunk.
let initialDataReceived = false; let initialDataReceived = false;
@ -180,16 +192,16 @@ export class PortProxy {
} }
}); });
// Track the new incoming connection.
this.activeConnections.add(socket);
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
// Flag to ensure cleanup happens only once. // Flag to ensure cleanup happens only once.
let connectionClosed = false; let connectionClosed = false;
const cleanupOnce = () => { const cleanupOnce = () => {
if (!connectionClosed) { if (!connectionClosed) {
connectionClosed = true; connectionClosed = true;
cleanUpSockets(socket, to); cleanUpSockets(socket, to || undefined);
this.incomingConnectionTimes.delete(socket);
if (to) {
this.outgoingConnectionTimes.delete(to);
}
if (this.activeConnections.has(socket)) { if (this.activeConnections.has(socket)) {
this.activeConnections.delete(socket); this.activeConnections.delete(socket);
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`); console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
@ -197,7 +209,8 @@ export class PortProxy {
} }
}; };
let to: plugins.net.Socket; // Declare the outgoing connection as possibly null.
let to: plugins.net.Socket | null = null;
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => { const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
const code = (err as any).code; const code = (err as any).code;
@ -253,6 +266,10 @@ export class PortProxy {
// Establish outgoing connection. // Establish outgoing connection.
to = plugins.net.connect(connectionOptions); to = plugins.net.connect(connectionOptions);
// Record start time for the outgoing connection.
if (to) {
this.outgoingConnectionTimes.set(to, Date.now());
}
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`); console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
// Push back the initial chunk if provided. // Push back the initial chunk if provided.
@ -260,18 +277,25 @@ export class PortProxy {
socket.unshift(initialChunk); socket.unshift(initialChunk);
} }
socket.setTimeout(120000); socket.setTimeout(120000);
socket.pipe(to); // Since 'to' is not null here, we can use the non-null assertion.
to.pipe(socket); socket.pipe(to!);
to!.pipe(socket);
// Attach error and close handlers for both sockets. // Attach error and close handlers for both sockets.
socket.on('error', handleError('incoming')); socket.on('error', handleError('incoming'));
to.on('error', handleError('outgoing')); to!.on('error', handleError('outgoing'));
socket.on('close', handleClose('incoming')); socket.on('close', handleClose('incoming'));
to.on('close', handleClose('outgoing')); to!.on('close', handleClose('outgoing'));
socket.on('timeout', handleError('incoming')); socket.on('timeout', () => {
to.on('timeout', handleError('outgoing')); console.log(`Timeout on incoming side from ${remoteIP}`);
cleanupOnce();
});
to!.on('timeout', () => {
console.log(`Timeout on outgoing side from ${remoteIP}`);
cleanupOnce();
});
socket.on('end', handleClose('incoming')); socket.on('end', handleClose('incoming'));
to.on('end', handleClose('outgoing')); to!.on('end', handleClose('outgoing'));
}; };
// For SNI-enabled connections, peek at the first chunk. // For SNI-enabled connections, peek at the first chunk.
@ -301,9 +325,24 @@ export class PortProxy {
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`); console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
}); });
// Log active connection count every 10 seconds. // Log active connection count and longest running connections every 10 seconds.
this.connectionLogger = setInterval(() => { this.connectionLogger = setInterval(() => {
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}`); const now = Date.now();
let maxIncoming = 0;
for (const startTime of this.incomingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxIncoming) {
maxIncoming = duration;
}
}
let maxOutgoing = 0;
for (const startTime of this.outgoingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxOutgoing) {
maxOutgoing = duration;
}
}
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}. Longest running incoming: ${plugins.prettyMs(maxIncoming)}, outgoing: ${plugins.prettyMs(maxOutgoing)}`);
}, 10000); }, 10000);
} }