> ## Documentation Index
> Fetch the complete documentation index at: https://o1.network/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Websocket

# WebSocket API Reference

Real-time communication and monitoring through WebSocket connections. The WebSocket API provides live updates for deployments, metrics, and logs.

## Endpoints Overview

| Method | Endpoint                 | Description                    |
| ------ | ------------------------ | ------------------------------ |
| GET    | `/api/websocket/stats`   | Get WebSocket statistics       |
| GET    | `/api/websocket/metrics` | Get performance metrics        |
| GET    | `/api/websocket/health`  | Check WebSocket service health |

## WebSocket Connection

### Establishing Connection

Connect to the WebSocket endpoint:

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
// JavaScript example
const ws = new WebSocket('ws://localhost:3000/api/websocket');

ws.onopen = () => {
  console.log('WebSocket connection established');
  // Subscribe to deployment updates
  ws.send(
    JSON.stringify({
      type: 'subscribe',
      deploymentId: 'deploy-20240115-103000',
    })
  );
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};

ws.onclose = () => {
  console.log('WebSocket connection closed');
};
```

## Message Types

### Deployment Messages

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "deployment",
  "deploymentId": "deploy-20240115-103000",
  "status": "running",
  "message": "Installing dependencies...",
  "timestamp": "2024-01-15T10:30:00Z",
  "progress": 45
}
```

### Log Messages

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "log",
  "host": "test-anvil-01",
  "application": "Anvil",
  "level": "INFO",
  "message": "Application started successfully",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Metrics Messages

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "metrics",
  "host": "test-anvil-01",
  "application": "Anvil",
  "cpu": 45.2,
  "memory": 50.0,
  "disk": 25.5,
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Status Messages

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "status",
  "status": "completed",
  "message": "Deployment completed successfully",
  "timestamp": "2024-01-15T10:35:00Z"
}
```

## Subscription Management

### Subscribe to Deployment

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
ws.send(
  JSON.stringify({
    type: 'subscribe',
    deploymentId: 'deploy-20240115-103000',
  })
);
```

### Subscribe to Logs

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
ws.send(
  JSON.stringify({
    type: 'subscribe-logs',
    host: 'test-anvil-01',
    application: 'Anvil',
    search: 'error',
  })
);
```

### Subscribe to Metrics

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
ws.send(
  JSON.stringify({
    type: 'subscribe-metrics',
    host: 'test-anvil-01',
    application: 'Anvil',
    metrics: ['cpu', 'memory', 'disk'],
  })
);
```

### Unsubscribe

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
ws.send(
  JSON.stringify({
    type: 'unsubscribe',
    subscriptionId: 'sub-123456',
  })
);
```

## API Endpoints

### Get WebSocket Statistics

```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET /api/websocket/stats
```

**Response:**

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "totalConnections": 15,
  "poolStats": {
    "active": 10,
    "idle": 5,
    "total": 15
  },
  "batcherStats": {
    "batchesProcessed": 1234,
    "messagesProcessed": 56789,
    "averageBatchSize": 46
  },
  "processorStats": {
    "messagesProcessed": 56789,
    "errors": 2,
    "successRate": 99.99
  },
  "performanceMetrics": {
    "averageResponseTime": 0.125,
    "p95": 0.234,
    "p99": 0.456
  }
}
```

### Get Performance Metrics

```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET /api/websocket/metrics
```

**Response:**

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "connections": {
    "current": 15,
    "peak": 25,
    "total": 1234
  },
  "messages": {
    "sent": 56789,
    "received": 54321,
    "dropped": 2
  },
  "performance": {
    "uptime": "15d 6h 30m",
    "memoryUsage": "45.2MB",
    "cpuUsage": "12.5%"
  }
}
```

### Check WebSocket Health

```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
GET /api/websocket/health
```

**Response:**

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "status": "healthy",
  "connectionCount": 15,
  "timestamp": "2024-01-15T10:30:00Z"
}
```

## Error Handling

### Connection Errors

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "error",
  "code": "connection_failed",
  "message": "WebSocket connection failed",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Subscription Errors

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "error",
  "code": "subscription_failed",
  "message": "Deployment not found",
  "details": {
    "deploymentId": "non-existent-deployment"
  },
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Rate Limiting

```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
{
  "type": "error",
  "code": "rate_limit_exceeded",
  "message": "Too many messages",
  "retryAfter": 30,
  "timestamp": "2024-01-15T10:30:00Z"
}
```

## Best Practices

### Connection Management

* Implement connection retry logic with exponential backoff
* Handle connection drops gracefully
* Monitor connection health and reestablish when needed
* Use appropriate heartbeat intervals

### Message Handling

* Process messages asynchronously to avoid blocking
* Implement message buffering for high-volume streams
* Handle message ordering and deduplication
* Monitor message processing performance

### Error Recovery

* Implement automatic reconnection on connection loss
* Handle subscription failures gracefully
* Monitor error rates and patterns
* Implement circuit breaker patterns

### Performance Optimization

* Use appropriate message compression
* Implement batching for high-frequency updates
* Monitor WebSocket performance metrics
* Optimize message serialization/deserialization

## Integration Examples

### Real-time Deployment Dashboard

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
class DeploymentMonitor {
  constructor(deploymentId) {
    this.deploymentId = deploymentId;
    this.ws = null;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket('ws://localhost:3000/api/websocket');

    this.ws.onopen = () => {
      this.ws.send(
        JSON.stringify({
          type: 'subscribe',
          deploymentId: this.deploymentId,
        })
      );
    };

    this.ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.handleMessage(data);
    };

    this.ws.onclose = () => {
      setTimeout(() => this.connect(), 5000); // Reconnect after 5 seconds
    };
  }

  handleMessage(data) {
    switch (data.type) {
      case 'deployment':
        this.updateProgress(data.progress);
        this.updateStatus(data.status, data.message);
        break;
      case 'log':
        this.addLog(data.level, data.message);
        break;
      case 'status':
        this.finalizeDeployment(data.status, data.message);
        break;
    }
  }
}
```

### Live Metrics Display

```javascript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
class MetricsDisplay {
  constructor(host, application) {
    this.host = host;
    this.application = application;
    this.metrics = {};
    this.connect();
  }

  connect() {
    this.ws = new WebSocket('ws://localhost:3000/api/websocket');

    this.ws.onopen = () => {
      this.ws.send(
        JSON.stringify({
          type: 'subscribe-metrics',
          host: this.host,
          application: this.application,
          metrics: ['cpu', 'memory', 'disk', 'network'],
        })
      );
    };

    this.ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === 'metrics') {
        this.updateMetrics(data);
      }
    };
  }

  updateMetrics(data) {
    this.metrics = { ...this.metrics, ...data };
    this.render();
  }

  render() {
    // Update UI with latest metrics
    document.getElementById('cpu-usage').textContent = `${this.metrics.cpu}%`;
    document.getElementById('memory-usage').textContent =
      `${this.metrics.memory}%`;
    // ... update other metrics
  }
}
```

For detailed schema definitions, refer to the OpenAPI specification published alongside the backend service.
