All files / src/core worker-manager.ts

90.29% Statements 93/103
69.23% Branches 18/26
94.44% Functions 17/18
90.9% Lines 90/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373          1x 1x 1x 1x                                                                                                                                                 1x   22x   22x   22x   22x                 22x   22x               25x         25x 1x       24x           24x   24x       24x   24x         24x                     24x 1x     24x 1x 1x     24x 5x 5x 5x 5x       24x     24x     24x     24x   24x               3x 3x     2x   2x   2x     2x 2x                     2x 2x 1x     1x                 5x                 8x               1x                 5x 5x   4x     4x     4x                 6x 6x   6x 7x 1x 6x 6x       6x                     2x   2x 2x     2x 1x                   1x     1x 1x       1x 1x 2x               1x     1x 1x                 24x     24x 24x 16x     8x   1x         1x 1x   1x       8x               36x 36x 2x 2x        
/**
 * 워커 매니저
 * 워커 생성, 관리, 스케일링 담당
 */
 
import { EventEmitter } from "eventemitter3";
import { IWorker, WorkerStatus, WorkerType } from "../types/index.js";
import { WorkerAdapter } from "./worker-adapter.js";
import { generateId } from "./utils.js";
 
/**
 * 워커 매니저 설정 인터페이스
 */
export interface WorkerManagerConfig {
  /** 최소 워커 수 */
  minWorkers: number;
  /** 최대 워커 수 */
  maxWorkers: number;
  /** 워커 유휴 타임아웃 (밀리초) */
  idleTimeout: number;
  /** 워커 URL (웹 환경) */
  workerUrl?: string | ((type: string) => string);
  /** 워커 파일 경로 (Node.js 환경) */
  workerFile?: string | ((type: string) => string);
  /** 워커 유형 */
  workerType: WorkerType | string;
}
 
/**
 * 워커 통계 인터페이스
 */
export interface WorkerManagerStats {
  /** 총 워커 수 */
  totalWorkers: number;
  /** 활성 워커 수 */
  activeWorkers: number;
  /** 유휴 워커 수 */
  idleWorkers: number;
}
 
/**
 * 워커 매니저 인터페이스
 */
export interface IWorkerManager {
  /** 워커 생성 */
  createWorker(): string;
  /** 워커 해제 */
  releaseWorker(workerId: string): Promise<void>;
  /** 유휴 워커 가져오기 */
  getIdleWorker(): IWorker | undefined;
  /** 워커 상태 가져오기 */
  getWorkerStatus(workerId: string): WorkerStatus;
  /** 워커 가져오기 */
  getWorker(workerId: string): IWorker | undefined;
  /** 모든 워커 가져오기 */
  getAllWorkers(): IWorker[];
  /** 워커 매니저 통계 가져오기 */
  getStats(): WorkerManagerStats;
  /** 최소 워커 수 유지 */
  ensureMinWorkers(): void;
  /** 모든 워커 종료 */
  closeAll(force?: boolean): Promise<void>;
}
 
/**
 * 워커 매니저 이벤트 인터페이스
 */
export interface WorkerManagerEvents {
  /** 워커 생성 이벤트 */
  workerCreated: [{ workerId: string }];
  /** 워커 에러 이벤트 */
  workerError: [{ workerId: string; error: Error }];
  /** 워커 종료 이벤트 */
  workerExit: [{ workerId: string; exitCode: number }];
  /** 워커 메시지 이벤트 */
  workerMessage: [{ workerId: string; message: any }];
}
 
/**
 * 워커 매니저 클래스
 */
export class WorkerManager extends EventEmitter implements IWorkerManager {
  /** 워커 맵 */
  private workers: Map<string, IWorker> = new Map();
  /** 워커 상태 맵 */
  private workerStatus: Map<string, WorkerStatus> = new Map();
  /** 유휴 타이머 맵 */
  private idleTimers: Map<string, NodeJS.Timeout> = new Map();
  /** 종료 중 여부 */
  private isClosing: boolean = false;
  /** 설정 */
  private config: WorkerManagerConfig;
 
  /**
   * 워커 매니저 생성자
   * @param config 설정
   */
  constructor(config: WorkerManagerConfig) {
    super();
 
    this.config = config;
  }
 
  /**
   * 워커 생성
   * @returns 워커 ID
   */
  createWorker(): string {
    Iif (this.isClosing) {
      throw new Error("워커 매니저가 종료 중입니다");
    }
 
    // 최대 워커 수 확인
    if (this.workers.size >= this.config.maxWorkers) {
      throw new Error(`최대 워커 수(${this.config.maxWorkers})에 도달했습니다`);
    }
 
    // 워커 ID 생성
    const workerId = generateId();
 
    // 워커 URL 또는 파일 경로 결정
    let url: string | undefined;
    let file: string | undefined;
 
    Iif (typeof this.config.workerUrl === "function") {
      url = this.config.workerUrl(this.config.workerType);
    } else Iif (typeof this.config.workerUrl === "string") {
      url = this.config.workerUrl;
    }
 
    Iif (typeof this.config.workerFile === "function") {
      file = this.config.workerFile(this.config.workerType);
    } else Iif (typeof this.config.workerFile === "string") {
      file = this.config.workerFile;
    }
 
    // 워커 어댑터 생성
    const worker = new WorkerAdapter({
      id: workerId,
      url,
      file,
      workerData: {
        id: workerId,
        type: this.config.workerType,
      },
    });
 
    // 이벤트 핸들러 등록
    worker.on("message", (message) => {
      this.emit("workerMessage", { workerId, message });
    });
 
    worker.on("error", (error) => {
      this.workerStatus.set(workerId, WorkerStatus.ERROR);
      this.emit("workerError", { workerId, error });
    });
 
    worker.on("exit", (code) => {
      this.clearIdleTimer(workerId);
      this.workers.delete(workerId);
      this.workerStatus.delete(workerId);
      this.emit("workerExit", { workerId, exitCode: code });
    });
 
    // 워커 맵에 추가
    this.workers.set(workerId, worker);
 
    // 워커 상태 설정
    this.workerStatus.set(workerId, WorkerStatus.IDLE);
 
    // 유휴 타이머 설정
    this.setIdleTimer(workerId);
 
    // 워커 생성 이벤트 발생
    this.emit("workerCreated", { workerId });
 
    return workerId;
  }
 
  /**
   * 워커 해제
   * @param workerId 워커 ID
   */
  async releaseWorker(workerId: string): Promise<void> {
    const worker = this.workers.get(workerId);
    if (!worker) return;
 
    // 유휴 타이머 제거
    this.clearIdleTimer(workerId);
 
    try {
      // 워커 종료
      await worker.terminate();
 
      // 워커 제거
      this.workers.delete(workerId);
      this.workerStatus.delete(workerId);
    } catch (error) {
      console.error(`워커(${workerId}) 해제 중 오류:`, error);
    }
  }
 
  /**
   * 유휴 워커 가져오기
   * @returns 유휴 워커 또는 undefined
   */
  getIdleWorker(): IWorker | undefined {
    for (const [workerId, status] of this.workerStatus.entries()) {
      if (status === WorkerStatus.IDLE) {
        return this.workers.get(workerId);
      }
    }
    return undefined;
  }
 
  /**
   * 워커 상태 가져오기
   * @param workerId 워커 ID
   * @returns 워커 상태
   */
  getWorkerStatus(workerId: string): WorkerStatus {
    return this.workerStatus.get(workerId) || WorkerStatus.UNKNOWN;
  }
 
  /**
   * 워커 가져오기
   * @param workerId 워커 ID
   * @returns 워커 또는 undefined
   */
  getWorker(workerId: string): IWorker | undefined {
    return this.workers.get(workerId);
  }
 
  /**
   * 모든 워커 가져오기
   * @returns 모든 워커 배열
   */
  getAllWorkers(): IWorker[] {
    return Array.from(this.workers.values());
  }
 
  /**
   * 워커 상태 설정
   * @param workerId 워커 ID
   * @param status 워커 상태
   */
  setWorkerStatus(workerId: string, status: WorkerStatus): void {
    const worker = this.workers.get(workerId);
    if (!worker) return;
 
    this.workerStatus.set(workerId, status);
 
    // 상태가 IDLE이면 유휴 타이머 설정
    Iif (status === WorkerStatus.IDLE) {
      this.setIdleTimer(workerId);
    } else {
      this.clearIdleTimer(workerId);
    }
  }
 
  /**
   * 워커 매니저 통계 가져오기
   * @returns 워커 매니저 통계
   */
  getStats(): WorkerManagerStats {
    let activeWorkers = 0;
    let idleWorkers = 0;
 
    for (const status of this.workerStatus.values()) {
      if (status === WorkerStatus.BUSY) {
        activeWorkers++;
      } else if (status === WorkerStatus.IDLE) {
        idleWorkers++;
      }
    }
 
    return {
      totalWorkers: this.workers.size,
      activeWorkers,
      idleWorkers,
    };
  }
 
  /**
   * 최소 워커 수 유지
   */
  ensureMinWorkers(): void {
    Iif (this.isClosing) return;
 
    const currentWorkerCount = this.workers.size;
    const minWorkers = this.config.minWorkers;
 
    // 현재 워커 수가 최소 워커 수보다 적으면 워커 추가
    for (let i = currentWorkerCount; i < minWorkers; i++) {
      this.createWorker();
    }
  }
 
  /**
   * 모든 워커 종료
   * @param force 강제 종료 여부
   * @returns 프로미스
   */
  async closeAll(force: boolean = false): Promise<void> {
    this.isClosing = true;
 
    // 모든 유휴 타이머 제거
    for (const workerId of this.idleTimers.keys()) {
      this.clearIdleTimer(workerId);
    }
 
    // 모든 워커 종료
    const terminatePromises = [];
    for (const [workerId, worker] of this.workers.entries()) {
      terminatePromises.push(
        worker.terminate().catch((error) => {
          console.error(`워커(${workerId}) 종료 중 오류:`, error);
        })
      );
    }
 
    // 모든 종료 작업 완료 대기
    await Promise.all(terminatePromises);
 
    // 모든 맵 초기화
    this.workers.clear();
    this.workerStatus.clear();
  }
 
  /**
   * 유휴 타이머 설정
   * @param workerId 워커 ID
   */
  private setIdleTimer(workerId: string): void {
    // 기존 타이머 제거
    this.clearIdleTimer(workerId);
 
    // 새 타이머 설정
    const idleTimeout = this.config.idleTimeout;
    if (idleTimeout <= 0 || this.workers.size <= this.config.minWorkers) {
      return;
    }
 
    const timer = setTimeout(() => {
      // 최소 워커 수 확인
      Iif (this.workers.size <= this.config.minWorkers) {
        return;
      }
 
      // 워커 상태 확인
      const status = this.workerStatus.get(workerId);
      if (status === WorkerStatus.IDLE) {
        // 유휴 워커 종료
        this.releaseWorker(workerId);
      }
    }, idleTimeout);
 
    this.idleTimers.set(workerId, timer);
  }
 
  /**
   * 유휴 타이머 제거
   * @param workerId 워커 ID
   */
  private clearIdleTimer(workerId: string): void {
    const timer = this.idleTimers.get(workerId);
    if (timer) {
      clearTimeout(timer);
      this.idleTimers.delete(workerId);
    }
  }
}