All files / src/services InstanceConnectionPool.ts

98.82% Statements 84/85
90.24% Branches 37/41
100% Functions 16/16
98.78% Lines 81/82

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 374 375 376 377 378 379 380 381                            112x 112x       112x                                                                                                                   112x                                                                                           112x 112x   41x       41x             56x 56x                         44x 44x     44x 37x             7x   7x   5x 4x 4x     4x     4x 4x 1x   3x       3x 1x 1x   1x       1x       2x 2x     1x       7x                   11x 11x   11x 7x     11x             6x                         13x 13x   13x   10x                         2x 2x   2x 1x 1x 1x               42x 42x 42x 42x             46x 40x 40x               44x   44x 44x 8x       36x 36x   36x           36x                     36x   36x 1x 1x           36x 36x                 36x     36x   36x                             70x     70x 2x       70x 2x       70x 1x     70x      
/**
 * Instance Connection Pool
 *
 * Manages per-instance HTTP/2 connection pools with keepalive support.
 * Each GitLab instance gets its own connection pool for:
 * - HTTP/2 multiplexing (multiple requests over single connection)
 * - Connection keepalive (reuse connections across requests)
 * - Per-instance TLS configuration
 * - Thread-safe concurrent access
 *
 * This solves the singleton endpoint mutation problem by providing
 * isolated clients per instance instead of mutating a shared client.
 */
 
import { GraphQLClient } from "../graphql/client.js";
import { logInfo, logDebug, logWarn } from "../logger.js";
import { GitLabInstanceConfig } from "../config/instances-schema.js";
 
// Dynamic require to avoid TypeScript analyzing complex undici types at compile time
const undici = require("undici") as {
  Agent: new (opts?: UndiciAgentOptions) => UndiciAgent;
  Pool: new (origin: string, opts?: UndiciPoolOptions) => UndiciPool;
};
 
/**
 * Undici Agent options for connection pooling
 */
interface UndiciAgentOptions {
  /** Maximum number of connections per origin */
  connections?: number;
  /** Keep-alive timeout in milliseconds */
  keepAliveTimeout?: number;
  /** Maximum keep-alive requests per connection */
  keepAliveMaxTimeout?: number;
  /** Pipeline connections (HTTP/1.1 only) */
  pipelining?: number;
  /** TLS options */
  connect?: {
    rejectUnauthorized?: boolean;
    ca?: Buffer | string;
  };
}
 
interface UndiciPoolOptions extends UndiciAgentOptions {
  /** Factory for creating connections */
  factory?: unknown;
}
 
interface UndiciAgent {
  destroy(): Promise<void>;
}
 
interface UndiciPool extends UndiciAgent {
  stats: {
    connected: number;
    free: number;
    pending: number;
    queued: number;
    running: number;
    size: number;
  };
}
 
/**
 * Connection pool configuration
 */
export interface ConnectionPoolConfig {
  /** Maximum connections per instance (default: 10) */
  maxConnections: number;
  /** Keep-alive timeout in ms (default: 30000) */
  keepAliveTimeout: number;
  /** Maximum keep-alive timeout in ms (default: 300000 = 5 min) */
  keepAliveMaxTimeout: number;
  /** HTTP/1.1 pipelining depth (default: 1 = disabled) */
  pipelining: number;
}
 
const DEFAULT_POOL_CONFIG: ConnectionPoolConfig = {
  maxConnections: 10,
  keepAliveTimeout: 30000, // 30 seconds
  keepAliveMaxTimeout: 300000, // 5 minutes
  pipelining: 1, // Disabled by default (safer)
};
 
/**
 * Per-instance connection entry
 */
interface ConnectionEntry {
  /** HTTP connection pool (Undici Pool) */
  pool: UndiciPool;
  /** GraphQL client using this pool */
  graphqlClient: GraphQLClient;
  /** GraphQL endpoint URL */
  graphqlEndpoint: string;
  /** Instance base URL */
  baseUrl: string;
  /** TLS skip verify setting */
  insecureSkipVerify: boolean;
  /** Created timestamp */
  createdAt: Date;
  /** Last used timestamp */
  lastUsedAt: Date;
}
 
/**
 * Pool statistics for monitoring
 */
export interface PoolStats {
  baseUrl: string;
  graphqlEndpoint: string;
  connected: number;
  free: number;
  pending: number;
  queued: number;
  running: number;
  size: number;
  createdAt: Date;
  lastUsedAt: Date;
}
 
/**
 * Singleton managing per-instance connection pools
 */
export class InstanceConnectionPool {
  private static instance: InstanceConnectionPool | null = null;
 
  private pools = new Map<string, ConnectionEntry>();
  private config: ConnectionPoolConfig;
 
  private constructor(config?: Partial<ConnectionPoolConfig>) {
    this.config = { ...DEFAULT_POOL_CONFIG, ...config };
  }
 
  /**
   * Get singleton instance
   */
  public static getInstance(config?: Partial<ConnectionPoolConfig>): InstanceConnectionPool {
    InstanceConnectionPool.instance ??= new InstanceConnectionPool(config);
    return InstanceConnectionPool.instance;
  }
 
  /**
   * Get or create a GraphQL client for an instance
   *
   * This is the primary method for getting a thread-safe GraphQL client
   * that doesn't require endpoint mutation.
   */
  public getGraphQLClient(
    instanceConfig: GitLabInstanceConfig,
    authHeaders?: Record<string, string>
  ): GraphQLClient {
    const entry = this.getOrCreateEntry(instanceConfig);
    entry.lastUsedAt = new Date();
 
    // If no auth headers are provided, return the shared per-instance client directly.
    if (!authHeaders) {
      return entry.graphqlClient;
    }
 
    // When auth headers are provided, avoid mutating the shared client's default headers,
    // which could cause cross-session header leakage. Instead, return a lightweight proxy
    // that injects these headers into each request while delegating all other behavior
    // to the underlying pooled client.
    const baseClient = entry.graphqlClient;
    type RequestFn = (...fnArgs: unknown[]) => unknown;
    const clientWithAuth = new Proxy(baseClient, {
      get(target, prop: string | symbol, receiver): unknown {
        if (prop === "request" || prop === "rawRequest") {
          const original = (target as unknown as Record<string, unknown>)[prop];
          Iif (typeof original !== "function") {
            return Reflect.get(target, prop, receiver) as unknown;
          }
          return (...args: unknown[]): unknown => {
            // graphql-request style: request(document, variables?, requestHeaders?)
            // Args: [doc] | [doc, vars] | [doc, vars, headers]
            const extraHeaders = authHeaders ?? {};
            if (Object.keys(extraHeaders).length === 0) {
              return (original as RequestFn).apply(target, args);
            }
            const adjustedArgs = [...args];
 
            // Only merge if 3+ args (last arg is requestHeaders)
            // For 1-2 args, append headers as new argument
            if (args.length >= 3) {
              const lastArg = adjustedArgs[adjustedArgs.length - 1];
              Eif (lastArg && typeof lastArg === "object" && !Array.isArray(lastArg)) {
                // Merge into existing request headers
                adjustedArgs[adjustedArgs.length - 1] = {
                  ...(lastArg as Record<string, string>),
                  ...extraHeaders,
                };
                return (original as RequestFn).apply(target, adjustedArgs);
              }
            }
            // Append headers as new argument
            adjustedArgs.push(extraHeaders);
            return (original as RequestFn).apply(target, adjustedArgs);
          };
        }
        return Reflect.get(target, prop, receiver) as unknown;
      },
    }) as unknown as GraphQLClient;
 
    return clientWithAuth;
  }
 
  /**
   * Get the Undici pool for an instance (for use with enhancedFetch)
   *
   * Returns undefined if instance is not yet initialized - caller should
   * use default global dispatcher in that case.
   */
  public getDispatcher(baseUrl: string): UndiciPool | undefined {
    const normalizedUrl = this.normalizeUrl(baseUrl);
    const entry = this.pools.get(normalizedUrl);
 
    if (entry) {
      entry.lastUsedAt = new Date();
    }
 
    return entry?.pool;
  }
 
  /**
   * Get pool statistics for all instances
   */
  public getStats(): PoolStats[] {
    return Array.from(this.pools.values()).map(entry => ({
      baseUrl: entry.baseUrl,
      graphqlEndpoint: entry.graphqlEndpoint,
      ...entry.pool.stats,
      createdAt: entry.createdAt,
      lastUsedAt: entry.lastUsedAt,
    }));
  }
 
  /**
   * Get pool statistics for a specific instance
   */
  public getInstanceStats(baseUrl: string): PoolStats | undefined {
    const normalizedUrl = this.normalizeUrl(baseUrl);
    const entry = this.pools.get(normalizedUrl);
 
    if (!entry) return undefined;
 
    return {
      baseUrl: entry.baseUrl,
      graphqlEndpoint: entry.graphqlEndpoint,
      ...entry.pool.stats,
      createdAt: entry.createdAt,
      lastUsedAt: entry.lastUsedAt,
    };
  }
 
  /**
   * Destroy a specific instance's pool
   */
  public async destroyPool(baseUrl: string): Promise<void> {
    const normalizedUrl = this.normalizeUrl(baseUrl);
    const entry = this.pools.get(normalizedUrl);
 
    if (entry) {
      await entry.pool.destroy();
      this.pools.delete(normalizedUrl);
      logDebug("Connection pool destroyed", { baseUrl: normalizedUrl });
    }
  }
 
  /**
   * Destroy all pools (cleanup on shutdown)
   */
  public async destroyAll(): Promise<void> {
    const destroyPromises = Array.from(this.pools.values()).map(entry => entry.pool.destroy());
    await Promise.all(destroyPromises);
    this.pools.clear();
    logInfo("All connection pools destroyed");
  }
 
  /**
   * Reset singleton (for testing)
   */
  public static async resetInstance(): Promise<void> {
    if (InstanceConnectionPool.instance) {
      await InstanceConnectionPool.instance.destroyAll();
      InstanceConnectionPool.instance = null;
    }
  }
 
  /**
   * Get or create connection entry for an instance
   */
  private getOrCreateEntry(instanceConfig: GitLabInstanceConfig): ConnectionEntry {
    const normalizedUrl = this.normalizeUrl(instanceConfig.url);
 
    let entry = this.pools.get(normalizedUrl);
    if (entry) {
      return entry;
    }
 
    // Create new pool and client
    entry = this.createEntry(instanceConfig, normalizedUrl);
    this.pools.set(normalizedUrl, entry);
 
    logInfo("Connection pool created for instance", {
      baseUrl: normalizedUrl,
      maxConnections: this.config.maxConnections,
      keepAliveTimeout: this.config.keepAliveTimeout,
    });
 
    return entry;
  }
 
  /**
   * Create a new connection entry
   */
  private createEntry(
    instanceConfig: GitLabInstanceConfig,
    normalizedUrl: string
  ): ConnectionEntry {
    // Build TLS options based on instance config
    const connectOptions: { rejectUnauthorized?: boolean; ca?: Buffer | string } = {};
 
    if (instanceConfig.insecureSkipVerify) {
      connectOptions.rejectUnauthorized = false;
      logWarn("TLS verification disabled for instance", { url: normalizedUrl });
    }
 
    // Create Undici Pool for this instance.
    // Undici Pool expects an origin (scheme + host + port), not a full URL with path.
    // For subpath-deployed GitLab (e.g., https://example.com/gitlab), we extract just the origin.
    const poolOrigin = new URL(normalizedUrl).origin;
    const pool = new undici.Pool(poolOrigin, {
      connections: this.config.maxConnections,
      keepAliveTimeout: this.config.keepAliveTimeout,
      keepAliveMaxTimeout: this.config.keepAliveMaxTimeout,
      pipelining: this.config.pipelining,
      connect: Object.keys(connectOptions).length > 0 ? connectOptions : undefined,
    });
 
    // Derive GraphQL endpoint
    const graphqlEndpoint = `${normalizedUrl}/api/graphql`;
 
    // Create GraphQL client with empty headers (OAuth tokens added per-request)
    const graphqlClient = new GraphQLClient(graphqlEndpoint, {});
 
    return {
      pool,
      graphqlClient,
      graphqlEndpoint,
      baseUrl: normalizedUrl,
      insecureSkipVerify: instanceConfig.insecureSkipVerify ?? false,
      createdAt: new Date(),
      lastUsedAt: new Date(),
    };
  }
 
  /**
   * Normalize URL for consistent lookup (matches InstanceRegistry logic)
   */
  private normalizeUrl(url: string): string {
    let normalized = url;
 
    // Remove trailing slash
    if (normalized.endsWith("/")) {
      normalized = normalized.slice(0, -1);
    }
 
    // Remove /api/v4 suffix
    if (normalized.endsWith("/api/v4")) {
      normalized = normalized.slice(0, -7);
    }
 
    // Remove /api/graphql suffix
    if (normalized.endsWith("/api/graphql")) {
      normalized = normalized.slice(0, -12);
    }
 
    return normalized;
  }
}