Skip to content

Commit 79429a8

Browse files
authored
Merge pull request #2 from BackendStack21/documentation-improvements
feat: Enhance TypeScript interfaces and documentation
2 parents 5e79f4a + 5cc0c89 commit 79429a8

15 files changed

Lines changed: 1298 additions & 273 deletions

File tree

README.md

Lines changed: 41 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 🚀 BunGate
1+
# 🚀 Bungate
22

33
> **The Lightning-Fast HTTP Gateway & Load Balancer for the Modern Web**
44
@@ -7,27 +7,27 @@
77
[![Performance](https://img.shields.io/badge/Performance-Blazing%20Fast-orange)](https://github.com/BackendStack21/bungate)
88
[![License](https://img.shields.io/badge/License-MIT-green)](./LICENSE)
99

10-
**BunGate** is a next-generation HTTP gateway and load balancer that harnesses the incredible speed of Bun.js to deliver unparalleled performance for modern web applications. Built from the ground up with TypeScript, it provides enterprise-grade features with zero-config simplicity.
10+
**Bungate** is a next-generation HTTP gateway and load balancer that harnesses the incredible speed of Bun to deliver unparalleled performance for modern web applications. Built from the ground up with TypeScript, it provides enterprise-grade features with zero-config simplicity.
1111

12-
## ⚡ Why BunGate?
12+
## ⚡ Why Bungate?
1313

14-
- **🔥 Blazing Fast**: Built on Bun.js - up to 4x faster than Node.js alternatives
14+
- **🔥 Blazing Fast**: Built on Bun - up to 4x faster than Node.js alternatives
1515
- **🎯 Zero Config**: Works out of the box with sensible defaults
16-
- **🧠 Smart Load Balancing**: 5 supported load balancing algorithms: `round-robin`, `least-connections`, `random`, `weighted`, `ip-hash`
16+
- **🧠 Smart Load Balancing**: 5 load balancing algorithms: `round-robin`, `least-connections`, `random`, `weighted`, `ip-hash`
1717
- **🛡️ Production Ready**: Circuit breakers, health checks, and auto-failover
1818
- **🔐 Built-in Authentication**: JWT, API keys, JWKS, and OAuth2 support out of the box
1919
- **🎨 Developer Friendly**: Full TypeScript support with intuitive APIs
2020
- **📊 Observable**: Built-in metrics, logging, and monitoring
2121
- **🔧 Extensible**: Powerful middleware system for custom logic
2222

23-
> See Benchmarks comparing BunGate with Nginx and Envoy in the [benchmark directory](./benchmark).
23+
> See benchmarks comparing Bungate with Nginx and Envoy in the [benchmark directory](./benchmark).
2424
2525
## 🚀 Quick Start
2626

2727
Get up and running in less than 60 seconds:
2828

2929
```bash
30-
# Install BunGate
30+
# Install Bungate
3131
bun add bungate
3232

3333
# Create your gateway
@@ -47,16 +47,17 @@ const gateway = new BunGateway({
4747
gateway.addRoute({
4848
pattern: '/api/*',
4949
loadBalancer: {
50+
strategy: 'least-connections',
5051
targets: [
51-
'http://api1.example.com',
52-
'http://api2.example.com',
53-
'http://api3.example.com',
52+
{ url: 'http://api1.example.com' },
53+
{ url: 'http://api2.example.com' },
54+
{ url: 'http://api3.example.com' },
5455
],
55-
strategy: 'least-connections',
5656
healthCheck: {
5757
enabled: true,
5858
interval: 30000,
5959
timeout: 5000,
60+
path: '/health',
6061
},
6162
},
6263
})
@@ -74,7 +75,7 @@ gateway.addRoute({
7475

7576
// Start the gateway
7677
await gateway.listen()
77-
console.log('🚀 BunGate running on http://localhost:3000')
78+
console.log('🚀 Bungate running on http://localhost:3000')
7879
```
7980

8081
**That's it!** Your high-performance gateway is now handling traffic with:
@@ -92,34 +93,36 @@ console.log('🚀 BunGate running on http://localhost:3000')
9293
### 🚀 **Performance & Scalability**
9394

9495
- **High Throughput**: Handle thousands of requests per second
95-
- **Low Latency**: Low latency routing with minimal overhead
96+
- **Low Latency**: Minimal overhead routing with optimized request processing
9697
- **Memory Efficient**: Optimized for high-concurrent workloads
9798
- **Auto-scaling**: Dynamic target management and health monitoring
9899
- **Cluster Mode**: Multi-process clustering for maximum CPU utilization
99100

100101
### 🎯 **Load Balancing Strategies**
101102

102103
- **Round Robin**: Equal distribution across all targets
103-
- **Weighted Round Robin**: Distribute based on server capacity
104-
- **Least Connections**: Route to least busy server
105-
- **IP Hash**: Consistent routing based on client IP
104+
- **Weighted**: Distribute based on server capacity and weights
105+
- **Least Connections**: Route to the least busy server
106+
- **IP Hash**: Consistent routing based on client IP for session affinity
106107
- **Random**: Randomized distribution for even load
107-
- **Sticky Sessions**: Session affinity with cookie support
108+
- **Sticky Sessions**: Session affinity with cookie-based persistence
108109

109110
### 🛡️ **Reliability & Resilience**
110111

111112
- **Circuit Breaker Pattern**: Automatic failure detection and recovery
112113
- **Health Checks**: Active monitoring with custom validation
113-
- **Timeout Management**: Route-level timeout controls
114+
- **Timeout Management**: Route-level and global timeout controls
115+
- **Auto-failover**: Automatic traffic rerouting on service failures
116+
- **Graceful Degradation**: Fallback responses and cached data support
114117

115118
### 🔧 **Advanced Features**
116119

117120
- **Authentication & Authorization**: JWT, API keys, JWKS, OAuth2/OIDC support
118-
- **Middleware System**: Custom request/response processing
121+
- **Middleware System**: Custom request/response processing pipeline
119122
- **Path Rewriting**: URL transformation and routing rules
120123
- **Rate Limiting**: Flexible rate limiting with custom key generation
121124
- **CORS Support**: Full cross-origin resource sharing configuration
122-
- **Request/Response Hooks**: Lifecycle event handling
125+
- **Request/Response Hooks**: Comprehensive lifecycle event handling
123126

124127
### 📊 **Monitoring & Observability**
125128

@@ -131,11 +134,11 @@ console.log('🚀 BunGate running on http://localhost:3000')
131134

132135
### 🎨 **Developer Experience**
133136

134-
- **TypeScript First**: Full type safety and IntelliSense
135-
- **Zero Dependencies**: Minimal footprint with essential features
137+
- **TypeScript First**: Full type safety and IntelliSense support
138+
- **Zero Dependencies**: Minimal footprint with essential features only
136139
- **Hot Reload**: Development mode with automatic restarts
137-
- **Rich Examples**: Comprehensive documentation and examples
138-
- **Testing Support**: Built-in testing utilities and mocks
140+
- **Rich Documentation**: Comprehensive examples and API documentation
141+
- **Testing Support**: Built-in utilities for testing and development
139142

140143
## 🏗️ Real-World Examples
141144

@@ -189,7 +192,7 @@ gateway.addRoute({
189192
hooks: {
190193
onError(req, error): Promise<Response> {
191194
// Fallback to cached payment status
192-
return getCachedPaymentStatus(req.params.id)
195+
return getCachedPaymentStatus(req.url)
193196
},
194197
},
195198
})
@@ -246,11 +249,6 @@ Distribute traffic intelligently across multiple backends:
246249
gateway.addRoute({
247250
pattern: '/products/*',
248251
loadBalancer: {
249-
targets: [
250-
'http://api1.example.com',
251-
'http://api2.example.com',
252-
'http://api3.example.com',
253-
],
254252
strategy: 'weighted',
255253
targets: [
256254
{ url: 'http://products-primary:3000', weight: 70 },
@@ -271,16 +269,11 @@ gateway.addRoute({
271269
gateway.addRoute({
272270
pattern: '/app/*',
273271
loadBalancer: {
274-
targets: [
275-
'http://api1.example.com',
276-
'http://api2.example.com',
277-
'http://api3.example.com',
278-
],
279272
strategy: 'ip-hash',
280273
targets: [
281-
'http://app-server-1:3000',
282-
'http://app-server-2:3000',
283-
'http://app-server-3:3000',
274+
{ url: 'http://app-server-1:3000' },
275+
{ url: 'http://app-server-2:3000' },
276+
{ url: 'http://app-server-3:3000' },
284277
],
285278
stickySession: {
286279
enabled: true,
@@ -354,7 +347,7 @@ gateway.addRoute({
354347

355348
## 🔐 **Built-in Authentication**
356349

357-
BunGate provides comprehensive authentication support out of the box:
350+
Bungate provides comprehensive authentication support out of the box:
358351

359352
#### JWT Authentication
360353

@@ -536,24 +529,9 @@ touch gateway.ts
536529
import { BunGateway, BunGateLogger } from 'bungate'
537530

538531
const logger = new BunGateLogger({
539-
level: 'error',
540-
transport: {
541-
target: 'pino-pretty',
542-
options: {
543-
colorize: true,
544-
translateTime: 'SYS:standard',
545-
ignore: 'pid,hostname',
546-
},
547-
},
548-
serializers: {
549-
req: (req) => ({
550-
method: req.method,
551-
url: req.url,
552-
}),
553-
res: (res) => ({
554-
statusCode: res.status,
555-
}),
556-
},
532+
level: 'info',
533+
format: 'pretty',
534+
enableRequestLogging: true,
557535
})
558536

559537
const gateway = new BunGateway({
@@ -585,18 +563,18 @@ gateway.addRoute({
585563
},
586564
})
587565

588-
// Add public routes with another layer of authentication
566+
// Add public routes with API key authentication
589567
gateway.addRoute({
590568
pattern: '/api/public/*',
591569
target: 'http://public-service:3002',
592570
auth: {
593571
apiKeys: ['public-key-1', 'public-key-2'],
594-
apiKeyHeader: 'x-public-key',
572+
apiKeyHeader: 'x-api-key',
595573
},
596574
})
597575

598576
await gateway.listen()
599-
console.log('🚀 BunGate running on http://localhost:3000')
577+
console.log('🚀 Bungate running on http://localhost:3000')
600578
```
601579

602580
## 📄 License
@@ -607,6 +585,8 @@ MIT Licensed - see [LICENSE](LICENSE) for details.
607585

608586
<div align="center">
609587

610-
**Built with ❤️ for the JavaScript Community**
588+
**Built with ❤️ by BackendStack21 for the JavaScript Community**
589+
590+
[🏠 Homepage](https://github.com/BackendStack21/bungate) | [📚 Documentation](https://github.com/BackendStack21/bungate#readme) | [🐛 Issues](https://github.com/BackendStack21/bungate/issues) | [💬 Discussions](https://github.com/BackendStack21/bungate/discussions)
611591

612592
</div>

package.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,16 @@
33
"version": "0.2.0",
44
"license": "MIT",
55
"description": "A high-performance HTTP gateway for Bun, designed for microservices and API gateways.",
6+
"keywords": [
7+
"javascript",
8+
"typescript",
9+
"bun",
10+
"gateway",
11+
"microservices",
12+
"api-gateway",
13+
"http",
14+
"performance"
15+
],
616
"scripts": {
717
"test": "bun test",
818
"test:integration": "bun test test/integration.test.ts",

src/cluster/cluster-manager.ts

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,81 @@
1+
/**
2+
* High-Availability Cluster Manager for Bungate
3+
*
4+
* Manages multiple worker processes for horizontal scaling and fault tolerance.
5+
* Provides automatic worker spawning, health monitoring, graceful restarts,
6+
* and load distribution across CPU cores for maximum performance.
7+
*
8+
* Features:
9+
* - Automatic worker process management and scaling
10+
* - Intelligent restart policies with backoff strategies
11+
* - Graceful shutdown with connection draining
12+
* - Real-time health monitoring and failure detection
13+
* - Zero-downtime deployments with rolling restarts
14+
* - Resource monitoring and performance optimization
15+
* - Signal-based management (SIGINT, SIGTERM, SIGUSR2)
16+
* - Comprehensive logging and operational visibility
17+
*
18+
* @example
19+
* ```ts
20+
* const clusterManager = new ClusterManager({
21+
* workers: 4,
22+
* restartWorkers: true,
23+
* maxRestarts: 10,
24+
* shutdownTimeout: 30000
25+
* }, logger, './worker.js')
26+
*
27+
* await clusterManager.start()
28+
* ```
29+
*/
30+
131
import { spawn, type Subprocess } from 'bun'
232
import { cpus } from 'os'
333
import type { Logger } from '../interfaces/logger'
434
import type { ClusterConfig } from '../interfaces/gateway'
535

36+
/**
37+
* Worker process information for tracking and management
38+
*/
639
export interface WorkerInfo {
40+
/** Unique worker identifier */
741
id: number
42+
/** Bun subprocess instance */
843
process: Subprocess
44+
/** Number of times this worker has been restarted */
945
restarts: number
46+
/** Timestamp of last restart attempt */
1047
lastRestartTime: number
48+
/** Flag indicating worker is in shutdown process */
1149
isExiting: boolean
1250
}
1351

52+
/**
53+
* Production-grade cluster manager for multi-process deployments
54+
*
55+
* Orchestrates worker processes with intelligent health monitoring,
56+
* automatic recovery, and zero-downtime deployment capabilities.
57+
*/
1458
export class ClusterManager {
59+
/** Cluster configuration with scaling and restart policies */
1560
private config: ClusterConfig
61+
/** Logger instance for operational monitoring */
1662
private logger?: Logger
63+
/** Map of active worker processes */
1764
private workers: Map<number, WorkerInfo> = new Map()
65+
/** Counter for generating unique worker IDs */
1866
private nextWorkerId = 1
67+
/** Flag indicating cluster shutdown in progress */
1968
private isShuttingDown = false
69+
/** Path to worker script for spawning processes */
2070
private workerScript: string
2171

72+
/**
73+
* Initialize cluster manager with configuration and dependencies
74+
*
75+
* @param config - Cluster configuration including worker count and restart policies
76+
* @param logger - Logger instance for monitoring and debugging
77+
* @param workerScript - Path to worker script to execute
78+
*/
2279
constructor(config: ClusterConfig, logger?: Logger, workerScript?: string) {
2380
this.config = {
2481
enabled: true,
@@ -35,6 +92,14 @@ export class ClusterManager {
3592
this.workerScript = workerScript || process.argv[1] || 'worker.js'
3693
}
3794

95+
/**
96+
* Start the cluster with configured worker processes
97+
*
98+
* Spawns worker processes, sets up signal handlers, and begins health monitoring.
99+
* Provides graceful startup with proper error handling and logging.
100+
*
101+
* @returns Promise that resolves when cluster is fully operational
102+
*/
38103
async start(): Promise<void> {
39104
if (!this.config.enabled) {
40105
this.logger?.info('Cluster mode disabled')
@@ -43,7 +108,7 @@ export class ClusterManager {
43108

44109
this.logger?.info(`Starting cluster with ${this.config.workers} workers`)
45110

46-
// Set up signal handlers
111+
// Configure signal handlers for graceful lifecycle management
47112
process.on('SIGINT', this.gracefulShutdown.bind(this))
48113
process.on('SIGTERM', this.gracefulShutdown.bind(this))
49114
process.on('SIGUSR2', this.restartAllWorkers.bind(this))

0 commit comments

Comments
 (0)