npm package: @flash-analytics/redis
Description: A robust Redis client package optimized for Cloud Run environments with comprehensive connection management, health monitoring, and graceful shutdown handling.
Latest version: 0.1.0
Deprecated: Internal package. Deprecated from public npm distribution; do not use.

# Redis Package

A robust Redis client package optimized for Cloud Run environments with comprehensive connection management, health monitoring, and graceful shutdown handling.

## Features

- 🚀 **Cloud Run Optimized**: Configured for serverless environments with VPC connectors
- 🔍 **Connection Health Monitoring**: Real-time status tracking for all Redis clients
- 🔄 **Graceful Shutdown**: Proper connection cleanup on application termination
- 📊 **Comprehensive Logging**: Detailed connection event tracking and error reporting
- 🛡️ **Type Safety**: Enhanced TypeScript support with proper error handling
- ⚡ **Performance**: Singleton pattern with lazy connection initialization

## Installation

```bash
npm install @flash-analytics/redis
```

## Usage

### Basic Usage

```typescript
import { getRedisCache } from '@flash-analytics/redis';

const redis = getRedisCache();
await redis.set('key', 'value');
const value = await redis.get('key');
```

### JSON Operations

```typescript
import { getRedisCache } from '@flash-analytics/redis';

const redis = getRedisCache();

// Store JSON data
await redis.setJson('user:123', 3600, { name: 'John', age: 30 });

// Retrieve JSON data with type safety
const user = await redis.getJson<{ name: string; age: number }>('user:123');
if (user) {
  console.log(user.name); // Type-safe access
}
```

### Connection Health Monitoring

```typescript
import { getRedisConnectionStatus, getRedisMetrics } from '@flash-analytics/redis';

// Check connection status for all clients
const status = getRedisConnectionStatus();
console.log(status);
// {
//   cache: true,
//   sub: true,
//   pub: true,
//   queue: true,
//   groupQueue: true
// }

// Get detailed metrics
const metrics = getRedisMetrics();
console.log(metrics);
// {
//   status: { cache: true, sub: true, pub: true, queue: true, groupQueue: true },
//   totalConnected: 5,
//   totalClients: 5,
//   connectionRate: 1,
//   timestamp: '2024-01-20T10:30:00.000Z'
// }
```

### Graceful Shutdown

```typescript
import { closeRedisConnections } from '@flash-analytics/redis';

// In your application shutdown handler
process.on('SIGTERM', async () => {
  await closeRedisConnections();
  process.exit(0);
});
```

## Available Clients

The package provides five specialized Redis clients:

### Cache Client (`getRedisCache()`)
General-purpose caching with JSON support.

```typescript
import { getRedisCache } from '@flash-analytics/redis';

const cache = getRedisCache();
await cache.set('key', 'value', 'EX', 3600);
```

### Pub/Sub Clients (`getRedisSub()`, `getRedisPub()`)
Dedicated clients for publish/subscribe operations.

```typescript
import { getRedisSub, getRedisPub } from '@flash-analytics/redis';

const subscriber = getRedisSub();
const publisher = getRedisPub();

await subscriber.subscribe('channel');
subscriber.on('message', (channel, message) => {
  console.log(`Received: ${message} from ${channel}`);
});

await publisher.publish('channel', 'Hello World!');
```

### Queue Clients (`getRedisQueue()`, `getRedisGroupQueue()`)
Optimized for BullMQ job queues with special configuration.

```typescript
import { getRedisQueue, getRedisGroupQueue } from '@flash-analytics/redis';

const queue = getRedisQueue();
const groupQueue = getRedisGroupQueue();

// Use with BullMQ
import { Queue } from 'bullmq';
const myQueue = new Queue('my-queue', { connection: queue });
```

## Configuration

### Environment Variables

- `REDIS_URL`: Redis connection URL (default: `redis://localhost:6379`)

### Connection Options

All clients are configured with Cloud Run optimizations:

```typescript
const baseOptions = {
  connectTimeout: 10000,
  keepAlive: 30000,           // Keep TCP connection alive
  lazyConnect: true,           // Don't connect until first command
  retryStrategy: (times) => {
    const delay = Math.min(times * 50, 2000);
    logger.debug('Redis connection retry attempt', { attempt: times, delayMs: delay });
    return delay;
  },
};
```

Queue clients have additional BullMQ-specific settings:

```typescript
{
  enableReadyCheck: false,
  maxRetriesPerRequest: null,
  enableOfflineQueue: true,
}
```

## Error Handling

The package includes comprehensive error handling:

### JSON Operations

```typescript
const data = await redis.getJson<User>('user:123');
// Returns null if key doesn't exist or JSON parsing fails
// Logs errors for debugging
```

### Connection Errors

Connection errors are logged with detailed context:

```
Redis connection error: {
  name: "cache",
  event: "error",
  error: "Connection refused",
  code: "ECONNREFUSED",
  command: "get",
  args: ["user:123"]
}
```

## Monitoring and Debugging

### Connection Events

All connection events are logged for visibility:

- `connect`: Connection initiated
- `ready`: Connection established
- `reconnecting`: Attempting reconnection
- `close`: Connection closed
- `end`: Connection ended
- `error`: Connection error

### Health Checks

Use the built-in health monitoring for application health checks:

```typescript
import { getRedisConnectionStatus } from '@flash-analytics/redis';

app.get('/health', (req, res) => {
  const status = getRedisConnectionStatus();
  const allConnected = Object.values(status).every(Boolean);
  
  res.status(allConnected ? 200 : 503).json({
    status: allConnected ? 'healthy' : 'unhealthy',
    redis: status
  });
});
```

## Development

### Running Tests

```bash
npm test
```

### Linting

```bash
npm run lint
```

### Type Checking

```bash
npm run typecheck
```

## Production Deployment

### Cloud Run Best Practices

1. **Environment Variables**: Set `REDIS_URL` in your Cloud Run service configuration
2. **Memory Limits**: Ensure sufficient memory for Redis connections
3. **Concurrency**: Configure appropriate concurrency settings
4. **Health Checks**: Use the built-in health monitoring functions

### Graceful Shutdown

Always implement graceful shutdown in your application:

```typescript
import { closeRedisConnections } from '@flash-analytics/redis';

async function shutdown(signal: string) {
  console.log(`Received ${signal}, shutting down gracefully...`);
  
  try {
    await closeRedisConnections();
    console.log('Redis connections closed');
    process.exit(0);
  } catch (error) {
    console.error('Error during shutdown:', error);
    process.exit(1);
  }
}

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

## Troubleshooting

### Connection Issues

1. **Check Redis URL**: Ensure `REDIS_URL` is correctly set
2. **Network Connectivity**: Verify VPC connector configuration for Cloud Run
3. **Firewall Rules**: Ensure Redis instance allows connections from Cloud Run
4. **Connection Limits**: Check Redis instance connection limits

### Debugging

Enable debug logging to see connection events:

```bash
DEBUG=redis:* npm start
```

### Common Issues

| Issue | Solution |
|-------|----------|
| "Connection is closed" | Check VPC connector and Redis instance configuration |
| "ECONNREFUSED" | Verify Redis URL and instance availability |
| "ETIMEDOUT" | Increase connect timeout or check network connectivity |
| High reconnection rate | Review retry strategy and connection pool settings |

## License

MIT