---
title: "HTTP Sync Server Quick Start Guide"
---

# HTTP Sync Server Quick Start Guide

## HeliosDB Nano HTTP Sync API Quick Reference

### 1. Installation

```bash
# Add to Cargo.toml
[dependencies]
heliosdb-nano = { version = "4", features = ["sync-experimental"] }
```

### 2. Start the Server

```bash
# Run the example
cargo run --example http_sync_server_example

# Or build and run
cargo build --release
JWT_SECRET=your-secret-key ./target/release/heliosdb-nano-sync-server
```

### 3. Quick Test

```bash
# Health check
curl http://localhost:8080/api/v1/sync/health

# Expected response:
{
  "status": "healthy",
  "version": 1,
  "uptime_secs": 10,
  "registered_clients": 0,
  "timestamp": 1700000000000
}
```

### 4. Generate JWT Token

```rust
use heliosdb_nano::sync::auth::JwtManager;
use uuid::Uuid;

let jwt_manager = JwtManager::new(b"your-secret-key");
let token = jwt_manager.generate_token(
    "user-id".to_string(),
    "tenant-id".to_string(),
    Uuid::new_v4(),
)?;
```

### 5. Register Client

```bash
curl -X POST http://localhost:8080/api/v1/sync/register \
  -H "Content-Type: application/json" \
  -d '{
    "type": "register_client",
    "version": 1,
    "client_id": "my-client-123",
    "last_known_lsn": 0,
    "vector_clock": {},
    "metadata": {"device": "mobile"}
  }'
```

### 6. Pull Changes

```bash
TOKEN="your-jwt-token-here"

curl -X POST http://localhost:8080/api/v1/sync/pull \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "type": "pull_request",
    "message_id": "550e8400-e29b-41d4-a716-446655440000",
    "client_id": "my-client-123",
    "since_lsn": 0,
    "max_entries": 100,
    "continuation_token": null
  }'
```

### 7. Push Changes

```bash
curl -X POST http://localhost:8080/api/v1/sync/push \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "type": "push_changes",
    "message_id": "660e8400-e29b-41d4-a716-446655440001",
    "client_id": "my-client-123",
    "changes": [{
      "lsn": 1,
      "table": "tasks",
      "operation": "Insert",
      "key": [1, 2, 3],
      "data": [10, 20, 30],
      "vector_clock": {},
      "timestamp": "2025-11-24T10:30:00Z",
      "checksum": 987654321,
      "compressed": false
    }],
    "vector_clock": {}
  }'
```

### 8. Send Heartbeat

```bash
curl -X POST http://localhost:8080/api/v1/sync/heartbeat \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "type": "heartbeat",
    "client_id": "my-client-123",
    "timestamp": 1700000000000,
    "current_lsn": 10
  }'
```

## Common Operations

### Create a Custom Server

```rust
use heliosdb_nano::sync::{
    HttpSyncServer,
    SyncProtocol,
    auth::{JwtManager, Authorizer},
};
use std::sync::Arc;

// Create protocol
let protocol = Arc::new(SyncProtocol::new(
    change_log,
    conflict_detector,
));

// Configure auth
let jwt_manager = JwtManager::new(b"secret");
let mut authorizer = Authorizer::new();
authorizer.add_tenant("my-tenant".to_string());

// Create server
let server = HttpSyncServer::with_auth(
    protocol,
    "0.0.0.0:8080".parse()?,
    jwt_manager,
    authorizer,
);

// Start serving
server.serve().await?;
```

### Handle Pagination

```rust
let mut continuation_token = None;
let mut all_changes = Vec::new();

loop {
    let pull_request = SyncMessage::PullRequest {
        message_id: Uuid::new_v4(),
        client_id: client_id.clone(),
        since_lsn: 0,
        max_entries: 100,
        continuation_token: continuation_token.clone(),
    };

    let response = pull_changes(pull_request).await?;

    match response {
        SyncMessage::PullResponse {
            changes,
            has_more,
            continuation_token: next_token,
            ..
        } => {
            all_changes.extend(changes);

            if !has_more {
                break;
            }

            continuation_token = next_token;
        }
        _ => return Err("Unexpected response"),
    }
}
```

### Error Handling

```rust
match response.status() {
    StatusCode::OK => {
        let data: PullResponse = response.json().await?;
        // Process data
    }
    StatusCode::UNAUTHORIZED => {
        // Refresh token or re-authenticate
    }
    StatusCode::CONFLICT => {
        let error: ErrorResponse = response.json().await?;
        // Handle conflicts
    }
    status => {
        eprintln!("Error: {}", status);
    }
}
```

## Configuration

### Environment Variables

```bash
# JWT secret (required for production)
export JWT_SECRET="your-256-bit-secret-key"

# Bind address (optional, default: 0.0.0.0:8080)
export BIND_ADDR="0.0.0.0:8080"

# Log level (optional, default: info)
export RUST_LOG="info,heliosdb_nano=debug"
```

### HTTPS/TLS

Use a reverse proxy (nginx, Caddy, or Traefik):

```nginx
# nginx configuration
server {
    listen 443 ssl http2;
    server_name sync.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location /api/v1/sync/ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

## Troubleshooting

### "Connection refused"

Server not running. Start the server:
```bash
cargo run --example http_sync_server_example
```

### "401 Unauthorized"

Invalid or expired JWT token. Generate a new token:
```rust
let token = jwt_manager.generate_token(user_id, tenant_id, client_id)?;
```

### "400 Bad Request"

Check JSON format and required fields:
```bash
# Validate JSON
echo '{"type": "register_client", ...}' | jq .
```

### "Client not registered"

Register the client first before pull/push/heartbeat:
```bash
curl -X POST .../register -d '{"type": "register_client", ...}'
```

## Performance Tips

1. **Batch requests**: Use max batch size (1000 entries)
2. **Enable compression**: Server supports gzip automatically
3. **Reuse connections**: Use HTTP keep-alive
4. **Cache tokens**: JWT tokens valid for 1 hour
5. **Monitor latency**: Check p95/p99 response times

## Security Checklist

- [ ] Use HTTPS in production
- [ ] Strong JWT secret (256+ bits)
- [ ] Rotate secrets regularly
- [ ] Enable rate limiting
- [ ] Validate all inputs
- [ ] Monitor authentication failures
- [ ] Use tenant isolation
- [ ] Enable audit logging

## Next Steps

1. Read full [API Documentation](https://www.heliosdb.com/docs/nano/guides/api/http_sync_api/)
2. Review Implementation Details
3. Run integration tests: `cargo test http_sync_integration_test`
4. Deploy to production with hardening

## Support

- GitHub Issues: https://github.com/HeliosDatabase/HeliosDB-Nano
- Documentation: /docs/guides/api/HTTP_SYNC_API.md
- Examples: /examples/http_sync_server_example.rs
