http-service-pool
v1.0.2
Published
Load balanced HTTP service pool with health checks and circuit breaker
Maintainers
Readme
service-pool
Load balanced HTTP service pool with health checks and circuit breaker.
Bu paket, birden fazla HTTP servisini tek bir pool altında toplayıp:
- Health check (periyodik sağlık kontrolü)
- Circuit breaker (otomatik aç/kapa, half-open)
- Load balancing stratejileri
round-robinleast-connectionsfastest
- Retry mekanizması (belirli sayıda tekrar deneme)
- Basit metrikler (response time, success rate vb.)
sağlayan küçük bir yardımcı kütüphanedir.
Kurulum
npm install service-pool
# veya
yarn add service-poolNode 16+ gerektirir ve ESM ("type": "module") yapısını kullanır.
Temel Kullanım
import { ServicePool } from 'service-pool';
async function main() {
const pool = new ServicePool(
[
{ url: 'http://service-1.internal:8080', name: 'service-1' },
{ url: 'http://service-2.internal:8080', name: 'service-2' }
],
{
strategy: 'round-robin', // 'round-robin' | 'least-connections' | 'fastest'
healthCheckPath: '/health',
requestTimeout: 30000,
healthTimeout: 5000,
healthCheckInterval: 10000,
maxConsecutiveFailures: 3,
retryAttempts: 2,
retryDelay: 1000,
headers: {}
}
);
// Örnek event dinleyicileri
pool.on('health:changed', (status) => {
console.log('Health changed:', status);
});
try {
const response = await pool.send('/api/example');
console.log('Response:', response);
} catch (error) {
console.error('Request failed:', error.message);
}
}
main();Daha detaylı bir örnek için examples/basic-usage.js dosyasına bakabilirsiniz.
API
ServicePool
new ServicePool(servicesConfig, options?)
servicesConfig:
Array<{ url: string; name?: string; headers?: object; ... }>url(zorunlu): Servisin base URL'iname(opsiyonel): Log ve event’lerde görünecek isimrequestTimeout(opsiyonel): Servis özelinde request timeouthealthTimeout(opsiyonel): Servis özelinde health check timeouthealthCheckPath(opsiyonel): Servis özelinde health pathhealthCheckValidStatus(opsiyonel): Health check için geçerli status fonksiyonumaxConsecutiveFailures(opsiyonel): Servis özelinde max ardışık hata sayısıheaders(opsiyonel): Servise özel header’lar
options: Global ayarlar
strategy:'round-robin' | 'least-connections' | 'fastest'(varsayılan:round-robin)requestTimeout: Varsayılan request timeout (ms)healthTimeout: Varsayılan health check timeout (ms)healthCheckPath: Varsayılan health endpoint (örn./health)healthCheckInterval: Periyodik health check aralığı (ms) (varsayılan:10000)maxConsecutiveFailures: Bir servis için art arda max hata sayısıretryAttempts: Başarısız istekte kaç kere tekrar deneneceği (ekstra deneme sayısı)retryDelay: Retry denemeleri arasındaki bekleme süresi (ms)headers: Tüm servislere uygulanacak global header’larautoStartHealthCheck:true/false(varsayılan:true)
Metodlar
pool.request(path, options?)→Promise<any>path: Servis base URL’ine eklenecek path (örn./api/users)options.method: HTTP metodu (varsayılan:GET)options.data: Body (POST/PUT vb. için)options.timeout: Bu request’e özel timeoutoptions.headers: Bu request’e özel header’laroptions.retryAttempts: Bu request’e özel retry sayısıoptions.retryDelay: Bu request’e özel retry bekleme süresi
pool.send(path, options?)→Promise<any>requestiçin basit bir alias.
pool.getHealthyServices()→Service[]- Şu an sağlıklı olan servisleri döner.
pool.getHealthStatus()→{ total, healthy, unhealthy, percentage }- Pool’un genel sağlık özetini verir.
pool.getStatus()- Tüm servislerin detaylı durumunu, metriklerini ve seçili stratejiyi döner.
pool.startHealthCheck()/pool.stopHealthCheck()- Periyodik health check’i başlatır / durdurur.
pool.resetMetrics()- Tüm servis metriklerini ve load balancer state’ini sıfırlar.
pool.destroy()- Health check timer’ını durdurur, listener’ları temizler.
pool.logStatus()- Pool durumunu konsola okunabilir şekilde loglar.
Event’ler
ServicePool, EventEmitter’ı genişlettiği için klasik .on(event, handler) ile dinleyebilirsiniz.
'service:up'- Bir servis tekrar sağlıklı olduğunda tetiklenir.
- Payload örneği:
{ service, url, checkDuration }
'service:down'- Bir servis art arda belirlenen sayıda hata aldığında veya istekler sırasında başarısız olduğunda tetiklenir.
- Payload örneği:
{ service, url, consecutiveFailures, reason }
'health:changed'- Genel pool health durumu değiştiğinde tetiklenir.
- Payload:
pool.getHealthStatus()çıktısı.
'health:check:completed'- Her health check turu sonunda tetiklenir.
- Payload:
{ timestamp, results: [{ service, success }] }
'request:success'- Bir istek başarılı olduğunda tetiklenir.
- Payload:
{ service, url, duration, status }
'request:failed'- Bir istek hata aldığında tetiklenir.
- Payload:
{ service, url, duration, error }
'request:retry'- Retry mekanizması devreye girdiğinde tetiklenir.
- Payload:
{ attempt, maxAttempts, error, nextRetryIn }
'request:failed:all'- Tüm retry denemeleri başarısız olduğunda tetiklenir.
- Payload:
{ attempts, lastError }
'metrics:reset'- Metrikler sıfırlandığında tetiklenir.
Load Balancing Stratejileri
Ayrı ayrı da import edebilirsiniz:
import { RoundRobin, LeastConnections, Fastest } from 'service-pool';Ancak pratikte genelde sadece ServicePool kullanmanız yeterli olur; strategy opsiyonu ile hangisinin kullanılacağını belirtirsiniz.
round-robin- Sırayla servis seçer. En basit ve deterministik strateji.
least-connections- Toplam istek sayısı en az olan servisi tercih eder.
fastest- Ortalama response time’ı en düşük olan, yani tarihsel olarak en hızlı cevabı veren servisi seçer.
Service sınıfı
Normalde doğrudan kullanmanız gerekmez; ServicePool bu sınıfı içerde kullanır. Yine de referans olarak:
- Her servis için sağlık durumunu (
isHealthy,circuitState) ve metriklerini tutar. checkHealth()verequest()metodları üzerinden HTTP çağrılarını gerçekleştirir.up,down,request:success,request:failed,metrics:resetgibi event’ler üretir.
Geliştirme
Repo içinde sadece bu paketi çalıştırmak için:
cd packages/service-pool
# Örnek script
yarn example
# Lint
yarn lint
# Formatter
yarn formatLisans
MIT
