# Rebrandly OpenTelemetry SDK for Node.js - Complete Documentation

## Table of Contents

1. [Overview](#overview)
2. [Installation](#installation)
3. [Quick Start](#quick-start)
4. [Core Components](#core-components)
5. [Basic Usage](#basic-usage)
6. [Advanced Usage](#advanced-usage)
7. [AWS Lambda Integration](#aws-lambda-integration)
8. [Express Integration](#express-integration)
9. [Database Instrumentation](#database-instrumentation)
10. [Metrics](#metrics)
11. [Logging](#logging)
12. [Context Propagation](#context-propagation)
13. [Best Practices](#best-practices)
14. [Troubleshooting](#troubleshooting)

## Overview

The Rebrandly OpenTelemetry SDK for Node.js provides comprehensive observability instrumentation for Node.js applications, with built-in support for AWS Lambda functions, Express applications, and automatic context propagation. It combines distributed tracing, metrics collection, and structured logging into a single, production-ready package.

### Key Features

- **Auto-Instrumentation**: Automatic tracing for AWS SDK, databases, and HTTP clients
- **AWS Lambda Optimized**: Specialized handlers with trigger detection and auto-flush
- **Express Integration**: Clean middleware for automatic request tracing
- **Context Propagation**: Automatic W3C Trace Context and AWS message attribute support
- **Knex Database Tracing**: Built-in instrumentation for SQL queries
- **Redis Span Enhancement**: Custom span processor for consistent Redis tracing
- **Structured Logging**: Winston-based logging with automatic trace correlation
- **Production-Ready**: Minimal overhead with efficient batching and export

## Installation

### Using npm

```bash
npm install @rebrandly/rebrandly-otel
```

### Using yarn

```bash
yarn add @rebrandly/rebrandly-otel
```

### Dependencies

The SDK automatically installs:
- OpenTelemetry API and SDK packages
- OTLP exporters for traces, metrics, and logs
- Winston for structured logging
- Auto-instrumentation packages

### Node.js Version

Requires Node.js `^18.19.0 || >=20.6.0` (`engines` in `package.json`), the same range as the OpenTelemetry JS 2.x line the SDK is built on. CI runs the suite on Node 18, 20, 22 and 24, so every supported Lambda `nodejs*` runtime is covered.

The SDK deliberately stays on the OpenTelemetry JS 2.x / 0.2xx line: the 3.x / 0.300 line requires Node >= 22.15 and would break Lambdas still on `nodejs18.x` / `nodejs20.x`.

## Quick Start

### Basic Setup

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

// Initialize (recommended but optional)
otel.initialize();

// Create a span
await otel.span('my_operation', async () => {
    logger.info('Processing operation');
    // Your code here
});

// Force flush before exit
await otel.forceFlush();
```

### Lambda Function

```javascript
const { lambdaHandler, logger } = require('@rebrandly/rebrandly-otel');

const handler = lambdaHandler({ name: 'process-request' })(async (event, context) => {
    logger.info('Processing Lambda request');

    // Your business logic
    const result = await processData(event);

    return {
        statusCode: 200,
        body: JSON.stringify({ result })
    };
});

module.exports = { handler };
```

### Express Application

```javascript
const express = require('express');
const { otel, setupExpress, forceFlush, shutdown } = require('@rebrandly/rebrandly-otel');

const app = express();

// Setup middleware
app.use(express.json());

// Setup OTEL - handles all telemetry automatically
setupExpress(otel, app);

// Your routes
app.get('/api/users', async (req, res) => {
    const users = await database.getUsers();
    res.json(users);
});

// Start server
const server = app.listen(3000, () => {
    console.log('Server running on port 3000');
});

// Graceful shutdown
process.on('SIGTERM', async () => {
    server.close(async () => {
        await forceFlush(5000);
        await shutdown();
        process.exit(0);
    });
});
```

## Core Components

### RebrandlyOTEL Class

The main entry point for all telemetry operations. Implements singleton pattern.

```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

// Access components
const tracer = otel.tracer;    // Distributed tracing
const meter = otel.meter;      // Metrics collection
const logger = otel.logger;    // Structured logging

// Core methods
otel.initialize();             // Explicit initialization
otel.forceFlush();            // Flush all pending data
otel.shutdown();              // Graceful shutdown
```

### Tracer

Manages distributed tracing with automatic context handling.

#### Creating Spans

**Async Function Wrapper (Recommended)**
```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

// Basic span
await otel.span('operation_name', async () => {
    // Your code
});

// With attributes
await otel.span('database_query', { 'db.table': 'users' }, async () => {
    const results = await queryDatabase();
});
```

**AWS Message Span**
```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

// Automatic context extraction from SQS/SNS messages
await otel.awsMessageSpan('process_message', record, {}, async () => {
    // Process message with propagated context
    await processMessage(record);
});
```

#### Manual Span Management

```javascript
const { tracer } = require('@rebrandly/rebrandly-otel');
const { SpanStatusCode } = require('@opentelemetry/api');

// Start span
const span = tracer.startSpan('manual_operation');

try {
    // Your code
    span.setAttribute('custom.attribute', 'value');
    span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
    span.recordException(error);
    span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
    throw error;
} finally {
    span.end();
}
```

### Meter

Handles metrics collection with predefined and custom metrics.

#### Predefined Metrics

```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// System metrics (automatically collected)
// - process.cpu.utilization
// - process.memory.used

// Access via GlobalMetrics
meter.GlobalMetrics.cpuUsagePercentage.set(45.2);
meter.GlobalMetrics.memoryUsageBytes.set(512 * 1024 * 1024);
```

#### Custom Metrics

**Counter**
```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Create counter
const requestCounter = meter.meter.createCounter('http_requests_total', {
    description: 'Total HTTP requests received',
    unit: '1'
});

// Increment counter
requestCounter.add(1, { method: 'GET', endpoint: '/api/users' });
```

**Histogram**
```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Create histogram
const responseTime = meter.meter.createHistogram('http_response_duration_ms', {
    description: 'HTTP response duration in milliseconds',
    unit: 'ms'
});

// Record value
responseTime.record(123.45, { endpoint: '/api/users', method: 'GET' });
```

**Observable Gauge**
```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Create observable gauge
meter.meter.createObservableGauge('queue_size', {
    description: 'Current message queue size',
    unit: '1'
}, (result) => {
    const size = messageQueue.size;
    result.observe(size, { queue: 'messages' });
});
```

### Logger

Structured logging with automatic trace correlation (Winston-based).

```javascript
const { logger } = require('@rebrandly/rebrandly-otel');

// Standard logging methods
logger.debug('Debug message', { detail: 'value' });
logger.info('Info message', { userId: '123' });
logger.warn('Warning message');
logger.error('Error message', { error: err });

// With structured metadata
logger.info('User action', {
    userId: '123',
    action: 'login',
    ipAddress: '192.168.1.1'
});

// Automatic trace correlation
await otel.span('operation', async () => {
    logger.info('This log is correlated with the span');
});
```

## Basic Usage

### Simple Operation Tracing

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

async function processOrder(orderId) {
    await otel.span('process_order', { orderId }, async () => {
        logger.info(`Processing order ${orderId}`);

        // Fetch order
        await otel.span('fetch_order', async () => {
            const order = await database.getOrder(orderId);
        });

        // Validate order
        await otel.span('validate_order', async () => {
            if (!validate(order)) {
                throw new Error('Invalid order');
            }
        });

        // Process payment
        await otel.span('process_payment', async () => {
            await paymentService.charge(order);
        });

        logger.info(`Order ${orderId} processed successfully`);
    });
}
```

### Error Handling

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');
const { SpanStatusCode } = require('@opentelemetry/api');

async function riskyOperation() {
    const span = otel.tracer.startSpan('risky_operation');

    try {
        const result = await performOperation();
        span.setStatus({ code: SpanStatusCode.OK });
        return result;
    } catch (error) {
        span.recordException(error);
        span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
        logger.error('Operation failed', { error: error.message });
        throw error;
    } finally {
        span.end();
    }
}
```

### Context Propagation

**Inject Context (Outbound)**
```javascript
const { getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');

// AWS SQS
const sqs = new SQSClient();
const command = new SendMessageCommand({
    QueueUrl: 'https://sqs.us-east-1.amazonaws.com/123456/my-queue',
    MessageBody: JSON.stringify({ data: 'value' }),
    MessageAttributes: getAwsMessageAttributes()  // Inject trace context
});

await sqs.send(command);

// HTTP requests (auto-instrumentation handles this)
const response = await fetch('https://api.example.com/users');
```

**Extract Context (Inbound)**
```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

// HTTP requests (Express middleware handles this)
// Manual extraction if needed
const ctx = otel.extractAwsContext(message);
```

## Advanced Usage

### Nested Spans with Attributes

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

async function complexWorkflow(userId) {
    await otel.span('workflow', { userId }, async () => {
        logger.info('Starting workflow');

        // Phase 1: Data Collection
        await otel.span('collect_data', { phase: 'collection' }, async () => {
            await otel.span('fetch_user_profile', async () => {
                const profile = await getProfile(userId);
            });

            await otel.span('fetch_user_orders', async () => {
                const orders = await getOrders(userId);
            });
        });

        // Phase 2: Processing
        await otel.span('process_data', { phase: 'processing' }, async () => {
            await otel.span('validate_data', async () => {
                await validate(profile, orders);
            });

            await otel.span('transform_data', async () => {
                const transformed = transform(profile, orders);
            });
        });

        // Phase 3: Output
        await otel.span('save_results', { phase: 'output' }, async () => {
            await save(transformed);
        });

        logger.info('Workflow completed');
    });
}
```

### Custom Span Events

```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

await otel.span('data_processing', async () => {
    const span = trace.getActiveSpan();

    span.addEvent('processing_started', {
        timestamp: Date.now(),
        inputSize: 1000
    });

    // Process data
    await processBatch();

    span.addEvent('checkpoint_reached', {
        processed: 500,
        remaining: 500
    });

    // Continue processing
    await processBatch();

    span.addEvent('processing_completed', {
        totalProcessed: 1000,
        durationMs: 1234
    });
});
```

### Multiple Operations in Parallel

```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

await otel.span('parallel_operations', async () => {
    // Execute multiple operations in parallel
    const results = await Promise.all([
        otel.span('operation_1', async () => await performOp1()),
        otel.span('operation_2', async () => await performOp2()),
        otel.span('operation_3', async () => await performOp3())
    ]);

    return results;
});
```

## AWS Lambda Integration

### Basic Lambda Handler

```javascript
const { lambdaHandler, logger } = require('@rebrandly/rebrandly-otel');

const handler = lambdaHandler({ name: 'my-function' })(async (event, context) => {
    logger.info('Lambda invoked', { requestId: context.awsRequestId });

    // Your business logic
    const result = await processEvent(event);

    return {
        statusCode: 200,
        body: JSON.stringify(result)
    };
});

module.exports = { handler };
```

### Lambda with Custom Configuration

```javascript
const { lambdaHandler, logger } = require('@rebrandly/rebrandly-otel');
const { SpanKind } = require('@opentelemetry/api');

const handler = lambdaHandler({
    name: 'advanced-function',
    attributes: { service: 'data-processor', version: '2.0' },
    kind: SpanKind.CONSUMER,
    autoFlush: true,
    captureSystemMetrics: true
})(async (event, context) => {
    logger.info('Advanced Lambda handler');
    return await processData(event);
});

module.exports = { handler };
```

### Streaming Handlers (`awslambda.streamifyResponse`)

`lambdaHandler()` accepts a response-streaming handler. Wrap the function returned by `awslambda.streamifyResponse()`; the wrapper keeps the runtime's streaming marker (and `highWaterMark`), so Lambda keeps streaming, and the handler is still called as `(event, responseStream, context)`:

```javascript
const { lambdaHandler } = require('rebrandly-otel');

exports.handler = lambdaHandler({ name: 'chat-stream' })(
    awslambda.streamifyResponse(async (event, responseStream, context) => {
        responseStream.setContentType('text/plain');
        responseStream.write('first chunk');
        responseStream.end();
    })
);
```

The span covers the whole invocation and ends when the handler's promise settles, so return (or await) only after the stream is finished. A streaming handler returns no `statusCode`, so a successful invocation gets status OK; a thrown error is recorded and rethrown as for any other handler. Requires rebrandly-otel 0.7.0 or later; earlier versions dropped the marker and passed the callback where the context belongs.

### SQS Message Processing

**Sender (with context propagation)**
```javascript
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');
const { lambdaHandler, logger, getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');

const sqs = new SQSClient({ region: 'us-east-1' });

const handler = lambdaHandler({ name: 'sqs-sender' })(async (event, context) => {
    logger.info('Sending SQS message');

    const command = new SendMessageCommand({
        QueueUrl: process.env.SQS_URL,
        MessageBody: JSON.stringify({
            orderId: '12345',
            action: 'process'
        }),
        MessageAttributes: getAwsMessageAttributes()  // Inject trace context
    });

    const result = await sqs.send(command);
    logger.info('SQS message sent', { messageId: result.MessageId });

    return {
        statusCode: 200,
        body: JSON.stringify({ messageId: result.MessageId })
    };
});

module.exports = { handler };
```

**Receiver (with automatic context extraction)**
```javascript
const { lambdaHandler, awsMessageHandler, logger } = require('@rebrandly/rebrandly-otel');

// Process each record with message handler
const processRecord = awsMessageHandler({ name: 'process-sqs-record' })(async (record) => {
    logger.info('Processing message', {
        messageId: record.messageId,
        body: JSON.parse(record.body)
    });

    // Your message processing logic
    const body = JSON.parse(record.body);
    await processOrder(body.orderId);

    return { processed: true };
});

// Main Lambda handler
const handler = lambdaHandler({ name: 'sqs-processor' })(async (event, context) => {
    logger.info('Processing SQS batch', { records: event.Records?.length });

    const results = [];
    for (const record of event.Records) {
        const result = await processRecord(record);
        results.push(result);
    }

    return { statusCode: 200, processed: results.length };
});

module.exports = { handler };
```

### SNS Message Processing

**Sender**
```javascript
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
const { lambdaHandler, logger, getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');

const sns = new SNSClient({ region: 'us-east-1' });

const handler = lambdaHandler({ name: 'sns-sender' })(async (event, context) => {
    logger.info('Publishing SNS message');

    const command = new PublishCommand({
        TopicArn: process.env.SNS_TOPIC_ARN,
        Message: JSON.stringify({
            event: 'order.created',
            orderId: '12345'
        }),
        MessageAttributes: getAwsMessageAttributes()
    });

    const result = await sns.send(command);
    logger.info('SNS message published', { messageId: result.MessageId });

    return { statusCode: 200 };
});

module.exports = { handler };
```

**Receiver with Event Filtering**
```javascript
const { lambdaHandler, awsMessageHandler, logger } = require('@rebrandly/rebrandly-otel');

const processRecord = awsMessageHandler({ name: 'process-sns-record' })(async (record) => {
    const snsMessage = JSON.parse(record.Sns.Message);
    const eventType = snsMessage.event;

    logger.info('Processing SNS message', { eventType, messageId: record.Sns.MessageId });

    // Process based on event type
    if (eventType === 'order.created') {
        await processOrderCreated(snsMessage.orderId);
    }

    return { processed: true, eventType };
});

const handler = lambdaHandler({ name: 'sns-processor' })(async (event, context) => {
    logger.info('Processing SNS batch', { records: event.Records?.length });

    for (const record of event.Records) {
        const message = JSON.parse(record.Sns.Message);

        // Filter by event type
        if (message.event === 'order.created') {
            await processRecord(record);
        }
    }

    return { statusCode: 200 };
});

module.exports = { handler };
```

### Batch Processing with Error Handling

```javascript
const { lambdaHandler, awsMessageHandler, logger } = require('@rebrandly/rebrandly-otel');

const processRecord = awsMessageHandler({ name: 'process-record' })(async (record) => {
    try {
        const body = JSON.parse(record.body);
        await processData(body);
        return { success: true, messageId: record.messageId };
    } catch (error) {
        logger.error('Failed to process record', {
            messageId: record.messageId,
            error: error.message
        });
        return { success: false, messageId: record.messageId, error: error.message };
    }
});

const handler = lambdaHandler({ name: 'batch-processor' })(async (event, context) => {
    const results = {
        total: event.Records.length,
        successful: 0,
        failed: 0,
        failures: []
    };

    for (const record of event.Records) {
        const result = await processRecord(record);

        if (result.success) {
            results.successful++;
        } else {
            results.failed++;
            results.failures.push(result);
        }
    }

    logger.info('Batch processing completed', results);

    // Return partial batch failure if needed
    if (results.failed > 0) {
        return {
            batchItemFailures: results.failures.map(f => ({ itemIdentifier: f.messageId }))
        };
    }

    return { statusCode: 200 };
});

module.exports = { handler };
```

## Express Integration

### Complete Example

```javascript
const express = require('express');
const { otel, logger, setupExpress, forceFlush, shutdown } = require('@rebrandly/rebrandly-otel');

const app = express();

// Middleware stack
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Setup OTEL integration - handles ALL telemetry automatically
setupExpress(otel, app);

// Health check
app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        timestamp: Date.now(),
        version: '1.0.0'
    });
});

// List users
app.get('/api/users', async (req, res) => {
    const { page = 1, limit = 10 } = req.query;

    await otel.span('fetch_users', { page, limit }, async () => {
        logger.info('Fetching users', { page, limit });

        const users = await database.getUsers(page, limit);

        res.json({
            users,
            pagination: { page, limit, total: 100 }
        });
    });
});

// Create user
app.post('/api/users', async (req, res) => {
    const { email, name } = req.body;

    await otel.span('create_user', { email }, async () => {
        // Validate
        if (!email || !name) {
            return res.status(400).json({ error: 'Email and name are required' });
        }

        // Check if exists
        await otel.span('check_user_exists', async () => {
            const exists = await database.userExists(email);
            if (exists) {
                logger.warn('User already exists', { email });
                return res.status(409).json({ error: 'User already exists' });
            }
        });

        // Create user
        const user = await otel.span('save_user', async () => {
            return await database.createUser({ email, name });
        });

        logger.info('User created', { userId: user.id });

        res.status(201).json(user);
    });
});

// Get user by ID
app.get('/api/users/:userId', async (req, res) => {
    const { userId } = req.params;

    await otel.span('get_user', { userId }, async () => {
        logger.info('Fetching user', { userId });

        const user = await database.getUser(userId);

        if (!user) {
            logger.warn('User not found', { userId });
            return res.status(404).json({ error: 'User not found' });
        }

        res.json(user);
    });
});

// Create order (complex operation)
app.post('/api/orders', async (req, res) => {
    const { userId, items } = req.body;

    await otel.span('create_order', { userId, itemsCount: items.length }, async () => {
        // Verify user
        await otel.span('verify_user', async () => {
            const user = await database.getUser(userId);
            if (!user) {
                return res.status(404).json({ error: 'User not found' });
            }
        });

        // Check inventory
        const available = await otel.span('check_inventory', async () => {
            return await inventory.checkAvailability(items);
        });

        if (!available) {
            logger.warn('Insufficient inventory', { userId, items });
            return res.status(409).json({ error: 'Insufficient inventory' });
        }

        // Process payment
        const payment = await otel.span('process_payment', async () => {
            return await paymentService.process(userId, items);
        });

        // Create order
        const order = await otel.span('save_order', async () => {
            return await database.createOrder({ userId, items, paymentId: payment.id });
        });

        logger.info('Order created', { orderId: order.id, userId });

        res.status(201).json(order);
    });
});

// Error simulation endpoint
app.get('/api/error/:type', (req, res, next) => {
    const { type } = req.params;

    switch (type) {
        case 'throw':
            throw new Error('Simulated thrown error');

        case 'async':
            setTimeout(() => {
                next(new Error('Simulated async error'));
            }, 10);
            break;

        case 'validation':
            return res.status(400).json({ error: 'Validation error' });

        default:
            res.status(400).json({ error: 'Unknown error type' });
    }
});

// 404 handler
app.use((req, res) => {
    res.status(404).json({
        error: 'Not Found',
        message: `Cannot ${req.method} ${req.path}`
    });
});

// Start server
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log('All telemetry handled automatically by OTEL integration');
});

// Graceful shutdown
const gracefulShutdown = async (signal) => {
    console.log(`\\n${signal} received, shutting down gracefully...`);

    server.close(async () => {
        console.log('Server closed');
        await forceFlush(5000);
        await shutdown();
        process.exit(0);
    });

    setTimeout(() => {
        console.error('Forced shutdown');
        process.exit(1);
    }, 10000);
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
```

### Express with Manual Spans

```javascript
const express = require('express');
const { otel, logger, setupExpress } = require('@rebrandly/rebrandly-otel');

const app = express();

app.use(express.json());
setupExpress(otel, app);

app.get('/api/complex', async (req, res) => {
    // Create custom span for this operation
    await otel.span('complex_operation', async () => {
        // Nested operations
        const data1 = await otel.span('fetch_data_1', async () => {
            return await fetchFromSource1();
        });

        const data2 = await otel.span('fetch_data_2', async () => {
            return await fetchFromSource2();
        });

        // Combine data
        const result = await otel.span('combine_data', async () => {
            return combine(data1, data2);
        });

        res.json(result);
    });
});

app.listen(3000);
```

### Request Body Capture

The SDK automatically captures HTTP request bodies for Express, Fastify, and Lambda-API frameworks. This feature is **enabled by default** but can be disabled if needed.

#### How It Works

- **Enabled by default**: Captures request bodies automatically (opt-out model)
- **JSON only**: Only captures `application/json` content types
- **Sensitive data redaction**: Automatically redacts passwords, tokens, API keys, and other sensitive fields
- **No size limit**: Captures full request bodies by default
- **Secure**: Sensitive fields are redacted before storage

#### Sensitive Fields Redacted

The following field names are automatically redacted (case-insensitive):
- `password`, `passwd`, `pwd`
- `token`, `access_token`, `refresh_token`, `auth_token`
- `apikey`, `api_key`, `secret`, `client_secret`
- `authorization`
- `creditcard`, `credit_card`, `cardnumber`, `cvv`, `cvc`
- `ssn`, `social_security`

#### Configuration

```javascript
// Disable body capture (set environment variable)
process.env.OTEL_CAPTURE_REQUEST_BODY = 'false';

// Or in your .env file
OTEL_CAPTURE_REQUEST_BODY=false
```

#### Example

```javascript
// Request body capture happens automatically
app.post('/api/login', async (req, res) => {
    const { username, password } = req.body;

    // The captured body in telemetry will show:
    // { "username": "john", "password": "[REDACTED]" }

    const user = await authenticate(username, password);
    res.json({ token: user.token });
});
```

#### Important Notes

- Body capture only works with `application/json` content types
- Binary content (`multipart/form-data`, `application/octet-stream`) is never captured
- Sensitive fields are redacted in nested objects and arrays
- The original request body is not modified, only the captured telemetry data

### Query-String Credential Redaction

Server spans from the Express, Fastify and Lambda-API middlewares and from `lambdaHandler()` on API Gateway events never carry credentials passed in the URL. In `url.full`, `url.query`, `http.target` and `http.url`, the value of any sensitive query parameter becomes `[REDACTED]`; every other parameter, the path and the attribute shape are unchanged:

```
GET /v1/links?apikey=sk_live_123&q=test
url.full  = https://api.example.com/v1/links?apikey=[REDACTED]&q=test
url.query = {"apikey":"[REDACTED]","q":"test"}
```

- **Sensitive names** (fully percent-decoded, up to 10 levels, so double-encoded names such as `c%256Fde` match too). A name is split on every character other than letters, digits, `_`, `.` and `-` (`filter[api_key]`, `debug;key`, `"sid"`), and is sensitive if any segment:
  - contains an entry of the body-redaction list above (`token`, `apikey`, `password`, `secret`, ...) or one of `passphrase`, `credential`, `cookie`, `hmac`, `bearer`;
  - equals `auth`, `code`, `session`, `sessionid`, `sid`, `pass` or `otp`;
  - ends in `key`, `sig`, `signature`, `jwt`, `pass` or `otp` after the start, `.`, `_` or `-` (`private_key`, `filter.key`, `x-hub-signature`, `X-Goog-Signature`, `db_pass`, `user_otp`), or in camelCase (`privateKey`, `accessKey`, `oauthSignature`, `userPass`). Not `monkey`, `turnkey`, `keyword`, `signaturePad`, `compass` or `footprint`
- Case is ignored except for the camelCase suffix
- A sensitive name keeps its name and its value becomes `[REDACTED]`. Repeated params and percent-encoded names (`api%5Fkey`) are covered
- **Every other value is checked as a whole**: it is fully percent-decoded (up to 10 levels, each valid `%XX` run on its own, so a stray `%` or invalid UTF-8 does not stop it) and the **whole value** becomes `[REDACTED]` if it contains, anywhere, a sensitive name followed by `=` or `:` (optionally after quotes, backslashes, closing `)` `]` `}` or whitespace), whatever punctuation precedes it (`/cb?token=x`, `(sid=1)`, `{"token":"x"}`, escaped `{\"token\":\"x\"}`, `(token)=x`, `token:x`), or `bearer` followed by whitespace and a token. Otherwise it is exported byte for byte, in both attributes:

  | Request query | `url.full` query | `url.query` |
  |---|---|---|
  | `next=%2Fdone%3Ftoken%3Dabc&state=s` | `next=[REDACTED]&state=s` | `{"next":"[REDACTED]","state":"s"}` |
  | `next=%2Fdone%3Fq%3Da%2Bb%26page%3D2` | unchanged | `{"next":"/done?q=a+b&page=2"}` |
  | `next=%2Fsearch%3Fq%3D50%%26token%3Dabc` (stray `%`) | `next=[REDACTED]` | `{"next":"[REDACTED]"}` |
  | `q=a;apikey=X` | `q=a;apikey=[REDACTED]` | `{"q":"[REDACTED]"}` (parsers keep `a;apikey=X` as the value) |
  | `token%3Dabc&q=1` (encoded `=` in the name) | `[REDACTED]&q=1` | `{"[REDACTED]":"[REDACTED]","q":"1"}` |
  | `f=%7B%22token%22%3A%22abc%22%7D` (JSON) | `f=[REDACTED]` | `{"f":"[REDACTED]"}` |
  | `q=Bearer+abc` | `q=[REDACTED]` | `{"q":"[REDACTED]"}` |

  - Only a run of `=` at the very end of the value is base64 padding, not an assignment: `v=8/xtHcmXDRmKha8fgBSeAhMAAePHTgrqr7Hn2YeCvcM=` is unchanged. Anywhere else, a sensitive `name=` counts even when what follows starts with a separator (`next=/cb?token=/abc` → `next=[REDACTED]`)
  - A value still decoding after 10 levels, or longer than 4096 characters (checked before any decoding), becomes `[REDACTED]`
  - A literal `[REDACTED]` sent by a client gets no special treatment: `next=/x?token=[REDACTED]abc` is replaced like any other
  - **Over-redaction**: the substring rule also matches short entries such as `ssn`, `pwd`, `cvc` inside unrelated words (`q=a,cvc9=1` → `[REDACTED]`), and `code`/`session` in ordinary JSON (`q={"code":200}` → `[REDACTED]`). This errs toward masking
- **Not inspected**: a credential that is not attached to a sensitive name with `=` or `:` (a bare token in free text), and `user:pass@` inside a value (only the request URL's own userinfo is masked)
- **Body and URL rules differ**: request-body redaction (above) still uses only the `SENSITIVE_FIELD_NAMES` substring rule; the exact names, suffixes and extra substrings here apply to URLs only. Aligning them is a follow-up
- The fragment (`#...`) is dropped from `url.full`; `url.path` stops at `?` or `#`
- `user:pass@` in an absolute URL becomes `[REDACTED]@`, up to the last `@` (a password may contain `@`)
- A URL that cannot be processed loses its query rather than leaking it
- Request headers: only the allow-listed `IMPORTANT_HEADERS` are captured; `authorization`, `cookie`, `x-api-key` and `apikey` are never captured
- Helpers: `redactUrl(url)` and `redactQuery(objectOrString)` in `rebrandly-otel/httpMiddlewareUtils`

## Database Instrumentation

### Knex Auto-Instrumentation

The SDK automatically instruments Knex.js queries. No manual setup required.

```javascript
const knex = require('knex')({
    client: 'pg',
    connection: {
        host: 'localhost',
        user: 'myuser',
        password: 'mypassword',
        database: 'mydb'
    }
});

// All queries automatically traced
const users = await knex('users').where('status', 'active').select('*');

// JOIN queries
const orders = await knex('orders')
    .join('users', 'orders.user_id', 'users.id')
    .where('orders.status', 'pending')
    .select('orders.*', 'users.email');

// Transactions
await knex.transaction(async (trx) => {
    await trx('users').insert({ email: 'user@example.com', name: 'John' });
    await trx('profiles').insert({ user_id: 1, bio: 'Developer' });
});
```

**Captured Attributes:**
- `db.system`: Database client (pg, mysql, etc.)
- `db.operation.name`: Query type (SELECT, INSERT, UPDATE, DELETE)
- `db.statement`: SQL query (truncated to 2000 chars)
- `db.duration_ms`: Query execution time
- `db.slow_query`: Flag for queries exceeding threshold
- `db.bindings`: Query parameters (if enabled)

### Library Auto-Instrumentation

Registered automatically when the SDK loads (require `rebrandly-otel` **before** the client libraries, and keep them external when bundling):

| Library | Instrumentation |
|---|---|
| AWS SDK v3 (`@aws-sdk/client-*`) | `@opentelemetry/instrumentation-aws-sdk` — hooks `@smithy/core`, so current clients (3.1100+) are traced |
| `redis` / `@redis/client` | `@opentelemetry/instrumentation-redis` |
| `ioredis` | `@opentelemetry/instrumentation-ioredis` (0.7.0+) |
| `mysql`, `mysql2` | `@opentelemetry/instrumentation-mysql`, `-mysql2` |
| gRPC | `@opentelemetry/instrumentation-grpc` |

`ioredis` commands are traced only inside an active span (the Lambda handler span, an HTTP middleware span, or one of your own). That is the upstream default and avoids one root span per Redis command.

### Redis Statements (`db.query.text` / `db.statement`)

Redis spans carry the **command name only** by default (0.7.1+): `SET k v` → `SET`, `EVAL <script> 1 k <argv>` → `EVAL`. Upstream's serializer writes EVAL/EVALSHA script bodies and ARGV, the arguments of GET/DEL/INCR..., and the first arguments of SET/HSET into `db.query.text`, so user content, lock tokens and values could have reached Coralogix. A Coralogix check (2026-10-20 to 2026-10-23) observed no such leakage; the change is preventive. The SDK never uses it.

Keys can be opted in; values never are:

```javascript
const { initialize } = require('rebrandly-otel');

initialize({ redis: { dbStatement: 'keys' } });
```

| Command | `'command'` (default) | `'keys'` |
|---|---|---|
| `EVAL <script> 2 k1 k2 <argv...>` | `EVAL` | `EVAL k1 k2` |
| `EVALSHA <sha1> 1 k1 <argv...>` | `EVALSHA` | `EVALSHA k1` |
| `SET k v` | `SET` | `SET k` |
| `HSET k f v` | `HSET` | `HSET k` |
| `GET k` | `GET` | `GET k` |
| `MGET a b` | `MGET` | `MGET a b` |

In `'keys'` mode, script bodies, SHA1s, function names, ARGV, values and hash fields are never emitted. A command whose key positions the SDK does not know (e.g. `AUTH`, `CONFIG`, `PUBLISH`, `RENAME`) emits its name only. Only use `'keys'` if your keys contain no personal data (emails, user-provided text). The case of the command name is the client's (`get` for ioredis, `GET` for node-redis).

For full control pass `initialize({ redis: { dbStatementSerializer: (cmdName, cmdArgs) => string } })`. It takes precedence over `dbStatement`; whatever it returns is exported, so never return values. If it throws or returns a non-string, the command name is used. Commands that run before `initialize()` use the default.

### Database Attribute Names (stable + legacy)

The redis, ioredis, mysql and mysql2 instrumentations emit the stable database semantic conventions. The SDK copies each one back onto the legacy key that earlier releases emitted, so existing queries, dashboards and alerts keep working. Database spans carry both:

| Stable key | Legacy key (still set) |
|---|---|
| `db.system.name` | `db.system` |
| `db.query.text` | `db.statement` |
| `db.namespace` | `db.name` |
| `server.address` | `net.peer.name` |
| `server.port` | `net.peer.port` |

A legacy key the instrumentation or your code already set is never overwritten. New queries should use the stable keys; the legacy copies will be removed in a future major release.

The mysql instrumentation's connection-pool metric is now `db.client.connection.count` (was `db.client.connections.usage`).

### Redis Custom Span Processor

The SDK includes a custom span processor that ensures the `db.name` attribute is always set for Redis spans.

**Features:**
- Automatic database name extraction from connection string
- Consistent naming across environments (local and ECS)
- Non-intrusive enhancement of built-in Redis instrumentation
- Extracts from `db.redis.database_index` or connection string

**Example:**
```javascript
const redis = require('redis');

// Connection string: redis://localhost:6379/2
const client = redis.createClient({
    url: 'redis://localhost:6379/2'
});

await client.connect();

// Automatically traced with db.name set to "redis-2"
await client.set('key', 'value');
await client.get('key');
```

### Manual Database Spans

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

async function queryDatabase(sql, params) {
    await otel.span('database_query', {
        'db.system': 'postgresql',
        'db.operation.name': 'SELECT',
        'db.statement': sql
    }, async () => {
        logger.info('Executing query', { sql });

        const result = await pool.query(sql, params);

        logger.info('Query completed', { rowCount: result.rowCount });

        return result;
    });
}
```

## Metrics

### System Metrics

```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Predefined metrics (automatically collected in Lambda)
// - process.cpu.utilization
// - process.memory.used

// Manual recording
meter.GlobalMetrics.cpuUsagePercentage.set(45.2);
meter.GlobalMetrics.memoryUsageBytes.set(512 * 1024 * 1024);
```

### Custom Counters

```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// HTTP requests
const httpRequests = meter.meter.createCounter('http_requests_total', {
    description: 'Total HTTP requests',
    unit: '1'
});

httpRequests.add(1, {
    method: 'GET',
    endpoint: '/api/users',
    status: '200'
});

// Processed messages
const messagesProcessed = meter.meter.createCounter('messages_processed_total', {
    description: 'Total messages processed',
    unit: '1'
});

messagesProcessed.add(1, {
    queue: 'orders',
    status: 'success'
});

// Error counter
const errors = meter.meter.createCounter('errors_total', {
    description: 'Total errors',
    unit: '1'
});

errors.add(1, {
    type: 'validation',
    endpoint: '/api/users'
});
```

### Custom Histograms

#### Bucket boundaries

A histogram created **without** bucket advice uses the SDK default boundaries, which are seconds-oriented:

```
0.001, 0.004, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5
```

Anything recorded in milliseconds, bytes or counts with those buckets lands almost entirely in the overflow bucket, so percentiles are meaningless. For any unit other than seconds, pass `advice.explicitBucketBoundaries`; it always wins over the default (0.7.0+; earlier versions ignored it):

```javascript
const turnDuration = meter.meter.createHistogram('ask_ai.turn_duration', {
    unit: 'ms',
    advice: { explicitBucketBoundaries: [100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000] }
});
```

This applies to every meter backed by the SDK, including `metrics.getMeter()` from `@opentelemetry/api`.

#### Examples

```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Response time
const responseTime = meter.meter.createHistogram('http_response_duration_ms', {
    description: 'HTTP response duration',
    unit: 'ms',
    advice: { explicitBucketBoundaries: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000] }
});

const start = Date.now();
await processRequest();
const duration = Date.now() - start;

responseTime.record(duration, {
    endpoint: '/api/users',
    method: 'GET'
});

// Database query time
const queryTime = meter.meter.createHistogram('db_query_duration_ms', {
    description: 'Database query duration',
    unit: 'ms',
    advice: { explicitBucketBoundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000] }
});

queryTime.record(45.3, {
    operation: 'SELECT',
    table: 'users'
});

// Payload size
const payloadSize = meter.meter.createHistogram('payload_size_bytes', {
    description: 'Request/response payload size',
    unit: 'bytes',
    advice: { explicitBucketBoundaries: [256, 1024, 4096, 16384, 65536, 262144, 1048576] }
});

payloadSize.record(1024, {
    endpoint: '/api/users',
    direction: 'response'
});
```

### Observable Gauges

```javascript
const { meter } = require('@rebrandly/rebrandly-otel');

// Queue size
const messageQueue = [];

meter.meter.createObservableGauge('queue_size', {
    description: 'Current message queue size',
    unit: '1'
}, (result) => {
    result.observe(messageQueue.length, { queue: 'messages' });
});

// Connection pool
const pool = createPool();

meter.meter.createObservableGauge('db_connections_active', {
    description: 'Active database connections',
    unit: '1'
}, (result) => {
    result.observe(pool.activeCount, { pool: 'main' });
});

// Memory usage
meter.meter.createObservableGauge('process_memory_usage_percent', {
    description: 'Process memory usage percentage',
    unit: '%'
}, (result) => {
    const used = process.memoryUsage();
    const percent = (used.heapUsed / used.heapTotal) * 100;
    result.observe(percent);
});
```

## Logging

### Basic Logging

```javascript
const { logger } = require('@rebrandly/rebrandly-otel');

// Standard levels
logger.debug('Debug message');
logger.info('Info message');
logger.warn('Warning message');
logger.error('Error message');

// With metadata
logger.info('Processing request', {
    userId: '12345',
    endpoint: '/api/users'
});

// With error
try {
    await riskyOperation();
} catch (error) {
    logger.error('Operation failed', { error: error.message, stack: error.stack });
}
```

### Structured Logging

```javascript
const { logger } = require('@rebrandly/rebrandly-otel');

// User action
logger.info('User logged in', {
    userId: '12345',
    ipAddress: '192.168.1.1',
    userAgent: 'Mozilla/5.0...',
    timestamp: Date.now()
});

// Business event
logger.info('Order placed', {
    orderId: 'ORD-12345',
    userId: 'USR-789',
    totalAmount: 149.99,
    itemsCount: 3,
    paymentMethod: 'credit_card',
    shippingAddress: 'redacted'
});

// Error context
logger.error('Payment processing failed', {
    orderId: 'ORD-12345',
    paymentGateway: 'stripe',
    errorCode: 'card_declined',
    amount: 149.99,
    attemptNumber: 2
});

// Performance metrics
logger.info('Query executed', {
    query: 'SELECT * FROM users',
    durationMs: 45.2,
    rowCount: 150,
    cached: false
});
```

### Trace Correlation

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

// Logs within spans automatically include trace_id and span_id
await otel.span('process_order', async () => {
    logger.info('Starting order processing');  // Correlated with span

    await processItems();

    logger.info('Order processing completed');  // Correlated with span
});
```

### Custom Log Levels

```javascript
const { logger } = require('@rebrandly/rebrandly-otel');

// Set log level via environment
process.env.LOG_LEVEL = 'debug';

// Or programmatically
logger.level = 'debug';

// Available levels: error, warn, info, http, verbose, debug, silly
```

## Context Propagation

### HTTP Context

```javascript
const { otel } = require('@rebrandly/rebrandly-otel');
const fetch = require('node-fetch');

// Auto-instrumentation handles HTTP context propagation
// No manual injection needed for most cases
await otel.span('call_external_api', async () => {
    const response = await fetch('https://api.example.com/users');
    const data = await response.json();
});

// Manual context injection (if needed)
const headers = {};
otel.injectContext(headers);  // If this method exists

const response = await fetch('https://api.example.com/users', { headers });
```

### AWS Message Context

**SQS**
```javascript
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');
const { lambdaHandler, logger, getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');

const sqs = new SQSClient();

const handler = lambdaHandler({ name: 'sqs-sender' })(async (event, context) => {
    // Send with context
    await otel.span('send_sqs_message', async () => {
        const command = new SendMessageCommand({
            QueueUrl: process.env.QUEUE_URL,
            MessageBody: JSON.stringify({ data: 'value' }),
            MessageAttributes: getAwsMessageAttributes()  // Inject trace context
        });

        const result = await sqs.send(command);
        logger.info('Message sent', { messageId: result.MessageId });
    });

    return { statusCode: 200 };
});

module.exports = { handler };
```

**SNS**
```javascript
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
const { lambdaHandler, logger, getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');

const sns = new SNSClient();

const handler = lambdaHandler({ name: 'sns-publisher' })(async (event, context) => {
    // Publish with context
    await otel.span('publish_sns_message', async () => {
        const command = new PublishCommand({
            TopicArn: process.env.TOPIC_ARN,
            Message: JSON.stringify({ event: 'order.created', orderId: '123' }),
            MessageAttributes: getAwsMessageAttributes()
        });

        const result = await sns.send(command);
        logger.info('Message published', { messageId: result.MessageId });
    });

    return { statusCode: 200 };
});

module.exports = { handler };
```

### Receive with Context Extraction

```javascript
const { lambdaHandler, awsMessageHandler, logger } = require('@rebrandly/rebrandly-otel');

// Context automatically extracted from MessageAttributes
const processRecord = awsMessageHandler({ name: 'process-message' })(async (record) => {
    // Context automatically propagated
    logger.info('Processing message', { messageId: record.messageId });

    const body = JSON.parse(record.body);
    await processData(body);

    return { processed: true };
});

const handler = lambdaHandler({ name: 'message-processor' })(async (event, context) => {
    for (const record of event.Records) {
        await processRecord(record);
    }

    return { statusCode: 200 };
});

module.exports = { handler };
```

## Best Practices

### 1. Naming Conventions

```javascript
// Use descriptive, hierarchical span names
await otel.span('database.query.users', async () => { ... });
await otel.span('http.client.get.api.users', async () => { ... });
await otel.span('service.user.create', async () => { ... });

// Use snake_case for metric names
meter.meter.createCounter('http_requests_total');
meter.meter.createHistogram('db_query_duration_ms');

// Use semantic conventions
// https://opentelemetry.io/docs/specs/semconv/
```

### 2. Attribute Management

```javascript
const { otel } = require('@rebrandly/rebrandly-otel');

// Use semantic conventions
await otel.span('http_request', {
    'http.method': 'GET',
    'http.url': 'https://api.example.com',
    'http.response.status_code': 200
}, async () => { ... });

// Keep cardinality low
// Good: Limited values
await otel.span('operation', { 'user.tier': 'premium' }, async () => { ... });

// Bad: High cardinality
await otel.span('operation', { 'user.id': '12345' }, async () => { ... });

// Use structured attributes
await otel.span('order_processing', {
    'order.id': orderId,
    'order.total': totalAmount,
    'order.items_count': items.length
}, async () => { ... });
```

### 3. Error Handling

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');
const { SpanStatusCode } = require('@opentelemetry/api');

async function safeOperation() {
    const span = otel.tracer.startSpan('operation');

    try {
        const result = await performOperation();
        span.setStatus({ code: SpanStatusCode.OK });
        return result;
    } catch (error) {
        // Record exception
        span.recordException(error);
        span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
        logger.error('Operation failed', { error: error.message });
        throw error;
    } finally {
        span.end();
    }
}
```

### 4. Resource Management

```javascript
const { otel, logger } = require('@rebrandly/rebrandly-otel');

async function main() {
    try {
        // Your application code
        await otel.span('main', async () => {
            await runApplication();
        });
    } finally {
        // Always flush before exit
        logger.info('Shutting down');
        await otel.forceFlush(5000);
        await otel.shutdown();
    }
}

main().catch((error) => {
    console.error('Application error:', error);
    process.exit(1);
});
```

### 5. Lambda Best Practices

```javascript
const { lambdaHandler, logger } = require('@rebrandly/rebrandly-otel');

const handler = lambdaHandler({
    name: 'my-function',
    autoFlush: true  // Always enable for Lambda
})(async (event, context) => {
    // Validate input early
    if (!isValidEvent(event)) {
        logger.warn('Invalid event received');
        return { statusCode: 400, body: 'Invalid input' };
    }

    // Use nested spans for clarity
    await otel.span('business_logic', async () => {
        await processEvent(event);
    });

    logger.info('Lambda completed successfully');
    return { statusCode: 200 };
});

module.exports = { handler };
```

### 6. Express Best Practices

```javascript
const express = require('express');
const { otel, logger, setupExpress } = require('@rebrandly/rebrandly-otel');

const app = express();

app.use(express.json());

// Setup OTEL first, before routes
setupExpress(otel, app);

// Use custom spans for complex operations only
app.post('/api/complex', async (req, res) => {
    // Let middleware handle basic tracing
    // Add custom spans for specific operations

    await otel.span('validate_input', async () => {
        validateInput(req.body);
    });

    const result = await otel.span('process_data', async () => {
        return await processData(req.body);
    });

    res.json(result);
});

// Implement graceful shutdown
const server = app.listen(3000);

process.on('SIGTERM', async () => {
    server.close(async () => {
        await otel.forceFlush(5000);
        await otel.shutdown();
        process.exit(0);
    });
});
```

## Troubleshooting

### No Data Exported

**Problem**: Telemetry data not appearing in backend

**Solutions**:
```javascript
// 1. Enable debug mode
process.env.OTEL_DEBUG = 'true';

// 2. Verify endpoint
console.log('OTLP Endpoint:', process.env.OTEL_EXPORTER_OTLP_ENDPOINT);

// 3. Test connectivity
const https = require('https');
const url = new URL(process.env.OTEL_EXPORTER_OTLP_ENDPOINT);

https.get(url, (res) => {
    console.log('Connectivity test:', res.statusCode);
}).on('error', (error) => {
    console.error('Cannot connect:', error.message);
});

// 4. Force flush manually
const { otel } = require('@rebrandly/rebrandly-otel');
await otel.forceFlush(10000);
```

### Lambda Missing Data

**Problem**: Lambda spans incomplete or missing

**Solutions**:
```javascript
// 1. Ensure auto-flush is enabled
const handler = lambdaHandler({ name: 'my-function', autoFlush: true })(async (event, context) => {
    // Your code
});

// 2. Increase flush timeout
const handler = lambdaHandler({ name: 'my-function' })(async (event, context) => {
    // Your code
    await otel.forceFlush(5000);  // Longer timeout
});

// 3. Check Lambda timeout setting
// Ensure Lambda has enough time to flush (add 2-3 seconds buffer)
```

### Context Not Propagated

**Problem**: Distributed traces disconnected

**Solutions**:
```javascript
// 1. Verify context injection
const { getAwsMessageAttributes } = require('@rebrandly/rebrandly-otel');
const attrs = getAwsMessageAttributes();
console.log('Context attributes:', attrs);  // Should contain traceparent

// 2. Use correct message handler
const { awsMessageHandler } = require('@rebrandly/rebrandly-otel');

// Correct - automatic context extraction
const processRecord = awsMessageHandler({ name: 'process' })(async (record) => {
    // Context automatically extracted
});

// 3. Verify message attributes are present
const handler = lambdaHandler({ name: 'receiver' })(async (event, context) => {
    for (const record of event.Records) {
        console.log('Message attributes:', record.messageAttributes || record.MessageAttributes);
    }
});
```

### High Memory Usage

**Problem**: Memory consumption increasing

**Solutions**:
```javascript
// 1. Check span cleanup
// Always use async functions or properly end spans
await otel.span('operation', async () => {
    // Span automatically closed
});

// 2. Reduce batch size
process.env.BATCH_EXPORT_TIME_MILLIS = '500';  // More frequent exports

// 3. Monitor memory
setInterval(() => {
    const used = process.memoryUsage();
    console.log('Memory:', Math.round(used.heapUsed / 1024 / 1024 * 100) / 100, 'MB');
}, 10000);
```

### Auto-Instrumentation Issues

**Problem**: Double spans or missing spans

**Note**: HTTP and Express auto-instrumentation are disabled by default in this SDK to prevent double-span creation. The Express middleware provides manual, aligned instrumentation instead.

```javascript
// Correct usage with setupExpress
const { otel, setupExpress } = require('@rebrandly/rebrandly-otel');
setupExpress(otel, app);  // Provides aligned instrumentation

// No need to use auto-instrumentation for Express
```

## Reference

### Environment Variables

| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `OTEL_SERVICE_NAME` | string | `default-service-nodejs` | Service identifier |
| `OTEL_SERVICE_VERSION` | string | `1.0.0` | Service version |
| `OTEL_REPO_NAME` | string | None | Repository name (added to `repository.name` resource attribute) |
| `OTEL_COMMIT_ID` | string | None | Git commit ID (overrides `OTEL_SERVICE_VERSION` when set) |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | URL | None | OTLP collector endpoint |
| `OTEL_EXPORTER_OTLP_HEADERS` | string | None | OTLP headers (comma-separated key=value) |
| `OTEL_DEBUG` | boolean | `false` | Enable console debugging |
| `OTEL_CAPTURE_REQUEST_BODY` | boolean | `true` | Capture HTTP request bodies (JSON only) |
| `BATCH_EXPORT_TIME_MILLIS` | int | `100` | Batch export interval (ms) |
| `ENV` | string | `local` | Deployment environment |
| `ENVIRONMENT` | string | `local` | Deployment environment (alias) |
| `NODE_ENV` | string | `local` | Deployment environment (alias) |
| `LOG_LEVEL` | string | `info` | Winston log level |

### Span Kinds

```javascript
const { SpanKind } = require('@opentelemetry/api');

SpanKind.INTERNAL   // Internal operation
SpanKind.SERVER     // Server request handler
SpanKind.CLIENT     // Client request
SpanKind.PRODUCER   // Message producer
SpanKind.CONSUMER   // Message consumer
```

### Status Codes

```javascript
const { SpanStatusCode } = require('@opentelemetry/api');

SpanStatusCode.OK      // Success
SpanStatusCode.ERROR   // Error
SpanStatusCode.UNSET   // Default/unset
```

### Lambda Handler Options

```javascript
const options = {
    name: 'function-name',           // Span name
    attributes: { key: 'value' },    // Custom attributes
    kind: SpanKind.SERVER,           // Span kind
    autoFlush: true,                 // Auto-flush telemetry
    flushMinIntervalMs: 0,           // Min ms between auto-flushes (0 = every
                                     // invocation; falls back to the
                                     // OTEL_FLUSH_MIN_INTERVAL_MS env var)
    captureSystemMetrics: true       // Capture CPU/memory
};

const handler = lambdaHandler(options)(async (event, context) => { ... });
```

### Message Handler Options

```javascript
const options = {
    name: 'handler-name',            // Span name
    attributes: { key: 'value' },    // Custom attributes
    kind: SpanKind.CONSUMER,         // Span kind
    autoFlush: true,                 // Auto-flush telemetry
    flushMinIntervalMs: 0            // Same semantics as lambdaHandler
};

const handler = awsMessageHandler(options)(async (record) => { ... });
```

## Additional Resources

- [OpenTelemetry Node.js Documentation](https://opentelemetry.io/docs/instrumentation/js/)
- [Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/)
- [OTLP Specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md)
- [AWS SDK Instrumentation](https://www.npmjs.com/package/@opentelemetry/instrumentation-aws-sdk)
- [Example Code](examples/)
