All files / src/core Reporter.ts

16.9% Statements 59/349
100% Branches 0/0
0% Functions 0/12
16.9% Lines 59/349

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 3501x 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 { DSNInfo, SentryEvent, ErrorEvent } from '../types';
import { getEnvelopeUrl } from '../utils/dsn';
import { now, generateEventId } from '../utils/helper';
import { encodeFields, FIELD_ENCODE_MAP } from '../utils/field-encoder';
import { logDebug, logError } from '../utils/logger';
 
export class Reporter {
  private dsn: DSNInfo;
  private maxRetries: number;
  private retryDelay: number;
  private useShortFields: boolean = true; // 是否使用短字段编码
 
  constructor(dsn: DSNInfo, maxRetries: number, retryDelay: number) {
    this.dsn = dsn;
    this.maxRetries = maxRetries;
    this.retryDelay = retryDelay;
  }
 
  async report(events: SentryEvent[]): Promise<void> {
    logDebug('Reporter', 'report called', { eventCount: events.length });

    if (events.length === 0) {
      logDebug('Reporter', 'report skipped: empty events');
      return;
    }

    const envelope = this.buildEnvelope(events);
    const url = getEnvelopeUrl(this.dsn);
    logDebug('Reporter', 'Envelope built', { envelopeSize: envelope.length, url });
    
    let retries = 0;
    while (retries <= this.maxRetries) {
      try {
        logDebug('Reporter', `Sending request (attempt ${retries + 1}/${this.maxRetries + 1})`);
        await this.send(envelope, false);
        logDebug('Reporter', 'Request succeeded');
        return;
      } catch (e) {
        const status = (e as { status?: number }).status;
        logError('Reporter', `Request failed (attempt ${retries + 1})`, { status, error: e });
        if (status && status >= 400 && status < 500) {
          throw e;
        }
        retries++;
        if (retries > this.maxRetries) {
          logError('Reporter', 'All retries exhausted');
          throw e;
        }
        const backoff = Math.min(this.retryDelay * Math.pow(2, retries - 1), 5000);
        logDebug('Reporter', `Retrying in ${backoff}ms`);
        await this.delay(backoff);
      }
    }
  }
 
  reportSync(events: SentryEvent[]): void {
    if (events.length === 0) return;

    const envelope = this.buildEnvelope(events);

    try {
      const success = this.sendSync(envelope);
      if (success) return;
    } catch {
      // ignore sync errors
    }

    this.sendViaImage(envelope);
  }
 
  /**
   * 构建 Sentry Envelope
   * 
   * 优化:
   * 1. 批量元数据共享 - 同批次共享 release/environment/user
   * 2. 字段短编码 - 常用字段名使用短码
   * 3. 时间戳相对化 - 批次内后续事件用差值
   */
  private buildEnvelope(events: SentryEvent[]): string {
    // 提取公共元数据(从第一个事件)
    const sharedMeta = this.extractSharedMeta(events);

    // 构建 header(包含公共元数据)
    const headerObj: Record<string, unknown> = {
      event_id: generateEventId(),
      sent_at: new Date().toISOString(),
      meta: sharedMeta,
    };

    // 如果启用短字段编码,在 header 中标记
    if (this.useShortFields) {
      headerObj._sf = 1; // short fields flag
    }

    // 时间戳相对化:第一个事件带基准时间,后续事件用差值
    const eventsWithRelativeTs = this.applyRelativeTimestamps(events, headerObj);

    const header = JSON.stringify(headerObj);

    const items: string[] = [header];

    for (const event of eventsWithRelativeTs) {
      // 移除已共享的字段,减少重复
      let strippedEvent: unknown = this.stripSharedFields(event as unknown as SentryEvent, sharedMeta);

      // 短字段编码(如果启用)
      if (this.useShortFields) {
        strippedEvent = encodeFields(strippedEvent as Record<string, unknown>);
      }

      const itemPayload = JSON.stringify(strippedEvent);
      const itemHeader = JSON.stringify({
        type: this.getEnvelopeType(event as unknown as SentryEvent),
        length: itemPayload.length,
      });
      items.push(itemHeader, itemPayload);
    }

    return items.join('\n');
  }
 
  /**
   * 时间戳相对化
   * 
   * 批次内:
   * - 第一个事件:完整时间戳
   * - 后续事件:相对于第一个事件的毫秒差值(用 _dts 字段表示)
   * 
   * 这样可以将时间戳从 13 位数字减少到 2-4 位数字
   */
  private applyRelativeTimestamps(events: SentryEvent[], headerObj: Record<string, unknown>): (SentryEvent | Record<string, unknown>)[] {
    if (events.length <= 1) return events;

    const result: (SentryEvent | Record<string, unknown>)[] = [];
    const baseTimestamp = events[0].timestamp ? new Date(events[0].timestamp).getTime() : Date.now();

    // 在 header 中标记使用相对时间戳
    headerObj._rt = 1; // relative timestamp flag
    headerObj._bt = baseTimestamp; // base timestamp

    for (let i = 0; i < events.length; i++) {
      const event: Record<string, unknown> = { ...events[i] };

      if (i === 0) {
        // 第一个事件保持完整时间戳
        result.push(event as unknown as SentryEvent);
      } else {
        // 后续事件用差值
        const eventTs = event.timestamp ? new Date(event.timestamp as string | number).getTime() : Date.now();
        const delta = eventTs - baseTimestamp;
        
        delete event.timestamp;
        event._dts = delta; // delta timestamp
        
        // 同时处理 start_timestamp(transaction 事件)
        if (event.start_timestamp) {
          const startTs = new Date(event.start_timestamp as string | number).getTime();
          const startDelta = startTs - baseTimestamp;
          delete event.start_timestamp;
          event._dsts = startDelta; // delta start timestamp
        }
        
        result.push(event);
      }
    }

    return result;
  }
 
  /**
   * 提取批次内公共元数据
   */
  private extractSharedMeta(events: SentryEvent[]): Record<string, unknown> {
    if (events.length === 0) return {};

    const firstEvent = events[0];
    const meta: Record<string, unknown> = {};

    // 提取 release(如果所有事件都相同)
    if (firstEvent.release) {
      const allSameRelease = events.every(e => e.release === firstEvent.release);
      if (allSameRelease) {
        meta.release = firstEvent.release;
      }
    }

    // 提取 environment(如果所有事件都相同)
    if (firstEvent.environment) {
      const allSameEnv = events.every(e => e.environment === firstEvent.environment);
      if (allSameEnv) {
        meta.environment = firstEvent.environment;
      }
    }

    // 提取 user(如果所有事件都相同)
    if (firstEvent.user) {
      const allSameUser = events.every(e => 
        JSON.stringify(e.user) === JSON.stringify(firstEvent.user)
      );
      if (allSameUser) {
        meta.user = firstEvent.user;
      }
    }

    // 提取 env(编码后的环境信息)
    const firstEnv = (firstEvent as unknown as Record<string, unknown>).env;
    if (firstEnv) {
      meta.env = firstEnv;
    }

    return meta;
  }
 
  /**
   * 移除已共享的字段,减少重复
   */
  private stripSharedFields(event: SentryEvent, meta: Record<string, unknown>): Record<string, unknown> {
    const stripped: Record<string, unknown> = { ...event };

    // 移除已共享的字段
    if (meta.release && stripped.release === meta.release) {
      delete stripped.release;
    }
    if (meta.environment && stripped.environment === meta.environment) {
      delete stripped.environment;
    }
    if (meta.user && JSON.stringify(stripped.user) === JSON.stringify(meta.user)) {
      delete stripped.user;
    }
    if (meta.env) {
      delete stripped.env;
    }

    return stripped;
  }
 
  private getEnvelopeType(event: SentryEvent): string {
    switch (event.type) {
      case 'error':
        return 'event';
      default:
        return event.type;
    }
  }
 
  private async send(body: string, isSync: boolean = false): Promise<void> {
    const url = getEnvelopeUrl(this.dsn);

    if (navigator.sendBeacon) {
      try {
        const blob = new Blob([body], { type: 'application/x-sentry-envelope' });
        const success = navigator.sendBeacon(url, blob);
        if (success) return;
      } catch {
        // sendBeacon failed, fall through
      }
    }

    if (typeof fetch === 'function') {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 10000);
        const response = await fetch(url, {
          method: 'POST',
          body,
          headers: {
            'Content-Type': 'application/x-sentry-envelope',
          },
          keepalive: true,
          signal: controller.signal,
        });
        clearTimeout(timeoutId);
        if (response.ok) return;
        const err = new Error(`HTTP ${response.status}`) as Error & { status: number };
        err.status = response.status;
        throw err;
      } catch (e) {
        throw e;
      }
    }

    if (typeof XMLHttpRequest !== 'undefined') {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url, !isSync);
        xhr.setRequestHeader('Content-Type', 'application/x-sentry-envelope');
        xhr.timeout = 10000;
        xhr.onload = () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve();
          } else {
            const err = new Error(`HTTP ${xhr.status}`) as Error & { status: number };
            err.status = xhr.status;
            reject(err);
          }
        };
        xhr.onerror = () => reject(new Error('Network error'));
        xhr.ontimeout = () => reject(new Error('Request timeout'));
        xhr.send(body);
      });
    }

    throw new Error('No transport available');
  }
 
  private sendSync(body: string): boolean {
    const url = getEnvelopeUrl(this.dsn);

    if (navigator.sendBeacon) {
      try {
        const blob = new Blob([body], { type: 'application/x-sentry-envelope' });
        return navigator.sendBeacon(url, blob);
      } catch {
        return false;
      }
    }

    if (typeof XMLHttpRequest !== 'undefined') {
      try {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url, false);
        xhr.setRequestHeader('Content-Type', 'application/x-sentry-envelope');
        xhr.send(body);
        return xhr.status >= 200 && xhr.status < 300;
      } catch {
        return false;
      }
    }

    return false;
  }
 
  private sendViaImage(body: string): boolean {
    try {
      const url = getEnvelopeUrl(this.dsn);
      const img = new Image();
      const encoded = encodeURIComponent(btoa(body));
      const separator = url.includes('?') ? '&' : '?';
      img.src = url + separator + 'sentry_data=' + encoded.substring(0, 2000);
      return true;
    } catch {
      return false;
    }
  }
 
  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}