All files / src/plugins PerformancePlugin.ts

12.83% Statements 68/530
100% Branches 0/0
0% Functions 0/23
12.83% Lines 68/530

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 5311x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                           1x 1x                         1x 1x                                     1x 1x           1x 1x                         1x 1x                 1x 1x                                         1x 1x                               1x 1x                               1x 1x                                                                           1x 1x                               1x 1x                                                           1x 1x                               1x 1x                                                                           1x 1x                                             1x 1x                           1x 1x                                                   1x 1x                                 1x 1x                                                   1x 1x                     1x 1x                                     1x 1x                                                                     1x 1x                                                                 1x 1x 1x  
import type { LightPlugin, LightClient, PerformanceEvent, LightConfig, Transaction, Span } from '../types';
import { now, isObject } from '../utils/helper';
 
interface PerformancePluginConfig {
  sampleRate?: number;
  captureLongTasks?: boolean;
  captureResources?: boolean;
  resourceSampleRate?: number;
  longTaskSampleRate?: number;
  captureNavigation?: boolean;
  captureFP?: boolean;
  enablePageLoadTracing?: boolean;  // 是否启用 Page Load Transaction
  maxResourceSpans?: number;        // 最大 Resource Span 数量
}
 
interface VitalMeasurement {
  value: number;
  unit?: string;
  rating?: 'good' | 'needs-improvement' | 'poor';
}
 
class PerformancePlugin implements LightPlugin {
  name = 'performance';
  version = '2.0.0';

  private client!: LightClient;
  private config: PerformancePluginConfig = {
    sampleRate: 0.1,
    captureLongTasks: true,
    captureResources: false,
    resourceSampleRate: 0.01,
    longTaskSampleRate: 0.05,
    captureNavigation: true,
    captureFP: true,
    enablePageLoadTracing: false,
    maxResourceSpans: 50,
  };

  private observers: PerformanceObserver[] = [];
  private onLoad?: () => void;
  private navLoadTimer: ReturnType<typeof setTimeout> | null = null;
  private totalBlockingTime: number = 0;
  private fcpTime: number | null = null;
  private lastLongTaskEndTime: number = 0;
  private ttiReported: boolean = false;
  private ttiTimer: ReturnType<typeof setTimeout> | null = null;

  private pageLoadTransaction: Transaction | null = null;
  private measurements: Record<string, VitalMeasurement> = {};
  private resourceSpanCount: number = 0;
 
  setup(client: LightClient): void {
    this.client = client;
    this.loadConfig();

    if (this.config.enablePageLoadTracing) {
      this.startPageLoadTransaction();
    }

    this.observeWebVitals();
    this.observeLongTasks();
    this.observeNavigation();
    this.observeResources();
  }
 
  private startPageLoadTransaction(): void {
    if (typeof window === 'undefined') return;

    const pageUrl = typeof location !== 'undefined' ? location.pathname : '/';
    const navStart = typeof performance !== 'undefined' && performance.timing?.navigationStart
      ? performance.timing.navigationStart
      : now();

    this.pageLoadTransaction = this.client.startTransaction({
      name: pageUrl,
      op: 'pageload',
      description: `Page load - ${pageUrl}`,
      startTimestamp: navStart,
      type: 'pageload',
      tags: {
        'page.url': pageUrl,
      },
    });
  }
 
  private loadConfig(): void {
    const clientConfig = this.client.config as LightConfig;
    if (clientConfig && isObject(clientConfig.performance)) {
      this.config = { ...this.config, ...(clientConfig.performance as object) };
    }
  }
 
  private shouldSample(type: 'default' | 'resource' | 'longtask' | 'vitals' = 'default'): boolean {
    let rate = this.config.sampleRate ?? 0.1;
    if (type === 'resource') {
      rate = this.config.resourceSampleRate ?? 0.01;
    } else if (type === 'longtask') {
      rate = this.config.longTaskSampleRate ?? 0.05;
    } else if (type === 'vitals') {
      rate = 1;
    }
    if (rate >= 1) return true;
    if (rate <= 0) return false;
    return Math.random() < rate;
  }
 
  private observeWebVitals(): void {
    if (typeof PerformanceObserver === 'undefined') return;

    this.observePaint();
    this.observeLCP();
    this.observeFID();
    this.observeCLS();
    this.observeTTFB();
  }
 
  private observePaint(): void {
    try {
      const po = new PerformanceObserver((entryList) => {
        const fpEntries = entryList.getEntriesByName('first-paint');
        if (fpEntries.length > 0 && this.config.captureFP) {
          this.reportMetric('FP', fpEntries[0].startTime, 'ms', {}, 'vitals');
        }
        const fcpEntries = entryList.getEntriesByName('first-contentful-paint');
        if (fcpEntries.length > 0) {
          this.fcpTime = fcpEntries[0].startTime;
          this.lastLongTaskEndTime = fcpEntries[0].startTime;
          this.reportMetric('FCP', fcpEntries[0].startTime, 'ms', {}, 'vitals');
          this.scheduleTTI();
        }
      });
      po.observe({ type: 'paint', buffered: true });
      this.observers.push(po);
    } catch {
      // Paint observer not supported
    }
  }
 
  private observeLCP(): void {
    try {
      const po = new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries();
        const lastEntry = entries[entries.length - 1] as PerformanceEntry & { renderTime?: number; loadTime?: number };
        if (lastEntry) {
          const value = lastEntry.renderTime || lastEntry.loadTime || lastEntry.startTime;
          this.reportMetric('LCP', value, 'ms', {}, 'vitals');
        }
      });
      po.observe({ type: 'largest-contentful-paint', buffered: true });
      this.observers.push(po);
    } catch {
      // LCP not supported
    }
  }
 
  private observeFID(): void {
    try {
      const po = new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries() as PerformanceEventTiming[];
        if (entries.length > 0) {
          const firstEntry = entries[0];
          const value = firstEntry.processingStart - firstEntry.startTime;
          this.reportMetric('FID', value, 'ms', {}, 'vitals');
        }
      });
      po.observe({ type: 'first-input', buffered: true });
      this.observers.push(po);
    } catch {
      // FID not supported
    }
  }
 
  private observeCLS(): void {
    try {
      let clsValue = 0;
      let sessionValue = 0;
      let sessionEntries: PerformanceEntry[] = [];

      const po = new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries() as unknown as { hadRecentInput?: boolean; value?: number; startTime: number; endTime?: number }[];
        for (const entry of entries) {
          if (!entry.hadRecentInput) {
            const firstSessionEntry = sessionEntries[0];
            const lastSessionEntry = sessionEntries[sessionEntries.length - 1];

            if (
              sessionValue &&
              entry.startTime - (lastSessionEntry?.duration || 0) < 1000 &&
              entry.startTime - firstSessionEntry.startTime < 5000
            ) {
              sessionValue += entry.value || 0;
              sessionEntries.push(entry as unknown as PerformanceEntry);
            } else {
              sessionValue = entry.value || 0;
              sessionEntries = [entry as unknown as PerformanceEntry];
            }

            if (sessionValue > clsValue) {
              clsValue = sessionValue;
              this.reportMetric('CLS', clsValue, '', {}, 'vitals');
            }
          }
        }
      });
      po.observe({ type: 'layout-shift', buffered: true });
      this.observers.push(po);
    } catch {
      // CLS not supported
    }
  }
 
  private observeTTFB(): void {
    try {
      const po = new PerformanceObserver((entryList) => {
        const navEntries = entryList.getEntriesByType('navigation') as PerformanceNavigationTiming[];
        if (navEntries.length > 0) {
          const navEntry = navEntries[0];
          const ttfb = navEntry.responseStart - navEntry.requestStart;
          this.reportMetric('TTFB', Math.max(0, ttfb), 'ms', {}, 'vitals');
        }
      });
      po.observe({ type: 'navigation', buffered: true });
      this.observers.push(po);
    } catch {
      // Navigation timing not supported
    }
  }
 
  private observeLongTasks(): void {
    if (!this.config.captureLongTasks) return;

    try {
      const po = new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries();
        for (const entry of entries) {
          const endTime = entry.startTime + entry.duration;
          if (endTime > this.lastLongTaskEndTime) {
            this.lastLongTaskEndTime = endTime;
          }

          if (this.fcpTime !== null && entry.startTime >= this.fcpTime) {
            const blockingTime = entry.duration - 50;
            if (blockingTime > 0) {
              this.totalBlockingTime += blockingTime;
            }
          }

          this.reportMetric('longtask', entry.duration, 'ms', {}, 'longtask');

          this.scheduleTTI();
        }
      });
      po.observe({ type: 'longtask', buffered: true });
      this.observers.push(po);
    } catch {
      // Long tasks not supported
    }
  }
 
  private scheduleTTI(): void {
    if (this.ttiReported) return;

    if (this.ttiTimer) {
      clearTimeout(this.ttiTimer);
    }

    this.ttiTimer = setTimeout(() => {
      if (this.ttiReported) return;
      this.ttiReported = true;

      const tti = Math.max(this.lastLongTaskEndTime, this.fcpTime || 0);
      this.reportMetric('TTI', tti, 'ms', {}, 'vitals');
      this.reportMetric('TBT', this.totalBlockingTime, 'ms', {}, 'vitals');
    }, 5000);
  }
 
  private observeNavigation(): void {
    if (!this.config.captureNavigation) return;
    if (typeof performance === 'undefined') return;

    this.onLoad = () => {
      this.navLoadTimer = setTimeout(() => {
        const timing = performance.timing;
        if (!timing) return;

        const navigationStart = timing.navigationStart;
        const metrics: Record<string, number> = {
          dom_ready: timing.domContentLoadedEventEnd - navigationStart,
          load_time: timing.loadEventEnd - navigationStart,
          dns: timing.domainLookupEnd - timing.domainLookupStart,
          tcp: timing.connectEnd - timing.connectStart,
          ssl: timing.secureConnectionStart > 0 ? timing.connectEnd - timing.secureConnectionStart : 0,
          ttfb: timing.responseStart - timing.requestStart,
          download: timing.responseEnd - timing.responseStart,
          dom_parse: timing.domInteractive - timing.responseEnd,
        };

        for (const [name, value] of Object.entries(metrics)) {
          if (value > 0) {
            this.reportMetric(name, value, 'ms');
          }
        }

        if (this.pageLoadTransaction && this.pageLoadTransaction.sampled !== false) {
          this.buildNavigationSpans(timing, navigationStart);
          this.finishPageLoadTransaction(timing.loadEventEnd || now());
        }

        this.navLoadTimer = null;
      }, 0);
    };

    window.addEventListener('load', this.onLoad);
  }
 
  private buildNavigationSpans(timing: PerformanceTiming, navigationStart: number): void {
    const spanDefs: Array<{ op: string; desc: string; start: number; end: number }> = [
      { op: 'dns', desc: 'DNS Lookup', start: timing.domainLookupStart, end: timing.domainLookupEnd },
      { op: 'tcp', desc: 'TCP Connection', start: timing.connectStart, end: timing.connectEnd },
      { op: 'ssl', desc: 'SSL/TLS Negotiation', start: timing.secureConnectionStart, end: timing.connectEnd },
      { op: 'ttfb', desc: 'Time to First Byte', start: timing.requestStart, end: timing.responseStart },
      { op: 'response', desc: 'Response Download', start: timing.responseStart, end: timing.responseEnd },
      { op: 'dom_parse', desc: 'DOM Parsing', start: timing.responseEnd, end: timing.domInteractive },
      { op: 'dom_content_loaded', desc: 'DOM Content Loaded', start: timing.domLoading, end: timing.domContentLoadedEventEnd },
      { op: 'load', desc: 'Page Load', start: timing.navigationStart, end: timing.loadEventEnd },
    ];

    for (const def of spanDefs) {
      if (def.start > 0 && def.end > 0 && def.end > def.start) {
        this.createNavigationSpan(
          def.op,
          def.desc,
          def.start,
          def.end
        );
      }
    }
  }
 
  private finishPageLoadTransaction(endTime: number): void {
    if (!this.pageLoadTransaction) return;

    if (Object.keys(this.measurements).length > 0) {
      (this.pageLoadTransaction as unknown as { setData: (k: string, v: unknown) => void }).setData(
        'measurements',
        this.measurements
      );
    }

    this.pageLoadTransaction.setStatus('ok');
    this.pageLoadTransaction.finish(endTime);
    this.pageLoadTransaction = null;
  }
 
  private observeResources(): void {
    if (!this.config.captureResources && !this.config.enablePageLoadTracing) return;
    if (typeof performance === 'undefined') return;

    try {
      const po = new PerformanceObserver((entryList) => {
        const entries = entryList.getEntriesByType('resource') as PerformanceResourceTiming[];
        for (const entry of entries) {
          if (entry.duration > 1000 && this.config.captureResources) {
            this.reportMetric('resource_slow', entry.duration, 'ms', {
              resource_name: entry.name.substring(0, 200),
              resource_type: entry.initiatorType,
            }, 'resource');
          }

          if (this.config.enablePageLoadTracing && this.pageLoadTransaction) {
            this.createResourceSpan(entry);
          }
        }
      });
      po.observe({ type: 'resource', buffered: true });
      this.observers.push(po);
    } catch {
      // Resource timing not supported
    }
  }
 
  private getRating(name: string, value: number): 'good' | 'needs-improvement' | 'poor' {
    const thresholds: Record<string, { good: number; poor: number }> = {
      LCP: { good: 2500, poor: 4000 },
      FCP: { good: 1800, poor: 3000 },
      FP: { good: 1800, poor: 3000 },
      FID: { good: 100, poor: 300 },
      CLS: { good: 0.1, poor: 0.25 },
      TTFB: { good: 800, poor: 1800 },
    };

    const threshold = thresholds[name];
    if (!threshold) return 'good';

    if (value <= threshold.good) return 'good';
    if (value <= threshold.poor) return 'needs-improvement';
    return 'poor';
  }
 
  private reportMetric(name: string, value: number, unit: string, extraTags: Record<string, string> = {}, sampleType: 'default' | 'resource' | 'longtask' | 'vitals' = 'default'): void {
    if (!this.shouldSample(sampleType)) return;

    const rating = this.getRating(name, value);
    
    const event: PerformanceEvent = {
      type: 'performance',
      level: 'info',
      metric: name,
      value: Math.round(value * 100) / 100,
      unit,
      rating,
      timestamp: now(),
      tags: {
        metric: name,
        rating,
        ...extraTags,
      },
    };

    this.client.captureEvent(event);

    if (this.pageLoadTransaction && this.pageLoadTransaction.sampled !== false) {
      this.recordMeasurement(name, value, unit, rating);
    }
  }
 
  private recordMeasurement(name: string, value: number, unit?: string, rating?: 'good' | 'needs-improvement' | 'poor'): void {
    if (!this.pageLoadTransaction) return;

    this.measurements[name] = {
      value: Math.round(value * 100) / 100,
      unit,
      rating,
    };

    this.pageLoadTransaction.setTag(`measurement.${name}.rating`, rating || 'unknown');
  }
 
  private createNavigationSpan(
    op: string,
    description: string,
    startTime: number,
    endTime: number,
    tags?: Record<string, string>
  ): void {
    if (!this.pageLoadTransaction || this.pageLoadTransaction.sampled === false) return;
    if (endTime <= startTime) return;

    const span = this.pageLoadTransaction.startChild({
      op: `browser.${op}`,
      description,
      startTimestamp: startTime,
      tags,
    });

    span.finish(endTime);
  }
 
  private createResourceSpan(entry: PerformanceResourceTiming): void {
    if (!this.pageLoadTransaction || this.pageLoadTransaction.sampled === false) return;

    const maxResources = this.config.maxResourceSpans ?? 50;
    if (this.resourceSpanCount >= maxResources) return;
    this.resourceSpanCount++;

    const timeOrigin = typeof performance !== 'undefined' && performance.timeOrigin
      ? performance.timeOrigin
      : (performance.timing?.navigationStart || 0);
    const startTime = timeOrigin + entry.startTime;
    const endTime = timeOrigin + (entry.responseEnd || entry.duration || entry.startTime);

    if (endTime <= startTime) return;

    const url = entry.name.substring(0, 200);
    const span = this.pageLoadTransaction.startChild({
      op: `resource.${entry.initiatorType || 'other'}`,
      description: url,
      startTimestamp: startTime,
      tags: {
        'resource.type': entry.initiatorType || 'other',
        'resource.url': url,
        'resource.transfer_size': String(entry.transferSize || 0),
        'resource.decoded_size': String(entry.decodedBodySize || 0),
      },
      data: {
        transferSize: entry.transferSize,
        decodedSize: entry.decodedBodySize,
        encodedSize: entry.encodedBodySize,
      },
    });

    span.finish(endTime);
  }
 
  destroy(): void {
    for (const observer of this.observers) {
      try {
        observer.disconnect();
      } catch {
        // ignore
      }
    }
    this.observers = [];

    if (this.ttiTimer) {
      clearTimeout(this.ttiTimer);
      this.ttiTimer = null;
    }

    if (this.navLoadTimer) {
      clearTimeout(this.navLoadTimer);
      this.navLoadTimer = null;
    }

    if (typeof window !== 'undefined' && this.onLoad) {
      window.removeEventListener('load', this.onLoad);
    }

    if (this.pageLoadTransaction) {
      this.pageLoadTransaction.setStatus('internal_error');
      this.pageLoadTransaction.finish();
      this.pageLoadTransaction = null;
    }

    this.measurements = {};
    this.resourceSpanCount = 0;
  }
}
 
export default PerformancePlugin;