Files
smartnetwork/readme.md

429 lines
13 KiB
Markdown

# @push.rocks/smartnetwork 🌐
Comprehensive network diagnostics and utilities for Node.js applications
## 🚀 Install
To install `@push.rocks/smartnetwork`, run the following command in your terminal:
```bash
pnpm install @push.rocks/smartnetwork --save
```
## 🎯 Overview
**@push.rocks/smartnetwork** is your Swiss Army knife for network diagnostics in Node.js. Whether you're building network monitoring tools, implementing health checks, or just need to debug connectivity issues, this library has you covered with a clean, promise-based API.
### ✨ Key Features
- **🏎️ Speed Testing** - Measure download/upload speeds using Cloudflare's infrastructure
- **🔌 Port Management** - Check local/remote port availability, find free ports (sequential or random)
- **📡 Connectivity Testing** - Ping hosts, trace routes, check endpoints
- **🌍 DNS Operations** - Resolve A, AAAA, and MX records with smart local/remote resolution
- **🔍 Network Discovery** - Get network interfaces, gateways, public IPs
- **⚡ Performance Caching** - Built-in caching for expensive operations
- **🔧 Plugin Architecture** - Extend functionality with custom plugins
- **📝 Full TypeScript Support** - Complete type definitions included
## 💻 Usage
### Basic Setup
First, import and initialize SmartNetwork:
```typescript
import { SmartNetwork } from '@push.rocks/smartnetwork';
// Basic instance
const network = new SmartNetwork();
// With caching enabled (60 seconds TTL)
const cachedNetwork = new SmartNetwork({ cacheTtl: 60000 });
```
### 🏎️ Network Speed Testing
Measure your network performance using Cloudflare's global infrastructure:
```typescript
const speedTest = async () => {
// Quick speed test
const result = await network.getSpeed();
console.log(`Download: ${result.downloadSpeed} Mbps`);
console.log(`Upload: ${result.uploadSpeed} Mbps`);
// Advanced configuration
const advancedResult = await network.getSpeed({
parallelStreams: 3, // Number of concurrent connections
duration: 5 // Test duration in seconds
});
console.log(`Download: ${advancedResult.downloadSpeed} Mbps`);
console.log(`Upload: ${advancedResult.uploadSpeed} Mbps`);
};
```
### 🔌 Port Management
#### Check Local Port Availability
Verify if a port is available on your local machine (checks both IPv4 and IPv6):
```typescript
const checkLocalPort = async (port: number) => {
const isUnused = await network.isLocalPortUnused(port);
if (isUnused) {
console.log(`✅ Port ${port} is available`);
} else {
console.log(`❌ Port ${port} is in use`);
}
};
await checkLocalPort(8080);
```
#### Find Free Port in Range
Automatically discover available ports:
```typescript
const findFreePort = async () => {
// Find a free port between 3000 and 3100 (sequential - returns first available)
const freePort = await network.findFreePort(3000, 3100);
if (freePort) {
console.log(`🎉 Found free port: ${freePort}`);
} else {
console.log('😢 No free ports available in range');
}
// Find a random free port in range (useful to avoid port conflicts)
const randomPort = await network.findFreePort(3000, 3100, { randomize: true });
console.log(`🎲 Random free port: ${randomPort}`);
// Exclude specific ports from the search
const portWithExclusions = await network.findFreePort(3000, 3100, {
exclude: [3000, 3001, 3005] // Skip these ports even if they're free
});
console.log(`🚫 Free port (excluding specific ports): ${portWithExclusions}`);
// Combine randomize with exclude options
const randomWithExclusions = await network.findFreePort(3000, 3100, {
randomize: true,
exclude: [3000, 3001, 3005]
});
console.log(`🎲🚫 Random free port (with exclusions): ${randomWithExclusions}`);
};
```
#### Check Remote Port Availability
Test if services are accessible on remote servers:
```typescript
// Method 1: Using "host:port" syntax
const isOpen1 = await network.isRemotePortAvailable('example.com:443');
// Method 2: Using separate host and port
const isOpen2 = await network.isRemotePortAvailable('example.com', 443);
// Method 3: With advanced options
const isOpen3 = await network.isRemotePortAvailable('example.com', {
port: 443,
protocol: 'tcp', // Only TCP is supported
retries: 3, // Number of connection attempts
timeout: 5000 // Timeout per attempt in ms
});
// Note: UDP is not supported
try {
await network.isRemotePortAvailable('example.com', {
port: 53,
protocol: 'udp'
});
} catch (e) {
console.error('UDP not supported:', e.code); // ENOTSUP
}
```
### 📡 Network Connectivity
#### Ping Operations
Test connectivity and measure latency:
```typescript
// Simple ping
const pingResult = await network.ping('google.com');
console.log(`Host alive: ${pingResult.alive}`);
console.log(`RTT: ${pingResult.time} ms`);
// Detailed ping statistics
const pingStats = await network.ping('google.com', {
count: 5, // Number of pings
timeout: 1000 // Timeout per ping in ms
});
console.log(`📊 Ping Statistics:`);
console.log(` Packet loss: ${pingStats.packetLoss}%`);
console.log(` Min: ${pingStats.min} ms`);
console.log(` Max: ${pingStats.max} ms`);
console.log(` Avg: ${pingStats.avg.toFixed(2)} ms`);
console.log(` Stddev: ${pingStats.stddev.toFixed(2)} ms`);
```
#### Traceroute
Analyze network paths hop-by-hop:
```typescript
const hops = await network.traceroute('google.com', {
maxHops: 10, // Maximum number of hops
timeout: 5000 // Timeout in ms
});
console.log('🛤️ Route to destination:');
hops.forEach(hop => {
const rtt = hop.rtt === null ? '*' : `${hop.rtt} ms`;
console.log(` ${hop.ttl}\t${hop.ip}\t${rtt}`);
});
```
*Note: Falls back to a single-hop stub if the `traceroute` binary is unavailable.*
### 🌍 DNS Operations
Resolve various DNS record types using @push.rocks/smartdns with intelligent resolution strategy:
```typescript
const dnsRecords = await network.resolveDns('example.com');
console.log('🔍 DNS Records:');
console.log(' A records:', dnsRecords.A); // IPv4 addresses
console.log(' AAAA records:', dnsRecords.AAAA); // IPv6 addresses
// MX records include priority
dnsRecords.MX.forEach(mx => {
console.log(` 📧 Mail server: ${mx.exchange} (priority: ${mx.priority})`);
});
// Properly handles local hostnames (localhost, etc.)
const localDns = await network.resolveDns('localhost');
console.log(' Localhost:', localDns.A); // Returns ['127.0.0.1']
```
*DNS resolution uses a `prefer-system` strategy: tries system resolver first (respects /etc/hosts and local DNS), with automatic fallback to Cloudflare DoH for external domains.*
### 🏥 HTTP/HTTPS Health Checks
Monitor endpoint availability and response times:
```typescript
const health = await network.checkEndpoint('https://api.example.com/health', {
timeout: 5000 // Request timeout in ms
});
console.log(`🩺 Endpoint Health:`);
console.log(` Status: ${health.status}`);
console.log(` RTT: ${health.rtt} ms`);
console.log(` Headers:`, health.headers);
```
### 🖥️ Network Interface Information
#### Get All Network Interfaces
List all network adapters on the system:
```typescript
const gateways = await network.getGateways();
Object.entries(gateways).forEach(([name, interfaces]) => {
console.log(`🔌 Interface: ${name}`);
interfaces.forEach(iface => {
console.log(` ${iface.family}: ${iface.address}`);
console.log(` Netmask: ${iface.netmask}`);
console.log(` MAC: ${iface.mac}`);
});
});
```
#### Get Default Gateway
Retrieve the primary network interface:
```typescript
const defaultGateway = await network.getDefaultGateway();
if (defaultGateway) {
console.log('🌐 Default Gateway:');
console.log(' IPv4:', defaultGateway.ipv4.address);
console.log(' IPv6:', defaultGateway.ipv6.address);
}
```
### 🌎 Public IP Discovery
Discover your public-facing IP addresses:
```typescript
const publicIps = await network.getPublicIps();
console.log(`🌍 Public IPs:`);
console.log(` IPv4: ${publicIps.v4 || 'Not available'}`);
console.log(` IPv6: ${publicIps.v6 || 'Not available'}`);
```
### ⚡ Performance Caching
Reduce network calls with built-in caching:
```typescript
// Create instance with 60-second cache TTL
const cachedNetwork = new SmartNetwork({ cacheTtl: 60000 });
// First call fetches from network
const gateways1 = await cachedNetwork.getGateways();
const publicIps1 = await cachedNetwork.getPublicIps();
// Subsequent calls within 60 seconds use cache
const gateways2 = await cachedNetwork.getGateways(); // From cache ⚡
const publicIps2 = await cachedNetwork.getPublicIps(); // From cache ⚡
```
### 🔧 Plugin Architecture
Extend SmartNetwork with custom functionality:
```typescript
// Define your plugin
class CustomNetworkPlugin {
constructor(private smartNetwork: SmartNetwork) {}
async customMethod() {
// Your custom network logic here
return 'Custom result';
}
}
// Register the plugin
SmartNetwork.registerPlugin('customPlugin', CustomNetworkPlugin);
// Use the plugin
const network = new SmartNetwork();
const PluginClass = SmartNetwork.pluginsRegistry.get('customPlugin');
const plugin = new PluginClass(network);
await plugin.customMethod();
// Clean up when done
SmartNetwork.unregisterPlugin('customPlugin');
```
### 🚨 Error Handling
Handle network errors gracefully with custom error types:
```typescript
import { NetworkError } from '@push.rocks/smartnetwork';
try {
await network.isRemotePortAvailable('example.com', { protocol: 'udp' });
} catch (error) {
if (error instanceof NetworkError) {
console.error(`❌ Network error: ${error.message}`);
console.error(` Error code: ${error.code}`);
}
}
```
### 📚 TypeScript Support
This package is written in TypeScript and provides comprehensive type definitions:
```typescript
interface SmartNetworkOptions {
cacheTtl?: number; // Cache TTL in milliseconds
}
interface IFindFreePortOptions {
randomize?: boolean; // If true, returns a random free port instead of the first one
exclude?: number[]; // Array of port numbers to exclude from the search
}
interface Hop {
ttl: number; // Time to live
ip: string; // IP address of the hop
rtt: number | null; // Round trip time in ms
}
// ... and many more types for complete type safety
```
## 🛠️ Advanced Examples
### Building a Network Monitor
```typescript
const monitorNetwork = async () => {
const network = new SmartNetwork({ cacheTtl: 30000 });
// Check critical services
const services = [
{ name: 'Web Server', host: 'example.com', port: 443 },
{ name: 'Database', host: 'db.internal', port: 5432 },
{ name: 'Cache', host: 'redis.internal', port: 6379 }
];
for (const service of services) {
const isUp = await network.isRemotePortAvailable(service.host, service.port);
console.log(`${service.name}: ${isUp ? '✅ UP' : '❌ DOWN'}`);
}
// Check internet connectivity
const ping = await network.ping('8.8.8.8');
console.log(`Internet: ${ping.alive ? '✅ Connected' : '❌ Disconnected'}`);
// Measure network performance
const speed = await network.getSpeed();
console.log(`Speed: ⬇️ ${speed.downloadSpeed} Mbps / ⬆️ ${speed.uploadSpeed} Mbps`);
};
// Run monitor every minute
setInterval(monitorNetwork, 60000);
```
### Service Discovery
```typescript
const discoverServices = async () => {
const network = new SmartNetwork();
const commonPorts = [22, 80, 443, 3000, 3306, 5432, 6379, 8080, 9200];
console.log('🔍 Scanning local services...');
for (const port of commonPorts) {
const isUsed = !(await network.isLocalPortUnused(port));
if (isUsed) {
console.log(` Port ${port}: In use (possible service running)`);
}
}
};
```
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.