# WebSocket Integration

> Real-time astronomical data streaming with the Nyx WebSocket API

The Nyx WebSocket API enables real-time streaming of celestial object positions,
satellite tracking, and astronomical event alerts.

## Table of Contents

1. [Connection](#connection)
2. [Authentication](#authentication)
3. [Channels](#channels)
4. [Message Types](#message-types)
5. [Subscriptions](#subscriptions)
6. [Examples](#examples)
7. [Best Practices](#best-practices)
8. [Error Handling](#error-handling)

---

## Connection

### WebSocket Endpoint

| Environment | URL                                 |
| ----------- | ----------------------------------- |
| Production  | `wss://api.nyx.oshun.io/ws`         |
| Staging     | `wss://staging-api.nyx.oshun.io/ws` |
| Development | `ws://localhost:3000/ws`            |

### Basic Connection

```javascript
const ws = new WebSocket('wss://api.nyx.oshun.io/ws');

ws.onopen = () => {
  console.log('Connected to Nyx WebSocket');
};

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

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = (event) => {
  console.log('Disconnected:', event.code, event.reason);
};
```

### Connection Lifecycle

1. **Connect**: Establish WebSocket connection
2. **Authenticate**: Send API key (optional but recommended)
3. **Subscribe**: Subscribe to data channels
4. **Receive**: Process incoming messages
5. **Heartbeat**: Respond to ping messages
6. **Disconnect**: Clean up and reconnect if needed

---

## Authentication

### Sending Authentication

After connecting, send an auth message to authenticate:

```javascript
ws.send(
  JSON.stringify({
    type: 'auth',
    payload: {
      apiKey: 'nyx_pro_testkey789',
    },
  })
);
```

### Authentication Response

**Success:**

```json
{
  "type": "auth_response",
  "payload": {
    "success": true,
    "tier": "pro",
    "userId": "user_abc123",
    "limits": {
      "maxSubscriptions": 100,
      "minUpdateInterval": 100,
      "maxBatchSize": 500
    }
  },
  "timestamp": 1705334445000
}
```

**Failure:**

```json
{
  "type": "auth_response",
  "payload": {
    "success": false,
    "error": "Invalid API key",
    "code": "INVALID_API_KEY"
  },
  "timestamp": 1705334445000
}
```

### Tier Limits

| Tier       | Max Subscriptions | Min Interval | Max Batch |
| ---------- | ----------------- | ------------ | --------- |
| Anonymous  | 5                 | 5000ms       | 10        |
| Free       | 25                | 1000ms       | 50        |
| Pro        | 100               | 100ms        | 500       |
| Enterprise | 1000              | 10ms         | 5000      |

---

## Channels

Channels are named streams of data you can subscribe to. Channel names use the
format: `{type}:{filter}`.

### Available Channels

#### Object Position Channels

| Channel           | Description                            |
| ----------------- | -------------------------------------- |
| `objects:*`       | All celestial object positions         |
| `objects:{id}`    | Specific object (e.g., `objects:mars`) |
| `objects:planets` | All planets                            |
| `objects:moon`    | Moon position and phase                |

#### Satellite Channels

| Channel               | Description                                   |
| --------------------- | --------------------------------------------- |
| `satellites:*`        | All tracked satellites                        |
| `satellites:{id}`     | Specific satellite (e.g., `satellites:25544`) |
| `satellites:iss`      | ISS only                                      |
| `satellites:starlink` | Starlink constellation                        |

#### Event Channels

| Channel         | Description                |
| --------------- | -------------------------- |
| `events:*`      | All astronomical events    |
| `events:{type}` | Specific event type        |
| `events:alerts` | High-priority event alerts |

#### Pass Prediction Channels

| Channel                    | Description                     |
| -------------------------- | ------------------------------- |
| `passes:*`                 | All satellite passes            |
| `passes:{lat},{lon}`       | Passes for location             |
| `passes:{lat},{lon}:{sat}` | Passes for location + satellite |

#### Time Channels

| Channel     | Description                  |
| ----------- | ---------------------------- |
| `time:sync` | Time synchronization         |
| `time:tick` | Server time ticks (1 second) |

---

## Message Types

### Message Structure

All messages follow this structure:

```typescript
interface NyxMessage {
  type: string; // Message type identifier
  payload?: unknown; // Message data
  channel?: string; // Associated channel
  id?: string; // Message ID (for tracking)
  timestamp?: number; // Unix timestamp (ms)
}
```

### System Messages

#### Ping/Pong

The server sends ping messages every 30 seconds. You must respond with pong:

```json
// Server sends:
{ "type": "ping", "timestamp": 1705334445000 }

// Client responds:
{ "type": "pong", "timestamp": 1705334445000 }
```

#### Error

```json
{
  "type": "error",
  "payload": {
    "code": "SUBSCRIPTION_FAILED",
    "message": "Channel not found: invalid:channel",
    "details": {}
  },
  "timestamp": 1705334445000
}
```

### Subscription Messages

#### Subscribe Request

```json
{
  "type": "subscribe",
  "payload": {
    "channel": "satellites:25544",
    "options": {
      "updateInterval": 1000,
      "precision": "high",
      "observer": {
        "latitude": 40.7128,
        "longitude": -74.006,
        "elevation": 10
      }
    }
  },
  "id": "sub_abc123"
}
```

#### Subscribe Response

```json
{
  "type": "subscribed",
  "payload": {
    "channel": "satellites:25544",
    "success": true,
    "subscriptionId": "sub_abc123"
  },
  "timestamp": 1705334445000
}
```

#### Unsubscribe

```json
{
  "type": "unsubscribe",
  "payload": {
    "channel": "satellites:25544"
  }
}
```

### Data Messages

#### Position Update

```json
{
  "type": "position:update",
  "channel": "satellites:25544",
  "timestamp": 1705334445000,
  "payload": {
    "objectId": "25544",
    "objectName": "ISS",
    "timestamp": "2026-01-21T19:35:00.000Z",
    "equatorial": {
      "ra": 123.45,
      "dec": 45.67,
      "epoch": "J2000.0"
    },
    "horizontal": {
      "altitude": 35.2,
      "azimuth": 270.0
    },
    "distance": {
      "km": 408,
      "lightTime": 0.0014
    },
    "velocity": {
      "kmps": 7.66
    },
    "magnitude": -2.5,
    "isVisible": true,
    "illuminated": true
  }
}
```

#### Batch Update

```json
{
  "type": "position:batch",
  "channel": "objects:planets",
  "timestamp": 1705334445000,
  "payload": {
    "count": 8,
    "objects": [
      {
        "objectId": "mercury",
        "ra": 280.5,
        "dec": -23.4,
        "altitude": -15.2,
        "azimuth": 250.0,
        "magnitude": 0.5,
        "isVisible": false
      },
      {
        "objectId": "venus",
        "ra": 310.2,
        "dec": -18.1,
        "altitude": 12.5,
        "azimuth": 235.0,
        "magnitude": -4.2,
        "isVisible": true
      }
      // ... more planets
    ]
  }
}
```

### Alert Messages

#### Event Alert

```json
{
  "type": "alert:event",
  "channel": "events:alerts",
  "timestamp": 1705334445000,
  "payload": {
    "eventId": "evt_2026_iss_pass_123",
    "type": "satellite_pass",
    "priority": "high",
    "title": "ISS Pass Beginning",
    "message": "ISS is rising in the west. Maximum altitude: 78°",
    "data": {
      "satelliteId": "25544",
      "currentAltitude": 10,
      "maxAltitude": 78,
      "duration": 360,
      "magnitude": -2.5
    },
    "expiresAt": "2026-01-21T19:45:00.000Z"
  }
}
```

#### Pass Alert

```json
{
  "type": "alert:pass",
  "channel": "passes:40.7128,-74.0060",
  "timestamp": 1705334445000,
  "payload": {
    "phase": "start", // start, peak, end
    "satelliteId": "25544",
    "satelliteName": "ISS",
    "currentPosition": {
      "altitude": 15.2,
      "azimuth": 270.0
    },
    "maxAltitude": 78.5,
    "magnitude": -2.5,
    "remainingSeconds": 360
  }
}
```

---

## Subscriptions

### Subscribe to a Channel

```javascript
function subscribe(channel, options = {}) {
  ws.send(
    JSON.stringify({
      type: 'subscribe',
      payload: {
        channel,
        options,
      },
      id: `sub_${Date.now()}`,
    })
  );
}

// Subscribe to ISS position updates every second
subscribe('satellites:25544', {
  updateInterval: 1000,
  precision: 'high',
  observer: {
    latitude: 40.7128,
    longitude: -74.006,
  },
});

// Subscribe to all planet positions
subscribe('objects:planets', {
  updateInterval: 60000, // Update every minute
});

// Subscribe to event alerts
subscribe('events:alerts');
```

### Subscription Options

| Option           | Type    | Default  | Description                  |
| ---------------- | ------- | -------- | ---------------------------- |
| `updateInterval` | number  | tier-dep | Update frequency (ms)        |
| `precision`      | string  | "medium" | "low", "medium", "high"      |
| `observer`       | object  | null     | Observer location            |
| `includeRaw`     | boolean | false    | Include raw orbital elements |
| `format`         | string  | "json"   | Output format                |

### Unsubscribe

```javascript
function unsubscribe(channel) {
  ws.send(
    JSON.stringify({
      type: 'unsubscribe',
      payload: { channel },
    })
  );
}

unsubscribe('satellites:25544');
```

### List Active Subscriptions

```javascript
ws.send(JSON.stringify({
  type: 'list_subscriptions'
}));

// Response:
{
  "type": "subscriptions",
  "payload": {
    "subscriptions": [
      {
        "channel": "satellites:25544",
        "subscriptionId": "sub_abc123",
        "options": { "updateInterval": 1000 },
        "subscribedAt": "2026-01-21T19:30:00.000Z"
      }
    ],
    "count": 1,
    "limit": 100
  }
}
```

---

## Examples

### Track ISS in Real-Time

```javascript
class ISSTracker {
  constructor(apiKey, observer) {
    this.apiKey = apiKey;
    this.observer = observer;
    this.ws = null;
    this.callbacks = new Map();
  }

  connect() {
    this.ws = new WebSocket('wss://api.nyx.oshun.io/ws');

    this.ws.onopen = () => {
      // Authenticate
      this.send('auth', { apiKey: this.apiKey });
    };

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

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    this.ws.onclose = () => {
      console.log('Disconnected. Reconnecting in 5s...');
      setTimeout(() => this.connect(), 5000);
    };
  }

  handleMessage(message) {
    switch (message.type) {
      case 'auth_response':
        if (message.payload.success) {
          this.subscribeToISS();
        }
        break;

      case 'ping':
        this.send('pong', { timestamp: message.timestamp });
        break;

      case 'position:update':
        if (message.channel === 'satellites:25544') {
          this.onISSUpdate(message.payload);
        }
        break;

      case 'alert:pass':
        this.onPassAlert(message.payload);
        break;
    }
  }

  subscribeToISS() {
    this.send('subscribe', {
      channel: 'satellites:25544',
      options: {
        updateInterval: 1000,
        precision: 'high',
        observer: this.observer,
      },
    });

    this.send('subscribe', {
      channel: `passes:${this.observer.latitude},${this.observer.longitude}:25544`,
    });
  }

  send(type, payload) {
    this.ws.send(JSON.stringify({ type, payload }));
  }

  onISSUpdate(data) {
    console.log(
      `ISS: Alt ${data.horizontal.altitude.toFixed(1)}°, ` +
        `Az ${data.horizontal.azimuth.toFixed(1)}°, ` +
        `Visible: ${data.isVisible}`
    );
  }

  onPassAlert(data) {
    if (data.phase === 'start') {
      console.log(
        `🛰️ ISS pass starting! Look ${data.currentPosition.azimuth}°`
      );
    }
  }
}

// Usage
const tracker = new ISSTracker('nyx_pro_testkey789', {
  latitude: 40.7128,
  longitude: -74.006,
});
tracker.connect();
```

### Monitor Astronomical Events

```javascript
function monitorEvents(apiKey) {
  const ws = new WebSocket('wss://api.nyx.oshun.io/ws');

  ws.onopen = () => {
    // Authenticate
    ws.send(
      JSON.stringify({
        type: 'auth',
        payload: { apiKey },
      })
    );
  };

  ws.onmessage = (event) => {
    const message = JSON.parse(event.data);

    if (message.type === 'auth_response' && message.payload.success) {
      // Subscribe to event alerts
      ws.send(
        JSON.stringify({
          type: 'subscribe',
          payload: {
            channel: 'events:alerts',
          },
        })
      );
    }

    if (message.type === 'alert:event') {
      const { title, message: desc, priority } = message.payload;
      console.log(`[${priority.toUpperCase()}] ${title}: ${desc}`);

      // Send notification
      if (priority === 'high') {
        showNotification(title, desc);
      }
    }

    if (message.type === 'ping') {
      ws.send(
        JSON.stringify({
          type: 'pong',
          timestamp: message.timestamp,
        })
      );
    }
  };
}
```

### Track Multiple Objects

```javascript
async function trackPlanets(apiKey, observer) {
  const ws = new WebSocket('wss://api.nyx.oshun.io/ws');

  const planets = {};

  ws.onopen = () => {
    ws.send(
      JSON.stringify({
        type: 'auth',
        payload: { apiKey },
      })
    );
  };

  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);

    switch (msg.type) {
      case 'auth_response':
        // Subscribe to all planets
        ws.send(
          JSON.stringify({
            type: 'subscribe',
            payload: {
              channel: 'objects:planets',
              options: {
                updateInterval: 60000,
                observer,
              },
            },
          })
        );
        break;

      case 'position:batch':
        msg.payload.objects.forEach((obj) => {
          planets[obj.objectId] = obj;
        });
        renderPlanetTable(planets);
        break;

      case 'ping':
        ws.send(JSON.stringify({ type: 'pong' }));
        break;
    }
  };
}
```

---

## Best Practices

### Connection Management

```javascript
class NyxWebSocket {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 10;
    this.reconnectDelay = 1000;
    this.subscriptions = new Map();
  }

  connect() {
    this.ws = new WebSocket('wss://api.nyx.oshun.io/ws');

    this.ws.onopen = () => {
      this.reconnectAttempts = 0;
      this.authenticate();
    };

    this.ws.onclose = (event) => {
      if (event.code !== 1000) {
        this.reconnect();
      }
    };

    this.ws.onerror = () => {
      // Error handling is done in onclose
    };
  }

  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached');
      return;
    }

    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts);
    this.reconnectAttempts++;

    console.log(
      `Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`
    );

    setTimeout(() => {
      this.connect();
    }, delay);
  }

  authenticate() {
    this.send('auth', { apiKey: this.apiKey });
  }

  // Resubscribe after reconnection
  resubscribe() {
    for (const [channel, options] of this.subscriptions) {
      this.send('subscribe', { channel, options });
    }
  }

  subscribe(channel, options = {}) {
    this.subscriptions.set(channel, options);
    this.send('subscribe', { channel, options });
  }

  send(type, payload) {
    if (this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({ type, payload }));
    }
  }
}
```

### Heartbeat Handling

Always respond to ping messages to keep the connection alive:

```javascript
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  if (message.type === 'ping') {
    ws.send(
      JSON.stringify({
        type: 'pong',
        timestamp: message.timestamp,
      })
    );
    return;
  }

  // Handle other messages...
};
```

### Memory Management

Unsubscribe from channels you no longer need:

```javascript
// When component unmounts or feature is disabled
function cleanup() {
  subscriptions.forEach((channel) => {
    ws.send(
      JSON.stringify({
        type: 'unsubscribe',
        payload: { channel },
      })
    );
  });
  subscriptions.clear();
}
```

---

## Error Handling

### Error Codes

| Code                  | Description                 |
| --------------------- | --------------------------- |
| `INVALID_MESSAGE`     | Malformed message           |
| `INVALID_API_KEY`     | API key invalid or expired  |
| `UNAUTHORIZED`        | Authentication required     |
| `SUBSCRIPTION_FAILED` | Channel subscription failed |
| `SUBSCRIPTION_LIMIT`  | Max subscriptions exceeded  |
| `RATE_LIMITED`        | Too many messages           |
| `CHANNEL_NOT_FOUND`   | Invalid channel name        |
| `INTERNAL_ERROR`      | Server error                |

### Handling Errors

```javascript
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  if (message.type === 'error') {
    const { code, message: errorMsg } = message.payload;

    switch (code) {
      case 'INVALID_API_KEY':
        console.error('Invalid API key. Please check your credentials.');
        // Don't reconnect with same key
        break;

      case 'SUBSCRIPTION_LIMIT':
        console.warn('Subscription limit reached. Removing old subscriptions.');
        // Remove least important subscription
        break;

      case 'RATE_LIMITED':
        console.warn('Rate limited. Reducing message frequency.');
        // Increase update intervals
        break;

      default:
        console.error(`Error: ${errorMsg}`);
    }
  }
};
```

---

## Next: [Widget Embedding](./widgets.md)
