All files / src/exporters rabbitmq.js

31.52% Statements 29/92
23.4% Branches 11/47
20.83% Functions 5/24
31.81% Lines 28/88

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          2x 2x     2x 2x       19x 19x 19x 19x 19x 19x 19x   2x       2x 2x 1x   1x           1x 1x     1x     1x           1x             1x 1x         1x   1x                                                                                                                                                                                 1x                                                                             8x                                                                                                         2x      
/**
 * RabbitMQ Exporter for OpenTelemetry
 * Sends traces, metrics, and logs to RabbitMQ
 */
 
const amqp = require('amqplib');
const { ExportResult } = require('@opentelemetry/core');
 
// Fallback if ExportResult is not available
const ExportResultSuccess = ExportResult?.SUCCESS || { code: 0 };
const ExportResultFailed = ExportResult?.FAILED || { code: 1 };
 
class RabbitMQExporter {
  constructor(config, type = 'traces') {
    this.config = config;
    this.type = type; // traces, metrics, or logs
    this.connection = null;
    this.channel = null;
    this.connected = false;
    this.queue = [];
    this.maxQueueSize = config.maxQueueSize || 1000;
 
    this.connect();
  }
 
  async connect() {
    try {
      this.connection = await amqp.connect(this.config.url);
      this.channel = await this.connection.createChannel();
 
      await this.channel.assertExchange(
        this.config.exchange,
        'topic',
        { durable: true }
      );
 
      this.connected = true;
      console.log(`[RabbitMQ Exporter] Connected for ${this.type}`);
 
      // Process queued items
      this.flushQueue();
 
      // Handle connection errors
      this.connection.on('error', (err) => {
        console.error('[RabbitMQ Exporter] Connection error:', err);
        this.connected = false;
        this.reconnect();
      });
 
      this.connection.on('close', () => {
        console.log('[RabbitMQ Exporter] Connection closed');
        this.connected = false;
        this.reconnect();
      });
 
    } catch (error) {
      console.error('[RabbitMQ Exporter] Failed to connect:', error);
      this.reconnect();
    }
  }
 
  reconnect() {
    Iif (this.reconnectTimer) return;
 
    this.reconnectTimer = setTimeout(() => {
      this.reconnectTimer = null;
      this.connect();
    }, 5000);
  }
 
  /**
   * Export spans to RabbitMQ
   */
  export(spans, resultCallback) {
    if (!Array.isArray(spans)) {
      spans = [spans];
    }
 
    const telemetryData = spans.map(span => this.transformSpan(span));
 
    telemetryData.forEach(data => {
      this.send(data);
    });
 
    if (resultCallback) {
      resultCallback({ code: ExportResultCode.SUCCESS });
    }
 
    return ExportResultSuccess;
  }
 
  /**
   * Transform OpenTelemetry span to our format
   */
  transformSpan(span) {
    const spanContext = span.spanContext();
    const attributes = {};
 
    if (span.attributes) {
      for (const [key, value] of Object.entries(span.attributes)) {
        attributes[key] = value;
      }
    }
 
    return {
      trace_id: spanContext.traceId,
      span_id: spanContext.spanId,
      parent_span_id: span.parentSpanId,
      service_name: span.resource?.attributes?.['service.name'] || 'unknown',
      operation_name: span.name,
      start_time: new Date(span.startTime[0] * 1000 + span.startTime[1] / 1000000).toISOString(),
      end_time: span.endTime ? new Date(span.endTime[0] * 1000 + span.endTime[1] / 1000000).toISOString() : null,
      status_code: span.status?.code || 0,
      attributes: attributes
    };
  }
 
  /**
   * Send data to RabbitMQ
   */
  send(data) {
    if (!this.connected) {
      // Queue if not connected
      if (this.queue.length < this.maxQueueSize) {
        this.queue.push(data);
      }
      return;
    }
 
    try {
      const routingKey = `telemetry.${this.type}.${data.service_name}`;
      const message = Buffer.from(JSON.stringify(data));
 
      this.channel.publish(
        this.config.exchange,
        routingKey,
        message,
        { persistent: true }
      );
    } catch (error) {
      console.error('[RabbitMQ Exporter] Send error:', error);
 
      // Re-queue on error
      if (this.queue.length < this.maxQueueSize) {
        this.queue.push(data);
      }
    }
  }
 
  /**
   * Flush queued messages
   */
  flushQueue() {
    Eif (!this.connected || this.queue.length === 0) return;
 
    const items = this.queue.splice(0, this.queue.length);
    items.forEach(data => this.send(data));
  }
 
  /**
   * Shutdown exporter
   */
  async shutdown() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
 
    if (this.channel) {
      await this.channel.close();
    }
 
    if (this.connection) {
      await this.connection.close();
    }
 
    return ExportResultSuccess;
  }
 
  /**
   * Force flush
   */
  async forceFlush() {
    this.flushQueue();
    return ExportResultSuccess;
  }
}
 
/**
 * Metrics exporter
 */
class RabbitMQMetricExporter extends RabbitMQExporter {
  constructor(config) {
    super(config, 'metrics');
  }
 
  export(metrics, resultCallback) {
    const telemetryData = this.transformMetrics(metrics);
 
    telemetryData.forEach(data => {
      this.send(data);
    });
 
    if (resultCallback) {
      resultCallback({ code: ExportResultCode.SUCCESS });
    }
 
    return ExportResultSuccess;
  }
 
  transformMetrics(metrics) {
    const result = [];
 
    metrics.resourceMetrics.forEach(resourceMetric => {
      const serviceName = resourceMetric.resource.attributes['service.name'] || 'unknown';
 
      resourceMetric.scopeMetrics.forEach(scopeMetric => {
        scopeMetric.metrics.forEach(metric => {
          metric.dataPoints.forEach(dataPoint => {
            result.push({
              timestamp: new Date(dataPoint.startTime[0] * 1000).toISOString(),
              service_name: serviceName,
              metric_name: metric.descriptor.name,
              metric_type: this.getMetricType(metric.descriptor.type),
              value: dataPoint.value,
              unit: metric.descriptor.unit || '',
              attributes: dataPoint.attributes || {}
            });
          });
        });
      });
    });
 
    return result;
  }
 
  getMetricType(type) {
    const types = {
      0: 'counter',
      1: 'histogram',
      2: 'gauge'
    };
    return types[type] || 'gauge';
  }
}
 
module.exports = {
  RabbitMQExporter,
  RabbitMQMetricExporter
};