467 lines
9.0 KiB
Markdown
467 lines
9.0 KiB
Markdown
# API Reference - sdk_relay
|
|
|
|
## Vue d'Ensemble
|
|
|
|
`sdk_relay` expose deux interfaces principales :
|
|
- **WebSocket** (port 8090) : Communication temps réel
|
|
- **HTTP** (port 8091) : API REST
|
|
|
|
## Interface WebSocket
|
|
|
|
### Connexion
|
|
```javascript
|
|
const ws = new WebSocket('ws://localhost:8090');
|
|
```
|
|
|
|
### Handshake Initial
|
|
```javascript
|
|
// Message de handshake
|
|
const handshake = {
|
|
"type": "handshake",
|
|
"client_id": "my-client",
|
|
"version": "1.0.0",
|
|
"capabilities": ["sync", "notifications"]
|
|
};
|
|
|
|
ws.send(JSON.stringify(handshake));
|
|
```
|
|
|
|
### Types de Messages
|
|
|
|
#### 1. Messages de Synchronisation
|
|
```json
|
|
{
|
|
"type": "sync",
|
|
"sync_type": "StateSync",
|
|
"relay_id": "relay-1",
|
|
"payload": {
|
|
"state": {
|
|
"uptime": "3600",
|
|
"version": "1.0.0",
|
|
"network": "signet"
|
|
}
|
|
},
|
|
"timestamp": 1703001600,
|
|
"message_id": "msg-123"
|
|
}
|
|
```
|
|
|
|
#### 2. Messages de Notification
|
|
```json
|
|
{
|
|
"type": "notification",
|
|
"notification_type": "payment_detected",
|
|
"data": {
|
|
"txid": "abc123...",
|
|
"block_height": 12345,
|
|
"amount": "0.001",
|
|
"address": "sp1..."
|
|
},
|
|
"timestamp": 1703001600
|
|
}
|
|
```
|
|
|
|
#### 3. Messages de Santé
|
|
```json
|
|
{
|
|
"type": "health",
|
|
"status": "healthy",
|
|
"metrics": {
|
|
"uptime": 3600,
|
|
"memory_usage": "128MB",
|
|
"cpu_usage": "5%",
|
|
"connections": 10
|
|
},
|
|
"timestamp": 1703001600
|
|
}
|
|
```
|
|
|
|
### Événements WebSocket
|
|
|
|
#### Connexion
|
|
```javascript
|
|
ws.onopen = function() {
|
|
console.log('Connecté à sdk_relay');
|
|
// Envoyer le handshake
|
|
ws.send(JSON.stringify(handshake));
|
|
};
|
|
```
|
|
|
|
#### Réception de Messages
|
|
```javascript
|
|
ws.onmessage = function(event) {
|
|
const message = JSON.parse(event.data);
|
|
|
|
switch(message.type) {
|
|
case 'handshake_response':
|
|
console.log('Handshake accepté');
|
|
break;
|
|
case 'sync':
|
|
handleSyncMessage(message);
|
|
break;
|
|
case 'notification':
|
|
handleNotification(message);
|
|
break;
|
|
case 'health':
|
|
handleHealthUpdate(message);
|
|
break;
|
|
}
|
|
};
|
|
```
|
|
|
|
#### Gestion d'Erreurs
|
|
```javascript
|
|
ws.onerror = function(error) {
|
|
console.error('Erreur WebSocket:', error);
|
|
};
|
|
|
|
ws.onclose = function(event) {
|
|
console.log('Connexion fermée:', event.code, event.reason);
|
|
};
|
|
```
|
|
|
|
## Interface HTTP
|
|
|
|
### Base URL
|
|
```
|
|
http://localhost:8091
|
|
```
|
|
|
|
### Endpoints
|
|
|
|
#### 1. Santé du Service
|
|
```http
|
|
GET /health
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"status": "healthy",
|
|
"uptime": 3600,
|
|
"version": "1.0.0",
|
|
"timestamp": 1703001600
|
|
}
|
|
```
|
|
|
|
#### 2. Métriques
|
|
```http
|
|
GET /metrics
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"sync_metrics": {
|
|
"known_relays": 3,
|
|
"mesh_connections": 6,
|
|
"sync_requests": 150,
|
|
"sync_responses": 150,
|
|
"cache_hits": 120,
|
|
"cache_misses": 30,
|
|
"avg_latency": 45.2,
|
|
"error_count": 0
|
|
},
|
|
"system_metrics": {
|
|
"memory_usage": "128MB",
|
|
"cpu_usage": "5%",
|
|
"active_connections": 10,
|
|
"total_requests": 1000
|
|
}
|
|
}
|
|
```
|
|
|
|
#### 3. Configuration
|
|
```http
|
|
GET /config
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"relay_id": "relay-1",
|
|
"network": "signet",
|
|
"ws_url": "0.0.0.0:8090",
|
|
"http_url": "0.0.0.0:8091",
|
|
"bitcoin_core": {
|
|
"url": "http://bitcoin:18443",
|
|
"wallet": "relay_wallet"
|
|
},
|
|
"blindbit": {
|
|
"url": "http://blindbit:8000"
|
|
},
|
|
"sync": {
|
|
"interval": 30,
|
|
"health_interval": 60
|
|
}
|
|
}
|
|
```
|
|
|
|
#### 4. Relais Connus
|
|
```http
|
|
GET /relays
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"relays": [
|
|
{
|
|
"relay_id": "relay-1",
|
|
"address": "sdk_relay_1:8090",
|
|
"version": "1.0.0",
|
|
"uptime": 3600,
|
|
"health": "healthy",
|
|
"last_seen": 1703001600
|
|
},
|
|
{
|
|
"relay_id": "relay-2",
|
|
"address": "sdk_relay_2:8090",
|
|
"version": "1.0.0",
|
|
"uptime": 3600,
|
|
"health": "healthy",
|
|
"last_seen": 1703001600
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
#### 5. Statut de Synchronisation
|
|
```http
|
|
GET /sync/status
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"status": "syncing",
|
|
"last_sync": 1703001600,
|
|
"next_sync": 1703001630,
|
|
"sync_types": [
|
|
"StateSync",
|
|
"HealthSync",
|
|
"MetricsSync"
|
|
],
|
|
"errors": []
|
|
}
|
|
```
|
|
|
|
#### 6. Forcer la Synchronisation
|
|
```http
|
|
POST /sync/force
|
|
Content-Type: application/json
|
|
|
|
{
|
|
"sync_types": ["StateSync", "HealthSync"]
|
|
}
|
|
```
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"status": "sync_triggered",
|
|
"sync_types": ["StateSync", "HealthSync"],
|
|
"timestamp": 1703001600
|
|
}
|
|
```
|
|
|
|
#### 7. Logs
|
|
```http
|
|
GET /logs?level=info&limit=100
|
|
```
|
|
|
|
**Paramètres :**
|
|
- `level` : debug, info, warn, error
|
|
- `limit` : nombre de lignes (défaut: 100)
|
|
|
|
**Réponse :**
|
|
```json
|
|
{
|
|
"logs": [
|
|
{
|
|
"timestamp": "2024-12-19T10:00:00Z",
|
|
"level": "info",
|
|
"message": "Relay started successfully"
|
|
},
|
|
{
|
|
"timestamp": "2024-12-19T10:00:30Z",
|
|
"level": "info",
|
|
"message": "Sync completed"
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
## Codes d'Erreur
|
|
|
|
### WebSocket
|
|
- `1000` : Fermeture normale
|
|
- `1001` : Client part
|
|
- `1002` : Erreur de protocole
|
|
- `1003` : Type de données non supporté
|
|
- `1006` : Connexion fermée anormalement
|
|
- `1011` : Erreur serveur
|
|
|
|
### HTTP
|
|
- `200` : Succès
|
|
- `400` : Requête invalide
|
|
- `404` : Endpoint non trouvé
|
|
- `500` : Erreur serveur interne
|
|
- `503` : Service indisponible
|
|
|
|
## Exemples d'Utilisation
|
|
|
|
### Client JavaScript
|
|
```javascript
|
|
class SdkRelayClient {
|
|
constructor(url) {
|
|
this.ws = new WebSocket(url);
|
|
this.setupEventHandlers();
|
|
}
|
|
|
|
setupEventHandlers() {
|
|
this.ws.onopen = () => this.onConnect();
|
|
this.ws.onmessage = (event) => this.onMessage(event);
|
|
this.ws.onerror = (error) => this.onError(error);
|
|
this.ws.onclose = (event) => this.onClose(event);
|
|
}
|
|
|
|
onConnect() {
|
|
console.log('Connecté à sdk_relay');
|
|
this.sendHandshake();
|
|
}
|
|
|
|
sendHandshake() {
|
|
const handshake = {
|
|
type: 'handshake',
|
|
client_id: 'js-client',
|
|
version: '1.0.0',
|
|
capabilities: ['sync', 'notifications']
|
|
};
|
|
this.ws.send(JSON.stringify(handshake));
|
|
}
|
|
|
|
onMessage(event) {
|
|
const message = JSON.parse(event.data);
|
|
console.log('Message reçu:', message);
|
|
}
|
|
|
|
onError(error) {
|
|
console.error('Erreur WebSocket:', error);
|
|
}
|
|
|
|
onClose(event) {
|
|
console.log('Connexion fermée:', event.code, event.reason);
|
|
}
|
|
}
|
|
|
|
// Utilisation
|
|
const client = new SdkRelayClient('ws://localhost:8090');
|
|
```
|
|
|
|
### Client Python
|
|
```python
|
|
import asyncio
|
|
import websockets
|
|
import json
|
|
|
|
class SdkRelayClient:
|
|
def __init__(self, url):
|
|
self.url = url
|
|
self.websocket = None
|
|
|
|
async def connect(self):
|
|
self.websocket = await websockets.connect(self.url)
|
|
await self.send_handshake()
|
|
|
|
async def send_handshake(self):
|
|
handshake = {
|
|
"type": "handshake",
|
|
"client_id": "python-client",
|
|
"version": "1.0.0",
|
|
"capabilities": ["sync", "notifications"]
|
|
}
|
|
await self.websocket.send(json.dumps(handshake))
|
|
|
|
async def listen(self):
|
|
async for message in self.websocket:
|
|
data = json.loads(message)
|
|
print(f"Message reçu: {data}")
|
|
|
|
async def close(self):
|
|
if self.websocket:
|
|
await self.websocket.close()
|
|
|
|
# Utilisation
|
|
async def main():
|
|
client = SdkRelayClient('ws://localhost:8090')
|
|
await client.connect()
|
|
await client.listen()
|
|
|
|
asyncio.run(main())
|
|
```
|
|
|
|
### Client cURL
|
|
```bash
|
|
# Vérifier la santé
|
|
curl http://localhost:8091/health
|
|
|
|
# Obtenir les métriques
|
|
curl http://localhost:8091/metrics
|
|
|
|
# Obtenir la configuration
|
|
curl http://localhost:8091/config
|
|
|
|
# Forcer la synchronisation
|
|
curl -X POST http://localhost:8091/sync/force \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"sync_types": ["StateSync"]}'
|
|
```
|
|
|
|
## Limites et Quotas
|
|
|
|
### WebSocket
|
|
- **Connexions simultanées** : 1000 par défaut
|
|
- **Taille des messages** : 1MB maximum
|
|
- **Heartbeat** : 30 secondes
|
|
- **Timeout de connexion** : 60 secondes
|
|
|
|
### HTTP
|
|
- **Taux limite** : 1000 requêtes/minute
|
|
- **Taille des requêtes** : 10MB maximum
|
|
- **Timeout** : 30 secondes
|
|
- **Connexions simultanées** : 100
|
|
|
|
## Sécurité
|
|
|
|
### Authentification
|
|
- **WebSocket** : Authentification optionnelle via handshake
|
|
- **HTTP** : Authentification basique (à configurer)
|
|
|
|
### Validation
|
|
- Validation JSON des messages
|
|
- Rate limiting
|
|
- Protection contre les attaques DoS
|
|
|
|
### Chiffrement
|
|
- **WebSocket** : WSS (WebSocket Secure) recommandé
|
|
- **HTTP** : HTTPS recommandé
|
|
|
|
## Monitoring
|
|
|
|
### Métriques Clés
|
|
- **Latence** : Temps de réponse des APIs
|
|
- **Débit** : Messages par seconde
|
|
- **Erreurs** : Taux d'erreur
|
|
- **Connexions** : Nombre de connexions actives
|
|
|
|
### Alertes
|
|
- Service indisponible
|
|
- Latence élevée (> 1s)
|
|
- Taux d'erreur élevé (> 5%)
|
|
- Mémoire/CPU élevés
|
|
|
|
---
|
|
|
|
**Cette API permet une intégration complète avec sdk_relay pour les clients WebSocket et HTTP.** 🚀
|