SweatHost
SDK Reference

Regions API

Complete reference for regions and clusters

Overview

The Regions API provides information about available regions, clusters, and their capacity.

Methods

list()

List all available regions and their clusters.

Parameters

interface ListRegionsParams {
  /**
   * Include capacity information
   * @default true
   */
  includeCapacity?: boolean;

  /**
   * Include pricing information
   * @default false
   */
  includePricing?: boolean;
}

Return Type

interface ListRegionsResponse {
  data: Region[];
}

interface Region {
  code: string;
  name: string;
  location: string;
  continent: string;
  country: string;
  city: string;
  coordinates: {
    latitude: number;
    longitude: number;
  };
  clusters: Cluster[];
  status: 'active' | 'maintenance' | 'inactive';
  features: string[];
}

interface Cluster {
  id: string;
  name: string;
  tier: 'standard' | 'performance' | 'premium';
  status: 'active' | 'maintenance' | 'full';
  capacity: {
    total: number;
    available: number;
    used: number;
    reserved: number;
  };
  specs: {
    cpu: string;
    memory: string;
    network: string;
    tickRate: number[];
  };
  pricing: {
    hourly: number;
    monthly: number;
    currency: string;
  };
}

Example

const regions = await client.regions.list({
  includeCapacity: true,
  includePricing: true,
});

console.log(`Available regions: ${regions.data.length}`);

regions.data.forEach(region => {
  console.log(`\n${region.name} (${region.code})`);
  console.log(`  Location: ${region.city}, ${region.country}`);
  console.log(`  Status: ${region.status}`);
  console.log(`  Clusters: ${region.clusters.length}`);
  
  region.clusters.forEach(cluster => {
    console.log(`\n  ${cluster.name} (${cluster.tier})`);
    console.log(`    Available: ${cluster.capacity.available}/${cluster.capacity.total}`);
    console.log(`    Price: $${cluster.pricing.hourly}/hour`);
    console.log(`    CPU: ${cluster.specs.cpu}`);
    console.log(`    Memory: ${cluster.specs.memory}`);
  });
});

Errors

Error CodeDescription
UNAUTHORIZEDInvalid or missing API key

get()

Get detailed information about a specific region.

Parameters

/**
 * @param regionCode - The region code (e.g., "us-east")
 */
get(regionCode: string): Promise<RegionDetails>

Return Type

interface RegionDetails extends Region {
  latency: {
    average: number;
    p50: number;
    p95: number;
    p99: number;
  };
  uptime: {
    current: number;
    last24h: number;
    last7d: number;
    last30d: number;
  };
  metrics: {
    activeServers: number;
    activeMatches: number;
    totalPlayers: number;
  };
}

Example

const region = await client.regions.get('us-east');

console.log(`Region: ${region.name}`);
console.log(`Location: ${region.city}, ${region.country}`);
console.log(`\nLatency:`);
console.log(`  Average: ${region.latency.average}ms`);
console.log(`  P95: ${region.latency.p95}ms`);
console.log(`\nUptime:`);
console.log(`  Current: ${region.uptime.current}%`);
console.log(`  Last 30 days: ${region.uptime.last30d}%`);
console.log(`\nUsage:`);
console.log(`  Active Servers: ${region.metrics.activeServers}`);
console.log(`  Active Matches: ${region.metrics.activeMatches}`);
console.log(`  Total Players: ${region.metrics.totalPlayers}`);

Errors

Error CodeDescription
UNAUTHORIZEDInvalid or missing API key
NOT_FOUNDRegion not found

getCluster()

Get detailed information about a specific cluster.

Parameters

/**
 * @param clusterId - The unique cluster ID
 */
getCluster(clusterId: string): Promise<ClusterDetails>

Return Type

interface ClusterDetails extends Cluster {
  region: {
    code: string;
    name: string;
  };
  health: {
    status: 'healthy' | 'degraded' | 'unhealthy';
    lastCheck: string;
    issues: string[];
  };
  performance: {
    avgCpu: number;
    avgMemory: number;
    avgNetwork: number;
  };
  servers: {
    total: number;
    running: number;
    starting: number;
    stopping: number;
    error: number;
  };
}

Example

const cluster = await client.regions.getCluster('cluster_abc123');

console.log(`Cluster: ${cluster.name}`);
console.log(`Region: ${cluster.region.name}`);
console.log(`Tier: ${cluster.tier}`);
console.log(`\nHealth: ${cluster.health.status}`);
console.log(`\nCapacity:`);
console.log(`  Available: ${cluster.capacity.available}/${cluster.capacity.total}`);
console.log(`  Used: ${cluster.capacity.used}`);
console.log(`  Reserved: ${cluster.capacity.reserved}`);
console.log(`\nPerformance:`);
console.log(`  Avg CPU: ${cluster.performance.avgCpu}%`);
console.log(`  Avg Memory: ${cluster.performance.avgMemory}%`);
console.log(`\nServers:`);
console.log(`  Running: ${cluster.servers.running}`);
console.log(`  Starting: ${cluster.servers.starting}`);
console.log(`  Total: ${cluster.servers.total}`);

findOptimal()

Find the optimal region/cluster based on criteria.

Parameters

interface FindOptimalParams {
  /**
   * Player locations (lat/lng or region codes)
   */
  playerLocations?: Array<{
    latitude: number;
    longitude: number;
  } | string>;

  /**
   * Required capacity
   * @default 1
   */
  requiredCapacity?: number;

  /**
   * Preferred cluster tier
   */
  preferredTier?: 'standard' | 'performance' | 'premium';

  /**
   * Maximum acceptable latency (ms)
   */
  maxLatency?: number;

  /**
   * Optimization strategy
   * @default "balanced"
   */
  strategy?: 'latency' | 'cost' | 'balanced';
}

Return Type

interface OptimalRegionResponse {
  recommended: {
    region: Region;
    cluster: Cluster;
    score: number;
    reasoning: string[];
  };
  alternatives: Array<{
    region: Region;
    cluster: Cluster;
    score: number;
    reasoning: string[];
  }>;
  analysis: {
    avgLatency: number;
    estimatedCost: number;
    availableCapacity: number;
  };
}

Example

// Find optimal region for players
const optimal = await client.regions.findOptimal({
  playerLocations: [
    { latitude: 40.7128, longitude: -74.0060 }, // New York
    { latitude: 34.0522, longitude: -118.2437 }, // Los Angeles
    { latitude: 41.8781, longitude: -87.6298 }, // Chicago
  ],
  requiredCapacity: 10,
  preferredTier: 'performance',
  strategy: 'latency',
});

console.log(`Recommended: ${optimal.recommended.region.name}`);
console.log(`Cluster: ${optimal.recommended.cluster.name}`);
console.log(`Score: ${optimal.recommended.score}/100`);
console.log(`\nReasons:`);
optimal.recommended.reasoning.forEach(reason => {
  console.log(`  - ${reason}`);
});

console.log(`\nAnalysis:`);
console.log(`  Avg Latency: ${optimal.analysis.avgLatency}ms`);
console.log(`  Est. Cost: $${optimal.analysis.estimatedCost}/hour`);

console.log(`\nAlternatives:`);
optimal.alternatives.slice(0, 3).forEach((alt, i) => {
  console.log(`  ${i + 1}. ${alt.region.name} - ${alt.cluster.name} (${alt.score}/100)`);
});

testLatency()

Test latency to regions from your location.

Parameters

interface TestLatencyParams {
  /**
   * Regions to test (empty = all regions)
   */
  regions?: string[];

  /**
   * Number of ping attempts
   * @default 5
   */
  attempts?: number;
}

Return Type

interface LatencyTestResponse {
  results: Array<{
    region: {
      code: string;
      name: string;
    };
    latency: {
      min: number;
      max: number;
      avg: number;
      median: number;
      jitter: number;
    };
    packetLoss: number;
    attempts: number;
  }>;
  yourLocation: {
    country: string;
    city: string;
    coordinates: {
      latitude: number;
      longitude: number;
    };
  };
}

Example

const latencyTest = await client.regions.testLatency({
  regions: ['us-east', 'us-west', 'eu-west'],
  attempts: 10,
});

console.log(`Your location: ${latencyTest.yourLocation.city}, ${latencyTest.yourLocation.country}`);
console.log(`\nLatency Results:`);

latencyTest.results
  .sort((a, b) => a.latency.avg - b.latency.avg)
  .forEach(result => {
    console.log(`\n${result.region.name}:`);
    console.log(`  Min: ${result.latency.min}ms`);
    console.log(`  Avg: ${result.latency.avg}ms`);
    console.log(`  Max: ${result.latency.max}ms`);
    console.log(`  Jitter: ${result.latency.jitter}ms`);
    console.log(`  Packet Loss: ${result.packetLoss}%`);
  });

// Find best region
const best = latencyTest.results[0];
console.log(`\nBest region: ${best.region.name} (${best.latency.avg}ms avg)`);

Helper Functions

Calculate Distance

function calculateDistance(
  point1: { latitude: number; longitude: number },
  point2: { latitude: number; longitude: number }
): number {
  const R = 6371; // Earth's radius in km
  const dLat = (point2.latitude - point1.latitude) * Math.PI / 180;
  const dLon = (point2.longitude - point1.longitude) * Math.PI / 180;
  
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(point1.latitude * Math.PI / 180) *
    Math.cos(point2.latitude * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

// Usage
const regions = await client.regions.list();
const playerLocation = { latitude: 40.7128, longitude: -74.0060 };

const sortedByDistance = regions.data
  .map(region => ({
    region,
    distance: calculateDistance(playerLocation, region.coordinates),
  }))
  .sort((a, b) => a.distance - b.distance);

console.log('Closest regions:');
sortedByDistance.slice(0, 3).forEach(({ region, distance }) => {
  console.log(`  ${region.name}: ${distance.toFixed(0)}km`);
});

Find Available Clusters

async function findAvailableClusters(
  minCapacity: number = 1,
  tier?: 'standard' | 'performance' | 'premium'
) {
  const regions = await client.regions.list({ includeCapacity: true });
  
  const available: Array<{
    region: string;
    cluster: Cluster;
  }> = [];

  regions.data.forEach(region => {
    region.clusters.forEach(cluster => {
      if (
        cluster.status === 'active' &&
        cluster.capacity.available >= minCapacity &&
        (!tier || cluster.tier === tier)
      ) {
        available.push({
          region: region.code,
          cluster,
        });
      }
    });
  });

  return available;
}

// Usage
const available = await findAvailableClusters(10, 'performance');
console.log(`Found ${available.length} available clusters`);

Compare Regions

async function compareRegions(regionCodes: string[]) {
  const regions = await Promise.all(
    regionCodes.map(code => client.regions.get(code))
  );

  console.log('Region Comparison:\n');
  console.log('Metric'.padEnd(20), ...regionCodes.map(c => c.padEnd(15)));
  console.log('-'.repeat(20 + regionCodes.length * 15));

  // Latency
  console.log(
    'Avg Latency (ms)'.padEnd(20),
    ...regions.map(r => r.latency.average.toString().padEnd(15))
  );

  // Uptime
  console.log(
    'Uptime (30d)'.padEnd(20),
    ...regions.map(r => `${r.uptime.last30d}%`.padEnd(15))
  );

  // Active Servers
  console.log(
    'Active Servers'.padEnd(20),
    ...regions.map(r => r.metrics.activeServers.toString().padEnd(15))
  );

  // Clusters
  console.log(
    'Clusters'.padEnd(20),
    ...regions.map(r => r.clusters.length.toString().padEnd(15))
  );
}

// Usage
await compareRegions(['us-east', 'us-west', 'eu-west']);

Complete Example

import { SweatHostClient } from '@sweathost/sdk';

async function selectOptimalRegion() {
  const client = new SweatHostClient({
    apiKey: process.env.SWEATHOST_API_KEY!,
  });

  try {
    // Test latency from your location
    console.log('Testing latency to all regions...');
    const latencyTest = await client.regions.testLatency();

    console.log(`Your location: ${latencyTest.yourLocation.city}`);

    // Find regions with good latency
    const goodLatency = latencyTest.results
      .filter(r => r.latency.avg < 50)
      .map(r => r.region.code);

    console.log(`\nRegions with <50ms latency: ${goodLatency.join(', ')}`);

    // Find optimal region for multiple players
    const optimal = await client.regions.findOptimal({
      playerLocations: [
        { latitude: 40.7128, longitude: -74.0060 }, // NYC
        { latitude: 34.0522, longitude: -118.2437 }, // LA
      ],
      requiredCapacity: 10,
      preferredTier: 'performance',
      strategy: 'balanced',
    });

    console.log(`\nRecommended region: ${optimal.recommended.region.name}`);
    console.log(`Cluster: ${optimal.recommended.cluster.name}`);
    console.log(`Estimated cost: $${optimal.analysis.estimatedCost}/hour`);

    // Get detailed region info
    const regionDetails = await client.regions.get(
      optimal.recommended.region.code
    );

    console.log(`\nRegion details:`);
    console.log(`  Uptime: ${regionDetails.uptime.last30d}%`);
    console.log(`  Active servers: ${regionDetails.metrics.activeServers}`);
    console.log(`  Available clusters: ${regionDetails.clusters.length}`);

    // Create server in optimal region
    const server = await client.gameServers.create({
      name: 'Optimal Server',
      game: 'cs2',
      region: optimal.recommended.region.code,
      clusterId: optimal.recommended.cluster.id,
      config: {
        maxPlayers: 10,
        tickRate: 128,
      },
    });

    console.log(`\nServer created: ${server.id}`);
    console.log(`Region: ${server.region}`);

  } catch (error) {
    console.error('Error:', error);
  }
}

selectOptimalRegion();

Next Steps

On this page