mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 10:53:24 +00:00
docs: Update README with semver and privacy features
This commit is contained in:
837
README.md
837
README.md
@@ -2,9 +2,9 @@
|
||||
|
||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
||||
|
||||
🌐 **WebRTC with durable connections and automatic reconnection**
|
||||
🌐 **Simple, high-level WebRTC peer-to-peer connections**
|
||||
|
||||
TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections that survive network interruptions with automatic reconnection and message queuing.
|
||||
TypeScript/JavaScript client for Rondevu, providing easy-to-use WebRTC connections with automatic signaling, username-based discovery, and built-in reconnection support.
|
||||
|
||||
**Related repositories:**
|
||||
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
||||
@@ -15,14 +15,16 @@ TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections t
|
||||
|
||||
## Features
|
||||
|
||||
- **Durable Connections**: Automatic reconnection on network drops
|
||||
- **Message Queuing**: Messages sent during disconnections are queued and flushed on reconnect
|
||||
- **Durable Channels**: RTCDataChannel wrappers that survive connection drops
|
||||
- **TTL Auto-Refresh**: Services automatically republish before expiration
|
||||
- **Username Claiming**: Cryptographic ownership with Ed25519 signatures
|
||||
- **Service Publishing**: Package-style naming (com.example.chat@1.0.0)
|
||||
- **High-Level Wrappers**: ServiceHost and ServiceClient eliminate WebRTC boilerplate
|
||||
- **Username-Based Discovery**: Connect to peers by username, not complex offer/answer exchange
|
||||
- **Semver-Compatible Matching**: Requesting chat@1.0.0 matches any compatible 1.x.x version
|
||||
- **Privacy-First Design**: Services are hidden by default - no enumeration possible
|
||||
- **Automatic Reconnection**: Built-in retry logic with exponential backoff
|
||||
- **Message Queuing**: Messages sent while disconnected are queued and flushed on reconnect
|
||||
- **Cryptographic Username Claiming**: Secure ownership with Ed25519 signatures
|
||||
- **Service Publishing**: Package-style naming (chat.app@1.0.0) with multiple simultaneous offers
|
||||
- **TypeScript**: Full type safety and autocomplete
|
||||
- **Configurable**: All timeouts, retry limits, and queue sizes are configurable
|
||||
- **Configurable Polling**: Exponential backoff with jitter to reduce server load
|
||||
|
||||
## Install
|
||||
|
||||
@@ -32,588 +34,400 @@ npm install @xtr-dev/rondevu-client
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Publishing a Service (Alice)
|
||||
### Hosting a Service (Alice)
|
||||
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
import { RondevuService, ServiceHost } from '@xtr-dev/rondevu-client'
|
||||
|
||||
// Initialize client and register
|
||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
||||
await client.register();
|
||||
// Step 1: Create and initialize service
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'alice'
|
||||
})
|
||||
|
||||
// Step 1: Claim username (one-time)
|
||||
const claim = await client.usernames.claimUsername('alice');
|
||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
||||
await service.initialize() // Generates keypair
|
||||
await service.claimUsername() // Claims username with signature
|
||||
|
||||
// Step 2: Expose service with handler
|
||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
||||
// Step 2: Create ServiceHost
|
||||
const host = new ServiceHost({
|
||||
service: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
maxPeers: 5, // Accept up to 5 connections
|
||||
ttl: 300000 // 5 minutes
|
||||
})
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
poolSize: 10, // Handle 10 concurrent connections
|
||||
handler: (channel, connectionId) => {
|
||||
console.log(`📡 New connection: ${connectionId}`);
|
||||
// Step 3: Listen for incoming connections
|
||||
host.events.on('connection', (connection) => {
|
||||
console.log('✅ New connection!')
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('📥 Received:', data);
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
connection.events.on('message', (msg) => {
|
||||
console.log('📨 Received:', msg)
|
||||
connection.sendMessage('Hello from Alice!')
|
||||
})
|
||||
|
||||
channel.on('close', () => {
|
||||
console.log(`👋 Connection ${connectionId} closed`);
|
||||
});
|
||||
}
|
||||
});
|
||||
connection.events.on('state-change', (state) => {
|
||||
console.log('Connection state:', state)
|
||||
})
|
||||
})
|
||||
|
||||
// Start the service
|
||||
const info = await service.start();
|
||||
console.log(`Service published with UUID: ${info.uuid}`);
|
||||
console.log('Waiting for connections...');
|
||||
host.events.on('error', (error) => {
|
||||
console.error('Host error:', error)
|
||||
})
|
||||
|
||||
// Later: stop the service
|
||||
await service.stop();
|
||||
// Step 4: Start hosting
|
||||
await host.start()
|
||||
console.log('Service is now live! Others can connect to @alice')
|
||||
|
||||
// Later: stop hosting
|
||||
host.dispose()
|
||||
```
|
||||
|
||||
### Connecting to a Service (Bob)
|
||||
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
import { RondevuService, ServiceClient } from '@xtr-dev/rondevu-client'
|
||||
|
||||
// Initialize client and register
|
||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
||||
await client.register();
|
||||
// Step 1: Create and initialize service
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'bob'
|
||||
})
|
||||
|
||||
// Connect to Alice's service
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
await service.initialize()
|
||||
await service.claimUsername()
|
||||
|
||||
// Create a durable channel
|
||||
const channel = connection.createChannel('main');
|
||||
// Step 2: Create ServiceClient
|
||||
const client = new ServiceClient({
|
||||
username: 'alice', // Connect to Alice
|
||||
serviceFqn: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
autoReconnect: true,
|
||||
maxReconnectAttempts: 5
|
||||
})
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('📥 Received:', data);
|
||||
});
|
||||
// Step 3: Listen for connection events
|
||||
client.events.on('connected', (connection) => {
|
||||
console.log('✅ Connected to Alice!')
|
||||
|
||||
channel.on('open', () => {
|
||||
console.log('✅ Channel open');
|
||||
channel.send('Hello Alice!');
|
||||
});
|
||||
connection.events.on('message', (msg) => {
|
||||
console.log('📨 Received:', msg)
|
||||
})
|
||||
|
||||
// Listen for connection events
|
||||
connection.on('connected', () => {
|
||||
console.log('🎉 Connected to Alice');
|
||||
});
|
||||
// Send a message
|
||||
connection.sendMessage('Hello from Bob!')
|
||||
})
|
||||
|
||||
connection.on('reconnecting', (attempt, max, delay) => {
|
||||
console.log(`🔄 Reconnecting... (${attempt}/${max}, retry in ${delay}ms)`);
|
||||
});
|
||||
client.events.on('disconnected', () => {
|
||||
console.log('🔌 Disconnected')
|
||||
})
|
||||
|
||||
connection.on('disconnected', () => {
|
||||
console.log('🔌 Disconnected');
|
||||
});
|
||||
client.events.on('reconnecting', ({ attempt, maxAttempts }) => {
|
||||
console.log(`🔄 Reconnecting (${attempt}/${maxAttempts})...`)
|
||||
})
|
||||
|
||||
connection.on('failed', (error) => {
|
||||
console.error('❌ Connection failed permanently:', error);
|
||||
});
|
||||
client.events.on('error', (error) => {
|
||||
console.error('❌ Error:', error)
|
||||
})
|
||||
|
||||
// Establish the connection
|
||||
await connection.connect();
|
||||
// Step 4: Connect
|
||||
await client.connect()
|
||||
|
||||
// Messages sent during disconnection are automatically queued
|
||||
channel.send('This will be queued if disconnected');
|
||||
|
||||
// Later: close the connection
|
||||
await connection.close();
|
||||
// Later: disconnect
|
||||
client.dispose()
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### DurableConnection
|
||||
### RondevuService
|
||||
|
||||
Manages WebRTC peer lifecycle with automatic reconnection:
|
||||
- Automatically reconnects when connection drops
|
||||
- Exponential backoff with jitter (1s → 2s → 4s → 8s → ... max 30s)
|
||||
- Configurable max retry attempts (default: 10)
|
||||
- Manages multiple DurableChannel instances
|
||||
Handles authentication and username management:
|
||||
- Generates Ed25519 keypair for signing
|
||||
- Claims usernames with cryptographic proof
|
||||
- Provides API client for signaling server
|
||||
|
||||
### DurableChannel
|
||||
### ServiceHost
|
||||
|
||||
Wraps RTCDataChannel with message queuing:
|
||||
- Queues messages during disconnection
|
||||
- Flushes queue on reconnection
|
||||
- Configurable queue size and message age limits
|
||||
- RTCDataChannel-compatible API with event emitters
|
||||
High-level wrapper for hosting a WebRTC service:
|
||||
- Automatically creates and publishes offers
|
||||
- Handles incoming connections
|
||||
- Manages ICE candidate exchange
|
||||
- Supports multiple simultaneous peers
|
||||
|
||||
### DurableService
|
||||
### ServiceClient
|
||||
|
||||
Server-side service with TTL auto-refresh:
|
||||
- Automatically republishes service before TTL expires
|
||||
- Creates DurableConnection for each incoming peer
|
||||
- Manages connection pool for multiple simultaneous connections
|
||||
High-level wrapper for connecting to services:
|
||||
- Discovers services by username
|
||||
- Handles offer/answer exchange automatically
|
||||
- Built-in auto-reconnection with exponential backoff
|
||||
- Event-driven API
|
||||
|
||||
### RTCDurableConnection
|
||||
|
||||
Low-level connection wrapper (used internally):
|
||||
- Manages WebRTC PeerConnection lifecycle
|
||||
- Handles ICE candidate polling
|
||||
- Provides message queue for reliability
|
||||
- State management and events
|
||||
|
||||
## API Reference
|
||||
|
||||
### Main Client
|
||||
### RondevuService
|
||||
|
||||
```typescript
|
||||
const client = new Rondevu({
|
||||
baseUrl: 'https://api.ronde.vu', // optional, default shown
|
||||
credentials?: { peerId, secret }, // optional, skip registration
|
||||
fetch?: customFetch, // optional, for Node.js < 18
|
||||
RTCPeerConnection?: RTCPeerConnection, // optional, for Node.js
|
||||
RTCSessionDescription?: RTCSessionDescription,
|
||||
RTCIceCandidate?: RTCIceCandidate
|
||||
});
|
||||
const service = new RondevuService({
|
||||
apiUrl: string, // Signaling server URL
|
||||
username: string, // Your username
|
||||
keypair?: Keypair // Optional: reuse existing keypair
|
||||
})
|
||||
|
||||
// Register and get credentials
|
||||
const creds = await client.register();
|
||||
// { peerId: '...', secret: '...' }
|
||||
// Initialize service (generates keypair if not provided)
|
||||
await service.initialize(): Promise<void>
|
||||
|
||||
// Check if authenticated
|
||||
client.isAuthenticated(); // boolean
|
||||
// Claim username with cryptographic signature
|
||||
await service.claimUsername(): Promise<void>
|
||||
|
||||
// Get current credentials
|
||||
client.getCredentials(); // { peerId, secret } | undefined
|
||||
// Check if username is claimed
|
||||
service.isUsernameClaimed(): boolean
|
||||
|
||||
// Get current username
|
||||
service.getUsername(): string
|
||||
|
||||
// Get keypair
|
||||
service.getKeypair(): Keypair
|
||||
|
||||
// Get API client
|
||||
service.getAPI(): RondevuAPI
|
||||
```
|
||||
|
||||
### Username API
|
||||
### ServiceHost
|
||||
|
||||
```typescript
|
||||
// Check username availability
|
||||
const check = await client.usernames.checkUsername('alice');
|
||||
// { available: true } or { available: false, expiresAt: number, publicKey: string }
|
||||
const host = new ServiceHost({
|
||||
service: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||
rondevuService: RondevuService,
|
||||
maxPeers?: number, // Default: 5
|
||||
ttl?: number, // Default: 300000 (5 minutes)
|
||||
isPublic?: boolean, // Default: true
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
})
|
||||
|
||||
// Claim username with new keypair
|
||||
const claim = await client.usernames.claimUsername('alice');
|
||||
// { username, publicKey, privateKey, claimedAt, expiresAt }
|
||||
// Start hosting
|
||||
await host.start(): Promise<void>
|
||||
|
||||
// Save keypair to localStorage
|
||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
||||
// Stop hosting and cleanup
|
||||
host.dispose(): void
|
||||
|
||||
// Load keypair from localStorage
|
||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
||||
// { publicKey, privateKey } | null
|
||||
// Get all active connections
|
||||
host.getConnections(): RTCDurableConnection[]
|
||||
|
||||
// Events
|
||||
host.events.on('connection', (conn: RTCDurableConnection) => {})
|
||||
host.events.on('error', (error: Error) => {})
|
||||
```
|
||||
|
||||
**Username Rules:**
|
||||
- Format: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
|
||||
- Length: 3-32 characters
|
||||
- Pattern: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
|
||||
- Validity: 365 days from claim/last use
|
||||
- Ownership: Secured by Ed25519 public key
|
||||
|
||||
### Durable Service API
|
||||
### ServiceClient
|
||||
|
||||
```typescript
|
||||
// Expose a durable service
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
const client = new ServiceClient({
|
||||
username: string, // Host username to connect to
|
||||
serviceFqn: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||
rondevuService: RondevuService,
|
||||
autoReconnect?: boolean, // Default: true
|
||||
maxReconnectAttempts?: number, // Default: 5
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
})
|
||||
|
||||
// Service options
|
||||
isPublic: true, // optional, default: false
|
||||
metadata: { version: '1.0' }, // optional
|
||||
ttl: 300000, // optional, default: 5 minutes
|
||||
ttlRefreshMargin: 0.2, // optional, refresh at 80% of TTL
|
||||
// Connect to service
|
||||
await client.connect(): Promise<RTCDurableConnection>
|
||||
|
||||
// Connection pooling
|
||||
poolSize: 10, // optional, default: 1
|
||||
pollingInterval: 2000, // optional, default: 2000ms
|
||||
// Disconnect and cleanup
|
||||
client.dispose(): void
|
||||
|
||||
// Connection options (applied to incoming connections)
|
||||
maxReconnectAttempts: 10, // optional, default: 10
|
||||
reconnectBackoffBase: 1000, // optional, default: 1000ms
|
||||
reconnectBackoffMax: 30000, // optional, default: 30000ms
|
||||
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
|
||||
connectionTimeout: 30000, // optional, default: 30000ms
|
||||
// Get current connection
|
||||
client.getConnection(): RTCDurableConnection | null
|
||||
|
||||
// Message queuing
|
||||
maxQueueSize: 1000, // optional, default: 1000
|
||||
maxMessageAge: 60000, // optional, default: 60000ms (1 minute)
|
||||
|
||||
// WebRTC configuration
|
||||
rtcConfig: {
|
||||
iceServers: [
|
||||
{ urls: 'stun:stun.l.google.com:19302' }
|
||||
]
|
||||
},
|
||||
|
||||
// Connection handler
|
||||
handler: (channel, connectionId) => {
|
||||
// Handle incoming connection
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Start the service
|
||||
const info = await service.start();
|
||||
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 }
|
||||
|
||||
// Get active connections
|
||||
const connections = service.getActiveConnections();
|
||||
// ['conn-123', 'conn-456']
|
||||
|
||||
// Get service info
|
||||
const serviceInfo = service.getServiceInfo();
|
||||
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 } | null
|
||||
|
||||
// Stop the service
|
||||
await service.stop();
|
||||
// Events
|
||||
client.events.on('connected', (conn: RTCDurableConnection) => {})
|
||||
client.events.on('disconnected', () => {})
|
||||
client.events.on('reconnecting', (info: { attempt: number, maxAttempts: number }) => {})
|
||||
client.events.on('error', (error: Error) => {})
|
||||
```
|
||||
|
||||
**Service Events:**
|
||||
### RTCDurableConnection
|
||||
|
||||
```typescript
|
||||
service.on('published', (serviceId, uuid) => {
|
||||
console.log(`Service published: ${uuid}`);
|
||||
});
|
||||
// Connection state
|
||||
connection.state: 'connected' | 'connecting' | 'disconnected'
|
||||
|
||||
service.on('connection', (connectionId) => {
|
||||
console.log(`New connection: ${connectionId}`);
|
||||
});
|
||||
// Send message (returns true if sent, false if queued)
|
||||
await connection.sendMessage(message: string): Promise<boolean>
|
||||
|
||||
service.on('disconnection', (connectionId) => {
|
||||
console.log(`Connection closed: ${connectionId}`);
|
||||
});
|
||||
// Queue message for sending when connected
|
||||
await connection.queueMessage(message: string, options?: QueueMessageOptions): Promise<void>
|
||||
|
||||
service.on('ttl-refreshed', (expiresAt) => {
|
||||
console.log(`TTL refreshed, expires at: ${new Date(expiresAt)}`);
|
||||
});
|
||||
// Disconnect
|
||||
connection.disconnect(): void
|
||||
|
||||
service.on('error', (error, context) => {
|
||||
console.error(`Service error (${context}):`, error);
|
||||
});
|
||||
|
||||
service.on('closed', () => {
|
||||
console.log('Service stopped');
|
||||
});
|
||||
// Events
|
||||
connection.events.on('message', (msg: string) => {})
|
||||
connection.events.on('state-change', (state: ConnectionStates) => {})
|
||||
```
|
||||
|
||||
### Durable Connection API
|
||||
## Configuration
|
||||
|
||||
### Polling Configuration
|
||||
|
||||
The signaling uses configurable polling with exponential backoff:
|
||||
|
||||
```typescript
|
||||
// Connect by username and service FQN
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
// Connection options
|
||||
maxReconnectAttempts: 10, // optional, default: 10
|
||||
reconnectBackoffBase: 1000, // optional, default: 1000ms
|
||||
reconnectBackoffMax: 30000, // optional, default: 30000ms
|
||||
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
|
||||
connectionTimeout: 30000, // optional, default: 30000ms
|
||||
|
||||
// Message queuing
|
||||
maxQueueSize: 1000, // optional, default: 1000
|
||||
maxMessageAge: 60000, // optional, default: 60000ms
|
||||
|
||||
// WebRTC configuration
|
||||
rtcConfig: {
|
||||
iceServers: [
|
||||
{ urls: 'stun:stun.l.google.com:19302' }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Connect by UUID
|
||||
const connection2 = await client.connectByUuid('service-uuid-here', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
|
||||
// Create channels before connecting
|
||||
const channel = connection.createChannel('main');
|
||||
const fileChannel = connection.createChannel('files', {
|
||||
ordered: false,
|
||||
maxRetransmits: 3
|
||||
});
|
||||
|
||||
// Get existing channel
|
||||
const existingChannel = connection.getChannel('main');
|
||||
|
||||
// Check connection state
|
||||
const state = connection.getState();
|
||||
// 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'failed' | 'closed'
|
||||
|
||||
const isConnected = connection.isConnected();
|
||||
|
||||
// Connect
|
||||
await connection.connect();
|
||||
|
||||
// Close connection
|
||||
await connection.close();
|
||||
```
|
||||
|
||||
**Connection Events:**
|
||||
```typescript
|
||||
connection.on('state', (newState, previousState) => {
|
||||
console.log(`State: ${previousState} → ${newState}`);
|
||||
});
|
||||
|
||||
connection.on('connected', () => {
|
||||
console.log('Connected');
|
||||
});
|
||||
|
||||
connection.on('reconnecting', (attempt, maxAttempts, delay) => {
|
||||
console.log(`Reconnecting (${attempt}/${maxAttempts}) in ${delay}ms`);
|
||||
});
|
||||
|
||||
connection.on('disconnected', () => {
|
||||
console.log('Disconnected');
|
||||
});
|
||||
|
||||
connection.on('failed', (error, permanent) => {
|
||||
console.error('Connection failed:', error, 'Permanent:', permanent);
|
||||
});
|
||||
|
||||
connection.on('closed', () => {
|
||||
console.log('Connection closed');
|
||||
});
|
||||
```
|
||||
|
||||
### Durable Channel API
|
||||
|
||||
```typescript
|
||||
const channel = connection.createChannel('chat', {
|
||||
ordered: true, // optional, default: true
|
||||
maxRetransmits: undefined // optional, for unordered channels
|
||||
});
|
||||
|
||||
// Send data (queued if disconnected)
|
||||
channel.send('Hello!');
|
||||
channel.send(new ArrayBuffer(1024));
|
||||
channel.send(new Blob(['data']));
|
||||
|
||||
// Check state
|
||||
const state = channel.readyState;
|
||||
// 'connecting' | 'open' | 'closing' | 'closed'
|
||||
|
||||
// Get buffered amount
|
||||
const buffered = channel.bufferedAmount;
|
||||
|
||||
// Set buffered amount low threshold
|
||||
channel.bufferedAmountLowThreshold = 16 * 1024; // 16KB
|
||||
|
||||
// Get queue size (for debugging)
|
||||
const queueSize = channel.getQueueSize();
|
||||
|
||||
// Close channel
|
||||
channel.close();
|
||||
```
|
||||
|
||||
**Channel Events:**
|
||||
```typescript
|
||||
channel.on('open', () => {
|
||||
console.log('Channel open');
|
||||
});
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
});
|
||||
|
||||
channel.on('error', (error) => {
|
||||
console.error('Channel error:', error);
|
||||
});
|
||||
|
||||
channel.on('close', () => {
|
||||
console.log('Channel closed');
|
||||
});
|
||||
|
||||
channel.on('bufferedAmountLow', () => {
|
||||
console.log('Buffer drained, safe to send more');
|
||||
});
|
||||
|
||||
channel.on('queueOverflow', (droppedCount) => {
|
||||
console.warn(`Queue overflow: ${droppedCount} messages dropped`);
|
||||
});
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Connection Configuration
|
||||
|
||||
```typescript
|
||||
interface DurableConnectionConfig {
|
||||
maxReconnectAttempts?: number; // default: 10
|
||||
reconnectBackoffBase?: number; // default: 1000 (1 second)
|
||||
reconnectBackoffMax?: number; // default: 30000 (30 seconds)
|
||||
reconnectJitter?: number; // default: 0.2 (±20%)
|
||||
connectionTimeout?: number; // default: 30000 (30 seconds)
|
||||
maxQueueSize?: number; // default: 1000 messages
|
||||
maxMessageAge?: number; // default: 60000 (1 minute)
|
||||
rtcConfig?: RTCConfiguration;
|
||||
// Default polling config
|
||||
{
|
||||
initialInterval: 500, // Start at 500ms
|
||||
maxInterval: 5000, // Max 5 seconds
|
||||
backoffMultiplier: 1.5, // Increase by 1.5x each time
|
||||
maxRetries: 50, // Max 50 attempts
|
||||
jitter: true // Add random 0-100ms to prevent thundering herd
|
||||
}
|
||||
```
|
||||
|
||||
### Service Configuration
|
||||
This is handled automatically - no configuration needed.
|
||||
|
||||
### WebRTC Configuration
|
||||
|
||||
Provide custom STUN/TURN servers:
|
||||
|
||||
```typescript
|
||||
interface DurableServiceConfig extends DurableConnectionConfig {
|
||||
username: string;
|
||||
privateKey: string;
|
||||
serviceFqn: string;
|
||||
isPublic?: boolean; // default: false
|
||||
metadata?: Record<string, any>;
|
||||
ttl?: number; // default: 300000 (5 minutes)
|
||||
ttlRefreshMargin?: number; // default: 0.2 (refresh at 80%)
|
||||
poolSize?: number; // default: 1
|
||||
pollingInterval?: number; // default: 2000 (2 seconds)
|
||||
}
|
||||
const host = new ServiceHost({
|
||||
service: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
rtcConfiguration: {
|
||||
iceServers: [
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
{
|
||||
urls: 'turn:turn.example.com:3478',
|
||||
username: 'user',
|
||||
credential: 'pass'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Username Rules
|
||||
|
||||
- **Format**: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
|
||||
- **Length**: 3-32 characters
|
||||
- **Pattern**: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
|
||||
- **Validity**: 365 days from claim/last use
|
||||
- **Ownership**: Secured by Ed25519 public key signature
|
||||
|
||||
## Examples
|
||||
|
||||
### Chat Application
|
||||
|
||||
```typescript
|
||||
// Server
|
||||
const client = new Rondevu();
|
||||
await client.register();
|
||||
See [demo/demo.js](./demo/demo.js) for a complete working example.
|
||||
|
||||
const claim = await client.usernames.claimUsername('alice');
|
||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
poolSize: 50, // Handle 50 concurrent users
|
||||
handler: (channel, connectionId) => {
|
||||
console.log(`User ${connectionId} joined`);
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log(`[${connectionId}]: ${data}`);
|
||||
// Broadcast to all users (implement your broadcast logic)
|
||||
});
|
||||
|
||||
channel.on('close', () => {
|
||||
console.log(`User ${connectionId} left`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
|
||||
// Client
|
||||
const client2 = new Rondevu();
|
||||
await client2.register();
|
||||
|
||||
const connection = await client2.connect('alice', 'chat@1.0.0');
|
||||
const channel = connection.createChannel('chat');
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Message:', data);
|
||||
});
|
||||
|
||||
await connection.connect();
|
||||
channel.send('Hello everyone!');
|
||||
```
|
||||
|
||||
### File Transfer with Progress
|
||||
### Persistent Keypair
|
||||
|
||||
```typescript
|
||||
// Server
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'files@1.0.0',
|
||||
handler: (channel, connectionId) => {
|
||||
channel.on('message', async (data) => {
|
||||
const request = JSON.parse(data);
|
||||
// Save keypair to localStorage
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'alice'
|
||||
})
|
||||
|
||||
if (request.action === 'download') {
|
||||
const file = await fs.readFile(request.path);
|
||||
const chunkSize = 16 * 1024; // 16KB chunks
|
||||
await service.initialize()
|
||||
await service.claimUsername()
|
||||
|
||||
for (let i = 0; i < file.byteLength; i += chunkSize) {
|
||||
const chunk = file.slice(i, i + chunkSize);
|
||||
channel.send(chunk);
|
||||
// Save for later
|
||||
localStorage.setItem('rondevu-keypair', JSON.stringify(service.getKeypair()))
|
||||
localStorage.setItem('rondevu-username', service.getUsername())
|
||||
|
||||
// Wait for buffer to drain if needed
|
||||
while (channel.bufferedAmount > 16 * 1024 * 1024) { // 16MB
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
// Load on next session
|
||||
const savedKeypair = JSON.parse(localStorage.getItem('rondevu-keypair'))
|
||||
const savedUsername = localStorage.getItem('rondevu-username')
|
||||
|
||||
channel.send(JSON.stringify({ done: true }));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const service2 = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: savedUsername,
|
||||
keypair: savedKeypair
|
||||
})
|
||||
|
||||
await service.start();
|
||||
|
||||
// Client
|
||||
const connection = await client.connect('alice', 'files@1.0.0');
|
||||
const channel = connection.createChannel('files');
|
||||
|
||||
const chunks = [];
|
||||
channel.on('message', (data) => {
|
||||
if (typeof data === 'string') {
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.done) {
|
||||
const blob = new Blob(chunks);
|
||||
console.log('Download complete:', blob.size, 'bytes');
|
||||
}
|
||||
} else {
|
||||
chunks.push(data);
|
||||
console.log('Progress:', chunks.length * 16 * 1024, 'bytes');
|
||||
}
|
||||
});
|
||||
|
||||
await connection.connect();
|
||||
channel.send(JSON.stringify({ action: 'download', path: '/file.zip' }));
|
||||
await service2.initialize() // Reuses keypair
|
||||
```
|
||||
|
||||
## Platform-Specific Setup
|
||||
### Message Queue Example
|
||||
|
||||
```typescript
|
||||
// Messages are automatically queued if not connected yet
|
||||
client.events.on('connected', (connection) => {
|
||||
// Send immediately
|
||||
connection.sendMessage('Hello!')
|
||||
})
|
||||
|
||||
// Or queue for later
|
||||
await client.connect()
|
||||
const conn = client.getConnection()
|
||||
await conn.queueMessage('This will be sent when connected', {
|
||||
expiresAt: Date.now() + 60000 // Expire after 1 minute
|
||||
})
|
||||
```
|
||||
|
||||
## Migration from v0.9.x
|
||||
|
||||
v0.11.0+ introduces high-level wrappers, RESTful API changes, and semver-compatible discovery:
|
||||
|
||||
**API Changes:**
|
||||
- Server endpoints restructured (`/usernames/*` → `/users/*`)
|
||||
- Added `ServiceHost` and `ServiceClient` wrappers
|
||||
- Message queue fully implemented
|
||||
- Configurable polling with exponential backoff
|
||||
- Removed deprecated `cleanup()` methods (use `dispose()`)
|
||||
- **v0.11.0+**: Services use `offers` array instead of single `sdp`
|
||||
- **v0.11.0+**: Semver-compatible service discovery (chat@1.0.0 matches 1.x.x)
|
||||
- **v0.11.0+**: All services are hidden - no listing endpoint
|
||||
- **v0.11.0+**: Services support multiple simultaneous offers for connection pooling
|
||||
|
||||
**Migration Guide:**
|
||||
|
||||
```typescript
|
||||
// Before (v0.9.x) - Manual WebRTC setup
|
||||
const signaler = new RondevuSignaler(service, 'chat@1.0.0')
|
||||
const context = new WebRTCContext()
|
||||
const pc = context.createPeerConnection()
|
||||
// ... 50+ lines of boilerplate
|
||||
|
||||
// After (v0.11.0) - ServiceHost wrapper
|
||||
const host = new ServiceHost({
|
||||
service: 'chat@1.0.0',
|
||||
rondevuService: service
|
||||
})
|
||||
await host.start()
|
||||
// Done!
|
||||
```
|
||||
|
||||
## Platform Support
|
||||
|
||||
### Modern Browsers
|
||||
Works out of the box - no additional setup needed.
|
||||
|
||||
### Node.js 18+
|
||||
Native fetch is available, but you need WebRTC polyfills:
|
||||
Native fetch is available, but WebRTC requires polyfills:
|
||||
|
||||
```bash
|
||||
npm install wrtc
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
||||
import { WebRTCContext } from '@xtr-dev/rondevu-client'
|
||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc'
|
||||
|
||||
const client = new Rondevu({
|
||||
baseUrl: 'https://api.ronde.vu',
|
||||
RTCPeerConnection,
|
||||
RTCSessionDescription,
|
||||
RTCIceCandidate
|
||||
});
|
||||
```
|
||||
|
||||
### Node.js < 18
|
||||
Install both fetch and WebRTC polyfills:
|
||||
|
||||
```bash
|
||||
npm install node-fetch wrtc
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
import fetch from 'node-fetch';
|
||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
||||
|
||||
const client = new Rondevu({
|
||||
baseUrl: 'https://api.ronde.vu',
|
||||
fetch: fetch as any,
|
||||
RTCPeerConnection,
|
||||
RTCSessionDescription,
|
||||
RTCIceCandidate
|
||||
});
|
||||
// Configure WebRTC context
|
||||
const context = new WebRTCContext({
|
||||
RTCPeerConnection,
|
||||
RTCSessionDescription,
|
||||
RTCIceCandidate
|
||||
} as any)
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
@@ -622,38 +436,23 @@ All types are exported:
|
||||
|
||||
```typescript
|
||||
import type {
|
||||
// Client types
|
||||
Credentials,
|
||||
RondevuOptions,
|
||||
|
||||
// Username types
|
||||
UsernameCheckResult,
|
||||
UsernameClaimResult,
|
||||
|
||||
// Durable connection types
|
||||
DurableConnectionState,
|
||||
DurableChannelState,
|
||||
DurableConnectionConfig,
|
||||
DurableChannelConfig,
|
||||
DurableServiceConfig,
|
||||
QueuedMessage,
|
||||
DurableConnectionEvents,
|
||||
DurableChannelEvents,
|
||||
DurableServiceEvents,
|
||||
ConnectionInfo,
|
||||
ServiceInfo
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
RondevuServiceOptions,
|
||||
ServiceHostOptions,
|
||||
ServiceHostEvents,
|
||||
ServiceClientOptions,
|
||||
ServiceClientEvents,
|
||||
ConnectionInterface,
|
||||
ConnectionEvents,
|
||||
ConnectionStates,
|
||||
Message,
|
||||
QueueMessageOptions,
|
||||
Signaler,
|
||||
PollingConfig,
|
||||
Credentials,
|
||||
Keypair
|
||||
} from '@xtr-dev/rondevu-client'
|
||||
```
|
||||
|
||||
## Migration from v0.8.x
|
||||
|
||||
v0.9.0 is a **breaking change** that replaces the low-level APIs with high-level durable connections. See [MIGRATION.md](./MIGRATION.md) for detailed migration guide.
|
||||
|
||||
**Key Changes:**
|
||||
- ❌ Removed: `client.services.*`, `client.discovery.*`, `client.createPeer()` (low-level APIs)
|
||||
- ✅ Added: `client.exposeService()`, `client.connect()`, `client.connectByUuid()` (durable APIs)
|
||||
- ✅ Changed: Focus on durable connections with automatic reconnection and message queuing
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
Reference in New Issue
Block a user