All files / src/common/transports r2.transport.ts

50.94% Statements 54/106
35.84% Branches 19/53
43.75% Functions 7/16
51.51% Lines 51/99

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 26467x 67x 67x 67x                                             67x       14x             14x 14x 14x   14x     14x 14x 14x 14x 14x 14x 14x     14x               14x                             14x 14x                 13x     13x 13x           13x 13x   13x         13x         1x     1x               1x                 1x                                                                   14x     1x         1x 1x 1x   1x 1x   1x 1x   1x 1x 1x                   1x                                                                                                                     14x 14x   14x 14x     14x   14x    
import Transport from 'winston-transport';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { randomUUID } from 'crypto';
import * as https from 'https';
 
interface R2TransportOptions extends Transport.TransportStreamOptions {
  bucket: string;
  prefix?: string;
  flushIntervalMs?: number;
  maxBufferSize?: number;
  requestTimeoutMs?: number;
  maxRetries?: number;
  circuitBreakerThreshold?: number;
}
 
/**
 * Winston transport that buffers log lines in memory and periodically uploads them
 * as JSON Lines files to a Cloudflare R2 bucket (S3-compatible endpoint).
 * 
 * Features:
 * - Exponential backoff retry logic
 * - Circuit breaker pattern to prevent continuous failures
 * - Configurable timeouts
 * - Buffer overflow protection
 * - Graceful degradation on failures
 */
export default class R2Transport extends Transport {
  private r2: S3Client;
  private bucket: string;
  private prefix: string;
  private buffer: string[] = [];
  private readonly flushInterval: NodeJS.Timeout;
  private readonly maxBufferSize: number;
  private readonly requestTimeoutMs: number;
  private readonly maxRetries: number;
  
  // Circuit breaker state
  private failureCount = 0;
  private lastFailureTime: number | null = null;
  private circuitOpen = false;
  private readonly circuitBreakerThreshold: number;
  private readonly circuitBreakerResetMs = 60_000; // 1 minute
 
  constructor(opts: R2TransportOptions) {
    super(opts);
    this.bucket = opts.bucket;
    this.prefix = opts.prefix ?? 'logs/';
    this.maxBufferSize = opts.maxBufferSize ?? 1000;
    this.requestTimeoutMs = opts.requestTimeoutMs ?? 10_000; // 10s default timeout
    this.maxRetries = opts.maxRetries ?? 3;
    this.circuitBreakerThreshold = opts.circuitBreakerThreshold ?? 5;
 
    // Configure HTTP agent with keep-alive and connection pooling for better resilience
    const httpsAgent = new https.Agent({
      keepAlive: true,
      keepAliveMsecs: 1000,
      maxSockets: 50,
      maxFreeSockets: 10,
      timeout: this.requestTimeoutMs,
    });
 
    this.r2 = new S3Client({
      region: process.env.R2_REGION || 'auto',
      endpoint: process.env.R2_ENDPOINT, // e.g. https://<accountid>.r2.cloudflarestorage.com
      forcePathStyle: true,
      requestHandler: {
        httpsAgent,
        requestTimeout: this.requestTimeoutMs,
      } as any,
      credentials: {
        accessKeyId: process.env.R2_ACCESS_KEY_ID || '',
        secretAccessKey: process.env.R2_SECRET_ACCESS_KEY || '',
      },
      maxAttempts: this.maxRetries,
    });
 
    const interval = opts.flushIntervalMs ?? 30_000;
    this.flushInterval = setInterval(() => {
      this.flush().catch((_err) => {
        // Silently handle errors to prevent unhandled promise rejections
        // Errors are already logged in flush method
      });
    }, interval);
  }
 
  log(info: any, next: () => void) {
    setImmediate(() => this.emit('logged', info));
 
    // Prevent buffer overflow - drop oldest entries if buffer is full
    const maxEntries = this.maxBufferSize * 2; // Allow some overflow before dropping
    Iif (this.buffer.length >= maxEntries) {
      const dropped = this.buffer.splice(0, Math.floor(this.maxBufferSize * 0.1)); // Drop 10% oldest
      console.warn(`R2Transport: Buffer overflow, dropped ${dropped.length} log entries`);
    }
 
    // Winston mutates info. Clone shallow.
    const entry = JSON.stringify({ ...info, timestamp: new Date().toISOString() });
    this.buffer.push(entry);
 
    Iif (this.buffer.length >= this.maxBufferSize) {
      this.flush().catch((_err) => {
        // Silently handle errors
      });
    }
    next();
  }
 
  /** Check if circuit breaker should be opened */
  private checkCircuitBreaker(): boolean {
    const now = Date.now();
    
    // Reset circuit breaker if enough time has passed
    Iif (this.circuitOpen && this.lastFailureTime && (now - this.lastFailureTime) > this.circuitBreakerResetMs) {
      this.circuitOpen = false;
      this.failureCount = 0;
      this.lastFailureTime = null;
      return false;
    }
    
    // Open circuit if threshold exceeded
    Iif (this.failureCount >= this.circuitBreakerThreshold) {
      Iif (!this.circuitOpen) {
        this.circuitOpen = true;
        this.lastFailureTime = now;
        console.warn(`R2Transport: Circuit breaker opened after ${this.failureCount} failures`);
      }
      return true;
    }
    
    return this.circuitOpen;
  }
 
  /** Record failure for circuit breaker */
  private recordFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();
  }
 
  /** Record success for circuit breaker */
  private recordSuccess() {
    Iif (this.failureCount > 0) {
      this.failureCount = Math.max(0, this.failureCount - 1); // Decay failures slowly
    }
    Iif (this.circuitOpen) {
      this.circuitOpen = false;
      this.lastFailureTime = null;
      console.info('R2Transport: Circuit breaker closed after successful upload');
    }
  }
 
  /** Determine if error is retryable */
  private isRetryableError(error: any): boolean {
    Iif (!error) return false;
    
    const code = error.code || error.$metadata?.httpStatusCode || error.name;
    const retryableCodes = ['ETIMEDOUT', 'ECONNRESET', 'EHOSTUNREACH', 'ENOTFOUND', 'ECONNREFUSED', 'TimeoutError'];
    const retryableStatusCodes = [408, 429, 500, 502, 503, 504];
    
    return retryableCodes.includes(code) || retryableStatusCodes.includes(code);
  }
 
  /** Flush buffer to R2 with retry logic */
  private async flush() {
    if (this.buffer.length === 0) return;
    
    // Check circuit breaker
    Iif (this.checkCircuitBreaker()) {
      console.warn(`R2Transport: Circuit breaker open, skipping upload (${this.buffer.length} entries buffered)`);
      return;
    }
 
    const body = this.buffer.join('\n') + '\n';
    const entriesToUpload = [...this.buffer];
    this.buffer = [];
 
    const now = new Date();
    const key = `${this.prefix}${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${String(now.getUTCDate()).padStart(2, '0')}/${Date.now()}-${randomUUID()}.jsonl`;
    
    let lastError: any = null;
    const maxRetries = this.maxRetries;
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        await Promise.race([
          this.r2.send(
            new PutObjectCommand({
              Bucket: this.bucket,
              Key: key,
              Body: body,
              ContentType: 'application/json',
            }),
          ),
          new Promise<never>((_, reject) => 
            setTimeout(() => reject(new Error('Request timeout')), this.requestTimeoutMs)
          ),
        ]);
        
        // Success - record and return
        this.recordSuccess();
        return;
      } catch (err: any) {
        lastError = err;
        const isRetryable = this.isRetryableError(err);
        
        Iif (!isRetryable || attempt === maxRetries) {
          // Non-retryable error or max retries reached
          break;
        }
        
        // Exponential backoff with jitter
        const baseDelay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
        const jitter = Math.random() * 200;
        const delay = baseDelay + jitter;
        
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
    
    // All retries failed - re-buffer logs and record failure
    this.recordFailure();
    
    // Re-buffer entries, but prevent unbounded growth
    const spaceAvailable = this.maxBufferSize * 2 - this.buffer.length;
    if (spaceAvailable > 0) {
      const entriesToRebuffer = entriesToUpload.slice(-spaceAvailable);
      this.buffer.unshift(...entriesToRebuffer);
      
      if (entriesToUpload.length > spaceAvailable) {
        const dropped = entriesToUpload.length - spaceAvailable;
        console.error(`R2Transport: Failed to upload ${entriesToUpload.length} entries after ${maxRetries} attempts. Dropped ${dropped} entries due to buffer limits. Error:`, {
          code: lastError?.code || lastError?.name,
          message: lastError?.message,
          $metadata: lastError?.$metadata,
        });
      } else {
        console.error(`R2Transport: Failed to upload ${entriesToUpload.length} entries after ${maxRetries} attempts. Re-buffered for retry. Error:`, {
          code: lastError?.code || lastError?.name,
          message: lastError?.message,
          $metadata: lastError?.$metadata,
        });
      }
    } else {
      console.error(`R2Transport: Failed to upload ${entriesToUpload.length} entries and buffer is full. Dropping entries. Error:`, {
        code: lastError?.code || lastError?.name,
        message: lastError?.message,
        $metadata: lastError?.$metadata,
      });
    }
  }
 
  /** Ensure buffer is flushed on shutdown */
  override close(): void {
    if (this.flushInterval) {
      clearInterval(this.flushInterval);
    }
    if (this.r2 && (this.r2 as any).destroy) {
      (this.r2 as any).destroy();
    }
    // Fire and forget final flush
    this.flush().catch((err) => console.error('R2Transport final flush error', err));
    // Signal that the transport is done - this is critical for Winston
    this.emit('finish');
  }
}