All files / src/lib/monitoring performanceQueries.ts

0% Statements 0/795
100% Branches 0/0
0% Functions 0/1
0% Lines 0/795

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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Performance Query Functions
 *
 * Shared query functions for performance data with filtering, pagination,
 * and aggregation support.
 */

import { prisma } from '@/lib/prisma';
import { calculatePercentile, calculatePerformanceStats } from './percentiles';
import type { Prisma } from '@prisma/client';

// ============================================================================
// Types
// ============================================================================

export interface PerformanceQueryParams {
  // Time range
  startTime?: Date;
  endTime?: Date;
  timeRange?: '1h' | '6h' | '24h' | '7d' | '30d';

  // Filtering
  path?: string;
  method?: string;
  statusCode?: string;
  minDuration?: number;
  maxDuration?: number;

  // Pagination
  page?: number;
  limit?: number;

  // Sorting
  sortBy?: 'duration' | 'timestamp' | 'path' | 'statusCode';
  sortOrder?: 'asc' | 'desc';
}

export interface PaginationInfo {
  page: number;
  limit: number;
  totalCount: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

export interface PerformanceSummary {
  totalRequests: number;
  avgDuration: number;
  maxDuration: number;
  minDuration: number;
  p95Duration: number;
  p99Duration: number;
  successRate: number;
  errorCount: number;
}

export interface HttpMetricRecord {
  id: string;
  method: string;
  path: string;
  statusCode: number;
  duration: number;
  timestamp: Date;
  requestId: string | null;
  userId: number | null;
}

export interface PerformanceDataResponse {
  data: HttpMetricRecord[];
  pagination: PaginationInfo;
  summary: PerformanceSummary;
  filters: {
    appliedFilters: Record<string, unknown>;
    availableTimeRange: { start: Date; end: Date };
  };
}

export interface EndpointDetails {
  path: string;
  summary: {
    totalRequests: number;
    avgDuration: number;
    p50Duration: number;
    p95Duration: number;
    p99Duration: number;
    maxDuration: number;
    successRate: number;
    errorBreakdown: Record<number, number>;
  };
  trends: {
    hourly: Array<{ timestamp: string; avgDuration: number; count: number }>;
    daily: Array<{ timestamp: string; avgDuration: number; count: number }>;
  };
  recentRequests: HttpMetricRecord[];
  slowestRequests: HttpMetricRecord[];
}

export interface SlowRequest extends HttpMetricRecord {
  percentileRank: number;
}

export interface SlowRequestsResponse {
  data: SlowRequest[];
  pagination: PaginationInfo;
  summary: {
    totalSlowRequests: number;
    avgSlowDuration: number;
    maxDuration: number;
    topOffenders: Array<{ path: string; count: number; avgDuration: number }>;
  };
}

export interface AggregationResult {
  groupBy: string;
  metric: string;
  data: Array<{
    key: string;
    value: number;
    count: number;
  }>;
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Get start date from time range preset
 */
export function getStartDateFromRange(range: string): Date {
  const now = new Date();
  switch (range) {
    case '1h':
      return new Date(now.getTime() - 60 * 60 * 1000);
    case '6h':
      return new Date(now.getTime() - 6 * 60 * 60 * 1000);
    case '24h':
      return new Date(now.getTime() - 24 * 60 * 60 * 1000);
    case '7d':
      return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    case '30d':
      return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
    default:
      return new Date(now.getTime() - 24 * 60 * 60 * 1000);
  }
}

/**
 * Parse status code filter (supports exact, range, and class formats)
 * Examples: "200", "4xx", "500-503"
 */
function parseStatusCodeFilter(statusCode: string): Prisma.IntFilter | undefined {
  if (!statusCode) return undefined;

  // Handle status class (e.g., "2xx", "4xx", "5xx")
  if (statusCode.endsWith('xx')) {
    const base = parseInt(statusCode[0], 10) * 100;
    return { gte: base, lt: base + 100 };
  }

  // Handle range (e.g., "500-503")
  if (statusCode.includes('-')) {
    const [min, max] = statusCode.split('-').map(Number);
    return { gte: min, lte: max };
  }

  // Handle exact value
  return { equals: parseInt(statusCode, 10) };
}

/**
 * Build Prisma where clause from query parameters
 */
function buildWhereClause(params: PerformanceQueryParams): Prisma.HttpMetricWhereInput {
  const where: Prisma.HttpMetricWhereInput = {};

  // Time range
  const endTime = params.endTime || new Date();
  let startTime = params.startTime;
  if (params.timeRange) {
    startTime = getStartDateFromRange(params.timeRange);
  }
  if (!startTime) {
    startTime = getStartDateFromRange('24h');
  }

  where.timestamp = { gte: startTime, lte: endTime };

  // Path filter (supports wildcards with *)
  if (params.path) {
    if (params.path.includes('*')) {
      where.path = { contains: params.path.replace(/\*/g, '') };
    } else {
      where.path = params.path;
    }
  }

  // Method filter
  if (params.method) {
    where.method = params.method.toUpperCase();
  }

  // Status code filter
  if (params.statusCode) {
    const statusFilter = parseStatusCodeFilter(params.statusCode);
    if (statusFilter) {
      where.statusCode = statusFilter;
    }
  }

  // Duration filters
  if (params.minDuration !== undefined || params.maxDuration !== undefined) {
    where.duration = {};
    if (params.minDuration !== undefined) {
      where.duration.gte = params.minDuration;
    }
    if (params.maxDuration !== undefined) {
      where.duration.lte = params.maxDuration;
    }
  }

  return where;
}

/**
 * Build Prisma orderBy from query parameters
 */
function buildOrderBy(
  params: PerformanceQueryParams
): Prisma.HttpMetricOrderByWithRelationInput {
  const sortBy = params.sortBy || 'timestamp';
  const sortOrder = params.sortOrder || 'desc';

  return { [sortBy]: sortOrder };
}

// ============================================================================
// Query Functions
// ============================================================================

/**
 * Get paginated performance data with filtering
 */
export async function getPerformanceData(
  params: PerformanceQueryParams
): Promise<PerformanceDataResponse> {
  const page = Math.max(1, params.page || 1);
  const limit = Math.min(200, Math.max(1, params.limit || 50));
  const skip = (page - 1) * limit;

  // Calculate time range for filters response
  const endTime = params.endTime || new Date();
  let startTime = params.startTime;
  if (params.timeRange) {
    startTime = getStartDateFromRange(params.timeRange);
  }
  if (!startTime) {
    startTime = getStartDateFromRange('24h');
  }

  const where = buildWhereClause(params);
  const orderBy = buildOrderBy(params);

  // Execute queries in parallel
  const [data, totalCount, allDurations] = await Promise.all([
    prisma.httpMetric.findMany({
      where,
      orderBy,
      skip,
      take: limit,
    }),
    prisma.httpMetric.count({ where }),
    prisma.httpMetric.findMany({
      where,
      select: { duration: true, statusCode: true },
    }),
  ]);

  // Calculate summary statistics
  const durations = allDurations.map((d) => d.duration);
  const successCount = allDurations.filter(
    (d) => d.statusCode >= 200 && d.statusCode < 400
  ).length;
  const errorCount = allDurations.filter((d) => d.statusCode >= 400).length;

  const stats = calculatePerformanceStats(durations);

  const totalPages = Math.ceil(totalCount / limit);

  return {
    data: data.map((d) => ({
      id: d.id,
      method: d.method,
      path: d.path,
      statusCode: d.statusCode,
      duration: d.duration,
      timestamp: d.timestamp,
      requestId: d.requestId,
      userId: d.userId,
    })),
    pagination: {
      page,
      limit,
      totalCount,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1,
    },
    summary: {
      totalRequests: totalCount,
      avgDuration: stats.avg,
      maxDuration: stats.max,
      minDuration: stats.min,
      p95Duration: stats.p95,
      p99Duration: stats.p99,
      successRate: totalCount > 0 ? (successCount / totalCount) * 100 : 100,
      errorCount,
    },
    filters: {
      appliedFilters: {
        path: params.path,
        method: params.method,
        statusCode: params.statusCode,
        minDuration: params.minDuration,
        maxDuration: params.maxDuration,
        timeRange: params.timeRange,
      },
      availableTimeRange: {
        start: startTime || getStartDateFromRange('24h'),
        end: endTime,
      },
    },
  };
}

/**
 * Get detailed performance data for a specific endpoint
 */
export async function getEndpointDetails(
  encodedPath: string,
  timeRange: string = '24h'
): Promise<EndpointDetails | null> {
  const path = decodeURIComponent(encodedPath);
  const startTime = getStartDateFromRange(timeRange);
  const endTime = new Date();

  const where: Prisma.HttpMetricWhereInput = {
    path,
    timestamp: { gte: startTime, lte: endTime },
  };

  const [metrics, recentRequests, slowestRequests] = await Promise.all([
    prisma.httpMetric.findMany({
      where,
      select: {
        duration: true,
        statusCode: true,
        timestamp: true,
      },
    }),
    prisma.httpMetric.findMany({
      where,
      orderBy: { timestamp: 'desc' },
      take: 10,
    }),
    prisma.httpMetric.findMany({
      where,
      orderBy: { duration: 'desc' },
      take: 10,
    }),
  ]);

  if (metrics.length === 0) {
    return null;
  }

  const durations = metrics.map((m) => m.duration);
  const stats = calculatePerformanceStats(durations);

  // Calculate error breakdown
  const errorBreakdown: Record<number, number> = {};
  for (const m of metrics) {
    if (m.statusCode >= 400) {
      errorBreakdown[m.statusCode] = (errorBreakdown[m.statusCode] || 0) + 1;
    }
  }

  const successCount = metrics.filter(
    (m) => m.statusCode >= 200 && m.statusCode < 400
  ).length;

  // Generate hourly trends (last 24 hours)
  const hourlyMap = new Map<string, { durations: number[]; count: number }>();
  for (let i = 23; i >= 0; i--) {
    const hour = new Date(endTime.getTime() - i * 60 * 60 * 1000);
    hour.setMinutes(0, 0, 0);
    hourlyMap.set(hour.toISOString(), { durations: [], count: 0 });
  }

  for (const m of metrics) {
    const hour = new Date(m.timestamp);
    hour.setMinutes(0, 0, 0);
    const key = hour.toISOString();
    if (hourlyMap.has(key)) {
      const bucket = hourlyMap.get(key)!;
      bucket.durations.push(m.duration);
      bucket.count++;
    }
  }

  const hourly = Array.from(hourlyMap.entries()).map(([timestamp, data]) => ({
    timestamp,
    avgDuration: data.durations.length > 0
      ? data.durations.reduce((a, b) => a + b, 0) / data.durations.length
      : 0,
    count: data.count,
  }));

  // Generate daily trends (last 30 days) - only if timeRange is 7d or 30d
  const dailyMap = new Map<string, { durations: number[]; count: number }>();
  for (let i = 29; i >= 0; i--) {
    const day = new Date(endTime.getTime() - i * 24 * 60 * 60 * 1000);
    day.setHours(0, 0, 0, 0);
    dailyMap.set(day.toISOString(), { durations: [], count: 0 });
  }

  for (const m of metrics) {
    const day = new Date(m.timestamp);
    day.setHours(0, 0, 0, 0);
    const key = day.toISOString();
    if (dailyMap.has(key)) {
      const bucket = dailyMap.get(key)!;
      bucket.durations.push(m.duration);
      bucket.count++;
    }
  }

  const daily = Array.from(dailyMap.entries()).map(([timestamp, data]) => ({
    timestamp,
    avgDuration: data.durations.length > 0
      ? data.durations.reduce((a, b) => a + b, 0) / data.durations.length
      : 0,
    count: data.count,
  }));

  return {
    path,
    summary: {
      totalRequests: metrics.length,
      avgDuration: stats.avg,
      p50Duration: stats.p50,
      p95Duration: stats.p95,
      p99Duration: stats.p99,
      maxDuration: stats.max,
      successRate: metrics.length > 0 ? (successCount / metrics.length) * 100 : 100,
      errorBreakdown,
    },
    trends: { hourly, daily },
    recentRequests: recentRequests.map((r) => ({
      id: r.id,
      method: r.method,
      path: r.path,
      statusCode: r.statusCode,
      duration: r.duration,
      timestamp: r.timestamp,
      requestId: r.requestId,
      userId: r.userId,
    })),
    slowestRequests: slowestRequests.map((r) => ({
      id: r.id,
      method: r.method,
      path: r.path,
      statusCode: r.statusCode,
      duration: r.duration,
      timestamp: r.timestamp,
      requestId: r.requestId,
      userId: r.userId,
    })),
  };
}

/**
 * Get slow requests with configurable threshold
 */
export async function getSlowRequests(params: {
  threshold?: number;
  timeRange?: string;
  path?: string;
  limit?: number;
  page?: number;
}): Promise<SlowRequestsResponse> {
  const threshold = params.threshold || 500;
  const page = Math.max(1, params.page || 1);
  const limit = Math.min(200, Math.max(1, params.limit || 50));
  const skip = (page - 1) * limit;
  const startTime = getStartDateFromRange(params.timeRange || '24h');

  const where: Prisma.HttpMetricWhereInput = {
    timestamp: { gte: startTime },
    duration: { gt: threshold },
  };

  if (params.path) {
    where.path = params.path.includes('*')
      ? { contains: params.path.replace(/\*/g, '') }
      : params.path;
  }

  const [data, totalCount, topOffendersRaw, allDurations] = await Promise.all([
    prisma.httpMetric.findMany({
      where,
      orderBy: { duration: 'desc' },
      skip,
      take: limit,
    }),
    prisma.httpMetric.count({ where }),
    prisma.httpMetric.groupBy({
      by: ['path'],
      where,
      _count: true,
      _avg: { duration: true },
      orderBy: { _count: { path: 'desc' } },
      take: 10,
    }),
    prisma.httpMetric.findMany({
      where: { timestamp: { gte: startTime } },
      select: { duration: true },
      orderBy: { duration: 'asc' },
    }),
  ]);

  const allDurationsSorted = allDurations.map((d) => d.duration);
  const totalPages = Math.ceil(totalCount / limit);

  // Calculate percentile rank for each slow request
  const slowData: SlowRequest[] = data.map((d) => {
    const rank = allDurationsSorted.findIndex((dur) => dur >= d.duration);
    const percentileRank = ((rank / allDurationsSorted.length) * 100);
    return {
      id: d.id,
      method: d.method,
      path: d.path,
      statusCode: d.statusCode,
      duration: d.duration,
      timestamp: d.timestamp,
      requestId: d.requestId,
      userId: d.userId,
      percentileRank: Math.round(percentileRank * 100) / 100,
    };
  });

  const avgSlowDuration = data.length > 0
    ? data.reduce((acc, d) => acc + d.duration, 0) / data.length
    : 0;
  const maxDuration = data.length > 0 ? Math.max(...data.map((d) => d.duration)) : 0;

  return {
    data: slowData,
    pagination: {
      page,
      limit,
      totalCount,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1,
    },
    summary: {
      totalSlowRequests: totalCount,
      avgSlowDuration,
      maxDuration,
      topOffenders: topOffendersRaw.map((o) => ({
        path: o.path,
        count: o._count,
        avgDuration: o._avg.duration || 0,
      })),
    },
  };
}

/**
 * Get aggregated performance metrics
 */
export async function getAggregatedMetrics(params: {
  groupBy: 'path' | 'method' | 'statusCode' | 'hour' | 'day';
  metric: 'count' | 'avgDuration' | 'p95Duration' | 'errorRate';
  timeRange?: string;
  limit?: number;
}): Promise<AggregationResult> {
  const startTime = getStartDateFromRange(params.timeRange || '24h');
  const limit = Math.min(100, Math.max(1, params.limit || 20));

  const where: Prisma.HttpMetricWhereInput = {
    timestamp: { gte: startTime },
  };

  if (params.groupBy === 'hour' || params.groupBy === 'day') {
    // Time-based aggregation
    const metrics = await prisma.httpMetric.findMany({
      where,
      select: {
        duration: true,
        statusCode: true,
        timestamp: true,
      },
    });

    const buckets = new Map<string, { durations: number[]; errors: number; total: number }>();
    const bucketSize = params.groupBy === 'hour' ? 60 * 60 * 1000 : 24 * 60 * 60 * 1000;

    for (const m of metrics) {
      const bucketTime = new Date(
        Math.floor(m.timestamp.getTime() / bucketSize) * bucketSize
      );
      const key = bucketTime.toISOString();

      if (!buckets.has(key)) {
        buckets.set(key, { durations: [], errors: 0, total: 0 });
      }

      const bucket = buckets.get(key)!;
      bucket.durations.push(m.duration);
      bucket.total++;
      if (m.statusCode >= 400) bucket.errors++;
    }

    const data = Array.from(buckets.entries())
      .map(([key, bucket]) => {
        let value: number;
        switch (params.metric) {
          case 'count':
            value = bucket.total;
            break;
          case 'avgDuration':
            value = bucket.durations.length > 0
              ? bucket.durations.reduce((a, b) => a + b, 0) / bucket.durations.length
              : 0;
            break;
          case 'p95Duration':
            value = calculatePercentile(bucket.durations, 95);
            break;
          case 'errorRate':
            value = bucket.total > 0 ? (bucket.errors / bucket.total) * 100 : 0;
            break;
          default:
            value = bucket.total;
        }
        return { key, value, count: bucket.total };
      })
      .sort((a, b) => new Date(a.key).getTime() - new Date(b.key).getTime())
      .slice(-limit);

    return { groupBy: params.groupBy, metric: params.metric, data };
  }

  // Group by path, method, or statusCode
  const groupByField = params.groupBy as 'path' | 'method' | 'statusCode';

  if (params.metric === 'count') {
    const result = await prisma.httpMetric.groupBy({
      by: [groupByField],
      where,
      _count: true,
      orderBy: { _count: { [groupByField]: 'desc' } },
      take: limit,
    });

    return {
      groupBy: params.groupBy,
      metric: params.metric,
      data: result.map((r) => ({
        key: String(r[groupByField]),
        value: r._count,
        count: r._count,
      })),
    };
  }

  // For other metrics, need to fetch raw data and calculate
  const metrics = await prisma.httpMetric.findMany({
    where,
    select: {
      [groupByField]: true,
      duration: true,
      statusCode: true,
    } as Record<string, boolean>,
  });

  const groups = new Map<string, { durations: number[]; errors: number; total: number }>();

  for (const m of metrics) {
    const key = String((m as Record<string, unknown>)[groupByField]);
    if (!groups.has(key)) {
      groups.set(key, { durations: [], errors: 0, total: 0 });
    }
    const group = groups.get(key)!;
    group.durations.push(m.duration);
    group.total++;
    if (m.statusCode >= 400) group.errors++;
  }

  const data = Array.from(groups.entries())
    .map(([key, group]) => {
      let value: number;
      switch (params.metric) {
        case 'avgDuration':
          value = group.durations.length > 0
            ? group.durations.reduce((a, b) => a + b, 0) / group.durations.length
            : 0;
          break;
        case 'p95Duration':
          value = calculatePercentile(group.durations, 95);
          break;
        case 'errorRate':
          value = group.total > 0 ? (group.errors / group.total) * 100 : 0;
          break;
        default:
          value = group.total;
      }
      return { key, value, count: group.total };
    })
    .sort((a, b) => b.value - a.value)
    .slice(0, limit);

  return { groupBy: params.groupBy, metric: params.metric, data };
}

/**
 * Get performance data for export
 */
export async function getExportData(params: {
  startTime?: Date;
  endTime?: Date;
  timeRange?: string;
  path?: string;
  includeRaw?: boolean;
  includeSummary?: boolean;
}): Promise<{
  data: HttpMetricRecord[];
  summary?: PerformanceSummary;
}> {
  const endTime = params.endTime || new Date();
  const startTime = params.startTime || getStartDateFromRange(params.timeRange || '24h');

  const where: Prisma.HttpMetricWhereInput = {
    timestamp: { gte: startTime, lte: endTime },
  };

  if (params.path) {
    where.path = params.path.includes('*')
      ? { contains: params.path.replace(/\*/g, '') }
      : params.path;
  }

  const data = await prisma.httpMetric.findMany({
    where,
    orderBy: { timestamp: 'desc' },
    take: 10000, // Limit export to 10k records
  });

  const result: { data: HttpMetricRecord[]; summary?: PerformanceSummary } = {
    data: data.map((d) => ({
      id: d.id,
      method: d.method,
      path: d.path,
      statusCode: d.statusCode,
      duration: d.duration,
      timestamp: d.timestamp,
      requestId: d.requestId,
      userId: d.userId,
    })),
  };

  if (params.includeSummary !== false) {
    const durations = data.map((d) => d.duration);
    const stats = calculatePerformanceStats(durations);
    const successCount = data.filter(
      (d) => d.statusCode >= 200 && d.statusCode < 400
    ).length;
    const errorCount = data.filter((d) => d.statusCode >= 400).length;

    result.summary = {
      totalRequests: data.length,
      avgDuration: stats.avg,
      maxDuration: stats.max,
      minDuration: stats.min,
      p95Duration: stats.p95,
      p99Duration: stats.p99,
      successRate: data.length > 0 ? (successCount / data.length) * 100 : 100,
      errorCount,
    };
  }

  return result;
}