Skip to main content

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 API Reference

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

Endpoints Overview

MethodEndpointDescription
GET/api/websocket/statsGet WebSocket statistics
GET/api/websocket/metricsGet performance metrics
GET/api/websocket/healthCheck WebSocket service health

WebSocket Connection

Establishing Connection

Connect to the WebSocket endpoint:
// 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

{
  "type": "deployment",
  "deploymentId": "deploy-20240115-103000",
  "status": "running",
  "message": "Installing dependencies...",
  "timestamp": "2024-01-15T10:30:00Z",
  "progress": 45
}

Log Messages

{
  "type": "log",
  "host": "test-anvil-01",
  "application": "Anvil",
  "level": "INFO",
  "message": "Application started successfully",
  "timestamp": "2024-01-15T10:30:00Z"
}

Metrics Messages

{
  "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

{
  "type": "status",
  "status": "completed",
  "message": "Deployment completed successfully",
  "timestamp": "2024-01-15T10:35:00Z"
}

Subscription Management

Subscribe to Deployment

ws.send(
  JSON.stringify({
    type: 'subscribe',
    deploymentId: 'deploy-20240115-103000',
  })
);

Subscribe to Logs

ws.send(
  JSON.stringify({
    type: 'subscribe-logs',
    host: 'test-anvil-01',
    application: 'Anvil',
    search: 'error',
  })
);

Subscribe to Metrics

ws.send(
  JSON.stringify({
    type: 'subscribe-metrics',
    host: 'test-anvil-01',
    application: 'Anvil',
    metrics: ['cpu', 'memory', 'disk'],
  })
);

Unsubscribe

ws.send(
  JSON.stringify({
    type: 'unsubscribe',
    subscriptionId: 'sub-123456',
  })
);

API Endpoints

Get WebSocket Statistics

GET /api/websocket/stats
Response:
{
  "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

GET /api/websocket/metrics
Response:
{
  "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

GET /api/websocket/health
Response:
{
  "status": "healthy",
  "connectionCount": 15,
  "timestamp": "2024-01-15T10:30:00Z"
}

Error Handling

Connection Errors

{
  "type": "error",
  "code": "connection_failed",
  "message": "WebSocket connection failed",
  "timestamp": "2024-01-15T10:30:00Z"
}

Subscription Errors

{
  "type": "error",
  "code": "subscription_failed",
  "message": "Deployment not found",
  "details": {
    "deploymentId": "non-existent-deployment"
  },
  "timestamp": "2024-01-15T10:30:00Z"
}

Rate Limiting

{
  "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

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

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.