All files / src/logging request-tracker.ts

92.92% Statements 105/113
78.72% Branches 37/47
100% Functions 31/31
99.02% Lines 102/103

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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414                                    105x   105x 105x                         105x         105x 229x           105x 11x           105x       1x                 105x 69x       69x             2x             64x                                     33x   32x                 32x   32x             25x             5x 5x   4x 4x 3x     4x                     4x 4x   4x 4x 4x     4x                     3x 3x   3x             2x 2x   2x             2x 2x   2x 2x             3x 3x   2x             3x 3x   3x               3x 3x   3x                     4x 4x 1x 1x       3x     3x   3x 1x       2x 2x         2x     2x     2x               1x 1x   1x 1x   1x             4x             3x             37x                       23x 23x 1x                     99x 99x 1x               2x 2x 1x               1x 1x 1x               24x 24x 1x               2x 2x 1x               23x 23x 1x               5x 5x 1x                     105x         105x 205x 205x           105x 31x    
/**
 * Request Tracker
 *
 * Implements request stack aggregation pattern: collect all events during a request
 * lifecycle and output a single condensed log line when the request completes.
 *
 * Lifecycle:
 * 1. Request arrives -> openStack() -> Record start time, client info
 * 2. Events during request -> setTool(), setGitLabResponse(), addDetail()
 * 3. Request completes -> closeStack() -> Calculate duration, output log
 *
 * Stack closes on: success response, error, or disconnect/timeout
 *
 * Request Context:
 * Uses AsyncLocalStorage to track current requestId across async operations.
 * This allows setTool/setGitLabResponse/addDetail to work without explicit requestId.
 */
 
import { AsyncLocalStorage } from "async_hooks";
import type { RequestStack } from "./types.js";
import { formatAccessLog, createAccessLogEntry } from "./access-log.js";
import { logger, LOG_JSON, logDebug } from "../logger.js";
 
/**
 * Request context stored in AsyncLocalStorage
 */
export interface RequestContext {
  requestId: string;
}
 
/**
 * AsyncLocalStorage for request context
 * Allows tracking of current request across async operations
 */
const requestContext = new AsyncLocalStorage<RequestContext>();
 
/**
 * Get current request ID from async context
 */
export function getCurrentRequestId(): string | undefined {
  return requestContext.getStore()?.requestId;
}
 
/**
 * Run a function with request context
 */
export function runWithRequestContext<T>(requestId: string, fn: () => T): T {
  return requestContext.run({ requestId }, fn);
}
 
/**
 * Run an async function with request context
 */
export async function runWithRequestContextAsync<T>(
  requestId: string,
  fn: () => Promise<T>
): Promise<T> {
  return requestContext.run({ requestId }, fn);
}
 
/**
 * Request tracker manages request stacks for concurrent requests.
 *
 * Uses requestId as key to track multiple concurrent requests (especially in HTTP mode).
 * Each request gets its own stack that accumulates events until completion.
 */
export class RequestTracker {
  private stacks: Map<string, RequestStack> = new Map();
  private enabled: boolean;
 
  constructor(enabled = true) {
    this.enabled = enabled;
  }
 
  /**
   * Check if condensed logging is enabled
   */
  isEnabled(): boolean {
    return this.enabled;
  }
 
  /**
   * Enable or disable condensed logging
   */
  setEnabled(enabled: boolean): void {
    this.enabled = enabled;
  }
 
  /**
   * Open a new request stack when request arrives
   *
   * @param requestId - Unique identifier for this request
   * @param clientIp - Client IP address
   * @param method - HTTP method
   * @param path - Request path
   * @param sessionId - Optional session ID (MCP or OAuth)
   */
  openStack(
    requestId: string,
    clientIp: string,
    method: string,
    path: string,
    sessionId?: string
  ): void {
    if (!this.enabled) return;
 
    const stack: RequestStack = {
      startTime: Date.now(),
      clientIp,
      method,
      path,
      sessionId,
      details: {},
    };
 
    this.stacks.set(requestId, stack);
 
    logDebug("Request stack opened", { requestId, clientIp, method, path });
  }
 
  /**
   * Get the current stack for a request
   */
  getStack(requestId: string): RequestStack | undefined {
    return this.stacks.get(requestId);
  }
 
  /**
   * Set tool name and action for the request
   */
  setTool(requestId: string, tool: string, action?: string): void {
    const stack = this.stacks.get(requestId);
    if (!stack) return;
 
    stack.tool = tool;
    if (action) {
      stack.action = action;
    }
 
    logDebug("Tool set on request stack", { requestId, tool, action });
  }
 
  /**
   * Set GitLab API response information
   */
  setGitLabResponse(
    requestId: string,
    status: number | "timeout" | "error",
    durationMs?: number
  ): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    stack.gitlabStatus = status;
    Eif (durationMs !== undefined) {
      stack.gitlabDuration = durationMs;
    }
 
    logDebug("GitLab response set on request stack", {
      requestId,
      gitlabStatus: status,
      gitlabDuration: durationMs,
    });
  }
 
  /**
   * Add a detail key-value pair to the request
   */
  addDetail(requestId: string, key: string, value: string | number | boolean): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    stack.details[key] = value;
  }
 
  /**
   * Add multiple details at once
   */
  addDetails(requestId: string, details: Record<string, string | number | boolean>): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    Object.assign(stack.details, details);
  }
 
  /**
   * Set error on the request
   */
  setError(requestId: string, error: string): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    stack.error = error;
    stack.details.err = error;
  }
 
  /**
   * Set context path on the request
   */
  setContext(requestId: string, context: string): void {
    const stack = this.stacks.get(requestId);
    if (!stack) return;
 
    stack.context = context;
  }
 
  /**
   * Set read-only mode flag on the request
   */
  setReadOnly(requestId: string, readOnly: boolean): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    stack.readOnly = readOnly;
  }
 
  /**
   * Update session ID on the request
   * Used when session ID is assigned after request stack is opened
   */
  setSessionId(requestId: string, sessionId: string): void {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return;
 
    stack.sessionId = sessionId;
  }
 
  /**
   * Close the request stack and output access log
   *
   * @param requestId - Request identifier
   * @param status - HTTP response status code
   * @returns The formatted access log line (for testing) or undefined if disabled/not found
   */
  closeStack(requestId: string, status: number): string | undefined {
    const stack = this.stacks.get(requestId);
    if (!stack) {
      logDebug("Request stack not found on close", { requestId });
      return undefined;
    }
 
    // Remove from map first to prevent duplicate closes
    this.stacks.delete(requestId);
 
    // Set final status
    stack.status = status;
 
    if (!this.enabled) {
      return undefined;
    }
 
    // Format and log the access entry
    const entry = createAccessLogEntry(stack);
    const logLine = formatAccessLog(entry);
 
    // Output the condensed access log at info level
    // JSON mode: include full accessLog object for log aggregators (Loki, ELK, etc.)
    // Plain mode: message only - prevents pino-pretty from outputting multiline JSON
    Iif (LOG_JSON) {
      logger.info({ accessLog: entry }, logLine);
    } else {
      logger.info(logLine);
    }
 
    return logLine;
  }
 
  /**
   * Close stack due to error without a final status
   * Used when connection is lost before response is sent
   */
  closeStackWithError(requestId: string, error: string): string | undefined {
    const stack = this.stacks.get(requestId);
    Iif (!stack) return undefined;
 
    stack.error = error;
    stack.details.err = error;
 
    return this.closeStack(requestId, 0);
  }
 
  /**
   * Check if a stack exists for a request
   */
  hasStack(requestId: string): boolean {
    return this.stacks.has(requestId);
  }
 
  /**
   * Get current number of open stacks (for diagnostics)
   */
  getOpenStackCount(): number {
    return this.stacks.size;
  }
 
  /**
   * Clear all stacks (for testing or shutdown)
   */
  clear(): void {
    this.stacks.clear();
  }
 
  // ============================================================================
  // Context-aware methods (use current request from AsyncLocalStorage)
  // ============================================================================
 
  /**
   * Set tool for current request (context-aware)
   * Uses AsyncLocalStorage to get current requestId
   */
  setToolForCurrentRequest(tool: string, action?: string): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setTool(requestId, tool, action);
    }
  }
 
  /**
   * Set GitLab response for current request (context-aware)
   */
  setGitLabResponseForCurrentRequest(
    status: number | "timeout" | "error",
    durationMs?: number
  ): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setGitLabResponse(requestId, status, durationMs);
    }
  }
 
  /**
   * Add detail for current request (context-aware)
   */
  addDetailForCurrentRequest(key: string, value: string | number | boolean): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.addDetail(requestId, key, value);
    }
  }
 
  /**
   * Add multiple details for current request (context-aware)
   */
  addDetailsForCurrentRequest(details: Record<string, string | number | boolean>): void {
    const requestId = getCurrentRequestId();
    Eif (requestId) {
      this.addDetails(requestId, details);
    }
  }
 
  /**
   * Set error for current request (context-aware)
   */
  setErrorForCurrentRequest(error: string): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setError(requestId, error);
    }
  }
 
  /**
   * Set context for current request (context-aware)
   */
  setContextForCurrentRequest(context: string): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setContext(requestId, context);
    }
  }
 
  /**
   * Set read-only for current request (context-aware)
   */
  setReadOnlyForCurrentRequest(readOnly: boolean): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setReadOnly(requestId, readOnly);
    }
  }
 
  /**
   * Set session ID for current request (context-aware)
   */
  setSessionIdForCurrentRequest(sessionId: string): void {
    const requestId = getCurrentRequestId();
    if (requestId) {
      this.setSessionId(requestId, sessionId);
    }
  }
}
 
/**
 * Singleton instance of RequestTracker
 *
 * Used throughout the application to track requests.
 * Enable/disable via setEnabled() based on LOG_FORMAT config.
 */
let globalTracker: RequestTracker | null = null;
 
/**
 * Get the global RequestTracker instance
 */
export function getRequestTracker(): RequestTracker {
  globalTracker ??= new RequestTracker();
  return globalTracker;
}
 
/**
 * Reset the global tracker (for testing)
 */
export function resetRequestTracker(): void {
  globalTracker = null;
}