npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

shared-libs-gateway

v1.1.0

Published

Distributed Gateway with Rate Limiting, Circuit Breaker, and Backpressure

Readme

🚀 Shared Libs Gateway

Enterprise-grade API Gateway & Multi-tenant Classification System with Advanced Observability

엔터프라이즈급 멀티테넌트 API 게이트웨이 & 자동 분류 시스템 (완전한 Observability 플랫폼)


📋 프로젝트 개요

🎯 핵심 목표

분산 시스템의 완전한 관찰성(Observability)을 제공하는 통합 플랫폼

  • 151개 프로젝트의 실시간 분류 및 모니터링
  • 동적 샘플링으로 부하 최소화 (오버헤드 <1ms)
  • 25개 자동 경보 규칙으로 주요 메트릭 모니터링
  • 36개 패널의 Grafana 대시보드로 실시간 시각화

✨ 주요 기능

Multi-tenancy & Security

  • 멀티테넌트 격리 (X-Tenant-ID 기반)
  • RBAC (4단계 권한 제어)
  • 감시 로그 (모든 API 호출 기록)
  • 보안 이벤트 실시간 감지

Real-time & Performance

  • WebSocket 기반 실시간 업데이트
  • 자동 분류 (기계학습)
  • 레이트 리미팅 + Circuit Breaker
  • 메트릭 자동 수집

Observability (Phase 10)

  • 동적 샘플링 (AdaptiveSampler)
  • Prometheus 메트릭 통합
  • 25개 Alert Rules (자동 경보)
  • 4개 Grafana 대시보드 (36 패널)

🏗️ 아키텍처

┌──────────────────────────────────────────────────────────────┐
│                     API Client / Webhook                      │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│                    Express.js (Port 40021)                   │
├──────────────────────────────────────────────────────────────┤
│                  TenantIsolationMiddleware                    │
│              (X-Tenant-ID 자동 추출 및 검증)                 │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│              TraceMiddleware (OpenTelemetry)                  │
│          (W3C Trace Context 자동 수집, Jaeger 전송)         │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│            MetricsExporter + AdaptiveSampler                 │
│          (성능 측정 + 동적 샘플링 비율 조정)                 │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│                    AuditLogger                               │
│             (모든 요청 기록 + 보안 이벤트 추적)              │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│                 RBAC Controller                              │
│            (권한 확인, O(1) 성능 보장)                      │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌──────────────────────────────────────────────────────────────┐
│              ClassifierAPI + RealTimeServer                  │
│         (자동 분류 + WebSocket 브로드캐스트)                 │
└────────────────────────────┬─────────────────────────────────┘
                             ↓
┌─────────────────────────────────────────────────────────────┐
│                    Observability Stack                      │
├──────────────┬──────────────┬──────────────┬────────────────┤
│  Prometheus  │ AlertManager │   Grafana    │    Jaeger      │
│  (Port 19090)│ (Port 9093)  │ (Port 13000) │  (Port 16686)  │
│              │              │              │                │
│ 메트릭 저장  │ 경보 라우팅  │ 시각화       │ 분산 추적      │
└──────────────┴──────────────┴──────────────┴────────────────┘

🛠️ 기술 스택

| 계층 | 기술 | 버전 | |------|------|------| | Runtime | Node.js | 18+ | | Framework | Express.js | 4.18 | | Real-time | WebSocket (ws) | 8.20 | | 분산 추적 | OpenTelemetry | 0.50+ | | Tracing Backend | Jaeger | v1.76 | | 메트릭 수집 | Prometheus | latest | | 메트릭 시각화 | Grafana | latest | | 경보 라우팅 | AlertManager | latest | | 캐싱 | Redis | 7.0 | | 로깅 | @shared-libs/logging | - | | 테스트 | Jest | 29.0 | | 배포 | Docker | latest |


🚀 빠른 시작

1. 설치

npm install

2. 환경 설정

# .env 파일 생성
cat > .env << EOF
PORT=40021
REALTIME_PORT=40022
REDIS_URL=redis://localhost:6379
LOG_LEVEL=info
MAX_TENANTS=1000
MAX_AUDIT_LOGS=10000

# Observability
OTEL_EXPORTER=jaeger
OTEL_EXPORTER_JAEGER_ENDPOINT=http://localhost:6831
OTEL_SERVICE_NAME=classifier-api
OTEL_SERVICE_VERSION=1.0.0
EOF

3. Docker Compose로 전체 스택 실행

# Prometheus, AlertManager, Grafana, Jaeger 시작
docker compose up -d

# 상태 확인
docker compose ps

4. API 서버 실행

# 개발 모드
npm run dev

# 프로덕션 모드
npm start

# 테스트
npm test

5. 접근 URL

| 서비스 | URL | 용도 | |--------|-----|------| | API Server | http://localhost:40021 | 분류 & 관리 API | | WebSocket | ws://localhost:40022 | 실시간 이벤트 | | Prometheus | http://localhost:19090 | 메트릭 저장 & 쿼리 | | Grafana | http://localhost:13000 | 대시보드 시각화 | | AlertManager | http://localhost:9093 | 경보 관리 | | Jaeger | http://localhost:16686 | 분산 추적 | | 메트릭 | http://localhost:40021/metrics | Prometheus 형식 |


📦 핵심 모듈

Phase 8: Enterprise Features

1. lib/tenant-isolation.js - 멀티테넌트 격리

const middleware = tenantIsolation.middleware();
app.use(middleware);

// 자동으로 X-Tenant-ID 헤더에서 테넌트 ID 추출
// 테넌트별 독립적인 분류기 관리 (LRU eviction)

특징:

  • 테넌트별 독립적 리소스 격리
  • LRU 메모리 관리 (최대 1,000 테넌트)
  • 모든 요청에 테넌트 ID 자동 삽입

2. lib/rbac-controller.js - 권한 제어

// 권한 확인 (O(1) 성능)
const hasPermission = rbac.hasPermission(userId, tenantId, 'classifier', 'train');

// 미들웨어로 라우트 보호
app.post('/train', rbac.requirePermission('classifier', 'train'), handler);

권한 매트릭스:

  • admin: 모든 권한
  • trainer: 모델 학습, 분류
  • classifier: 분류만 가능
  • viewer: 조회만 가능

3. lib/audit-logger.js - 감시 로그

// CircularBuffer로 고정 메모리 사용 (10,000개 로그)
auditLogger.log(tenantId, userId, 'classifier', 'train', 'success');

// CSV/JSON 내보내기
const csv = auditLogger.export(tenantId, 'csv');

특징:

  • 4단계 로그 레벨 (INFO, WARNING, ERROR, SECURITY)
  • O(1) 푸시 + 자동 eviction
  • 보안 이벤트 실시간 감지

4. lib/metrics-exporter.js - 메트릭 수집

const metrics = new MetricsExporter('classifier-api');
app.use(metrics.middleware());

// Prometheus 형식 내보내기
app.get('/metrics', (req, res) => {
  res.send(metrics.toPrometheus());
});

특징:

  • Prometheus 형식 메트릭
  • p50, p95, p99 자동 계산
  • JSON/Prometheus 듀얼 형식 지원

Phase 9: Distributed Tracing

5. lib/opentelemetry-setup.js - 분산 추적

// OpenTelemetry SDK 초기화
const { tracer } = require('./opentelemetry-setup');

// 자동으로 모든 HTTP 요청이 Span으로 변환됨
// W3C Trace Context 자동 전파

특징:

  • Jaeger exporter 통합
  • W3C Trace Context 준수
  • 멀티테넌트 context 격리 (AsyncLocalStorage)

Phase 10: Advanced Observability

6. lib/adaptive-sampler.js - 동적 샘플링

const sampler = new AdaptiveSampler({
  minSamplingRate: 0.01,    // 최소 1%
  maxSamplingRate: 1.0,      // 최대 100%
  targetErrorRate: 0.05,     // 목표 에러율 5%
  targetLatencyMs: 100,      // 목표 레이턴시 100ms
  targetRps: 1000            // 목표 RPS
});

// 주기적 재계산
sampler.updateSamplingRate();

동적 조정 로직:

  • 에러율 >10% → 70% 샘플링 (문제 파악)
  • P95 레이턴시 >200ms → 30% 감소 (성능 보호)
  • RPS >1500 → 20% 감소 (부하 관리)
  • 급격한 변화 방지 (±30% 제한)

7. lib/metrics-integration.js - 메트릭 통합

// OpenTelemetry Span → Prometheus 메트릭 변환
metricsIntegration.recordSpanMetrics(span, duration);
metricsIntegration.recordTraceMetrics(traceDurationMs, spanCount, hasError);

// 집계 메트릭 조회
const metrics = metricsIntegration.getTraceMetrics();

특징:

  • Span 타입별 메트릭 (HTTP, Classification, Event, Redis)
  • 백분위수 자동 계산 (P50, P95, P99)
  • 에러 분포 추적

📡 API 엔드포인트

분류 API

POST   /api/classifier/train           - 모델 학습
POST   /api/classifier/classify        - 프로젝트 분류
GET    /api/classifier/stats           - 모델 통계
POST   /api/classifier/anomalies       - 이상 탐지
POST   /api/classifier/webhook/gogs    - Gogs 웹훅

사용자 & 권한

POST   /api/users                      - 사용자 생성
GET    /api/users                      - 사용자 목록
PUT    /api/users/:id/role             - 역할 변경
DELETE /api/users/:id                  - 사용자 삭제
GET    /api/roles                      - 모든 역할

감시 로그

GET    /api/audit-logs                 - 감시 로그 조회
GET    /api/audit-logs/security        - 보안 이벤트
GET    /api/audit-logs/search          - 로그 검색
GET    /api/audit-logs/export          - 로그 내보내기 (CSV/JSON)

메트릭 & 모니터링

GET    /api/metrics                    - JSON 형식 메트릭
GET    /metrics                        - Prometheus 형식
GET    /api/alerts                     - 현재 경보

테넌트 설정

GET    /api/tenants                    - 모든 테넌트
PUT    /api/tenants/:id/settings       - 테넌트 설정 변경

📊 Observability Stack

Prometheus (메트릭 저장)

포트: 19090

특징:

  • 5개 scrape targets (5-15초 주기)
    • classifier-api (5초)
    • prometheus, jaeger, alertmanager, grafana (15초)
  • 30일 retention (50GB max)
  • 자동 rule evaluation (30초 주기)

설정: prometheus.yml

AlertManager (경보 라우팅)

포트: 9093

25개 Alert Rules:

HTTP 메트릭:

  • HighErrorRate (>5%, critical)
  • HighLatencyP99 (>500ms, warning)
  • HighLatencyP95 (>250ms, warning)

Tracing:

  • HighSpanProcessingLatency (>200ms)
  • HighSpanCount (>10K/sec)
  • SpanErrorRate (>10%)

Classification:

  • ClassificationLatencyHigh (>300ms)
  • ClassificationFailureRate (>2%)

Events:

  • EventPublishFailure (>10/sec)
  • EventDeliveryLatency (>1s P95)
  • EventQueueBacklog (>1000)

System Resources:

  • HighMemoryUsage (>500MB)
  • HighCPUUsage (>80%)
  • HighHeapUsage (>90%)

Availability & Security:

  • ServiceDown, MetricScrapeFailing, TenantIsolationViolation 등

설정: alertmanager.yml, alerts.yml

Grafana (시각화)

포트: 13000

4개 대시보드 (36 패널):

1. HTTP Performance (7 패널)

  • RPS, 에러율, P99 레이턴시
  • 상태 코드 분포
  • 백분위수 분포 (P50/95/99)
  • Top Endpoints
  • 요청 타임라인

2. Classification (9 패널)

  • 분류 처리량, 성공률
  • 레이턴시 분포
  • 에러 분류
  • 모델 정확도, 학습 상태
  • 프로젝트 타임라인

3. Events (9 패널)

  • 발행/전달 속도
  • 성공률, 큐 깊이
  • 레이턴시 (P95)
  • 이벤트 타입 분포
  • 실패 추적

4. System Resources (11 패널)

  • 메모리, CPU, 힙 사용량
  • Event Loop Lag
  • GC 이벤트, Open FDs
  • 업타임, Node.js 정보

자동 provisioning: grafana/provisioning/

Jaeger (분산 추적)

포트: 16686

특징:

  • 완전한 request trace 시각화
  • Span 계층 구조 분석
  • 성능 병목 지점 식별
  • W3C Trace Context 지원

🧪 테스트

Phase 10 테스트 (27개, 100% PASS)

npm test -- __tests__/phase10-sampling.test.js

테스트 범위:

  • ✅ AdaptiveSampler (15개)

    • 초기화, 요청/에러/레이턴시 기록
    • 에러율/P95/RPS 계산
    • 동적 샘플링 조정
    • Min/Max 범위 준수
    • 급격한 변화 방지
  • ✅ MetricsIntegration (9개)

    • Span 메트릭 기록
    • 트레이스 메트릭 기록
    • 백분위수 계산
    • 에러 분포 추적
  • ✅ Integration (3개)

    • 완전한 pipeline
    • 높은 부하 시나리오
    • 높은 에러율 시나리오

Phase 8 Enterprise Tests (21개, 100% PASS)

npm test -- lib/phase8-week4-test.js

테스트 범위:

  • ✅ 멀티테넌트 격리
  • ✅ RBAC 권한 제어
  • ✅ 감시 로그
  • ✅ 메트릭 수집
  • ✅ 실시간 업데이트
  • ✅ API 기능

📈 성능 벤치마크

Phase 10 성능

AdaptiveSampler 오버헤드:        < 1ms
메트릭 수집 오버헤드:             < 1ms
Prometheus 스크래핑:              < 500ms (5-15초 주기)
메모리 증가:                      < 5MB

Phase 8 성능

정확 검색:                       < 10ms
유사 검색:                       < 50ms
감시 로그 조회:                  < 100ms
메트릭 수집:                     < 50ms
권한 확인 (RBAC):                O(1) ~ 1ms

🔐 보안 아키텍처

멀티테넌트 격리

테넌트 A의 요청 → X-Tenant-ID: A
              → TenantIsolationMiddleware
              → 테넌트 A 컨텍스트로 격리
              → 테넌트 B 데이터 접근 불가

RBAC 권한 제어

사용자 요청 → RBACController
           → O(1) 권한 조회
           → 거부 시 → AuditLogger (SECURITY 레벨)
           → 승인 시 → 비즈니스 로직 실행

감시 로그

모든 API → AuditLogger
        → CircularBuffer (O(1) eviction)
        → 4단계 레벨 (INFO/WARNING/ERROR/SECURITY)
        → CSV/JSON 내보내기

🐳 Docker & 배포

Docker Compose

# 전체 스택 실행 (모니터링 포함)
docker compose up -d

# 로그 확인
docker compose logs -f prometheus
docker compose logs -f grafana
docker compose logs -f alertmanager

# 중지
docker compose down

서비스 포트

| 서비스 | 포트 | 내부 포트 | |--------|------|---------| | API | 40021 | 40021 | | WebSocket | 40022 | 40022 | | Prometheus | 19090 | 9090 | | Grafana | 13000 | 3000 | | AlertManager | 9093 | 9093 | | Jaeger UI | 16686 | 16686 | | Jaeger Agent | 6831/udp | 6831/udp | | Jaeger Collector | 14268 | 14268 |

환경 변수

# API 설정
PORT=40021
REALTIME_PORT=40022

# Redis
REDIS_URL=redis://localhost:6379

# 로깅
LOG_LEVEL=info

# 리소스 관리
MAX_TENANTS=1000
MAX_AUDIT_LOGS=10000

# Observability
OTEL_EXPORTER=jaeger
OTEL_EXPORTER_JAEGER_ENDPOINT=http://localhost:6831
OTEL_SERVICE_NAME=classifier-api
OTEL_SERVICE_VERSION=1.0.0

📚 문서

핵심 문서

참고 자료

  • 테스트: __tests__/phase10-sampling.test.js (27개 테스트)
  • 설정: ecosystem.config.js (PM2 배포)
  • 상수: lib/constants.js (모든 정의)

🎯 로드맵

✅ 완료된 Phase

  • Phase 8: Enterprise Features (멀티테넌트, RBAC, 감시 로그)
  • Phase 9: Distributed Tracing (OpenTelemetry, Jaeger)
  • Phase 10: Advanced Metrics (Prometheus, Grafana, AlertManager, Adaptive Sampling)

📋 다음 단계

Phase 11: Observability Platform 완성

  • [ ] Grafana 대시보드 실시간 데이터 검증
  • [ ] 커스텀 메트릭 추가
  • [ ] 장기 트렌드 분석 (7/30/90일)
  • [ ] 성능 이슈 자동 감지

Phase 12: 시스템 최적화

  • [ ] 메트릭 저장소 최적화
  • [ ] 쿼리 성능 개선
  • [ ] 대시보드 캐싱
  • [ ] 비용 최적화

📞 지원 & 연락처

  • Gogs Repository: https://gogs.dclub.kr/kim/shared-libs-gateway
  • Issues: Gogs Issues 탭
  • Latest Release: Phase 10 (Commit: bc6b2d2)

📊 프로젝트 통계

| 항목 | 수치 | |------|------| | 총 코드량 | ~2,935줄 | | Phase 10 기여 | 450줄 (모듈) + 1,786줄 (설정) | | 테스트 케이스 | 48개 (27 Phase 10 + 21 Phase 8) | | 테스트 성공률 | 100% | | Alert Rules | 25개 | | Grafana 패널 | 36개 | | API 엔드포인트 | 30개 | | 모니터링 대상 | 151개 프로젝트 |


Version: 1.0.0 Last Updated: 2026-04-05 Status: Production Ready ✅ Observability: Advanced ⭐⭐⭐⭐⭐