rpcnet 0.1.0

RPC library based on QUIC+TLS encryption
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# API Reference

Quick reference for RpcNet's most commonly used APIs. For complete documentation, see the [API docs](https://docs.rs/rpcnet).

## Core Types

### Server

Creates and manages RPC servers.

```rust
use rpcnet::{Server, ServerConfig};

// Create server
let config = ServerConfig::builder()
    .with_cert_and_key(cert, key)?
    .build();
let mut server = Server::new(config);

// Register services
server.register_service(Arc::new(MyService));

// Bind and run
server.bind("0.0.0.0:8080").await?;
server.run().await?;
```

**Key methods**:
- `new(config)` - Create server with configuration
- `register_service(service)` - Register RPC service handler
- `bind(addr)` - Bind to address
- `enable_cluster(config)` - Enable cluster features
- `run()` - Start server (blocks until shutdown)
- `shutdown()` - Gracefully shut down server

### Client

Connects to RPC servers and makes requests.

```rust
use rpcnet::{Client, ClientConfig};

// Create client
let config = ClientConfig::builder()
    .with_server_cert(cert)?
    .build();

// Connect
let client = MyServiceClient::connect("server.example.com:8080", config).await?;

// Make request
let response = client.my_method(args).await?;
```

**Key methods**:
- `connect(addr, config)` - Connect to server
- Generated methods per RPC trait
- Auto-reconnect on connection loss

## Cluster APIs

### ClusterMembership

Manages node membership via SWIM gossip protocol.

```rust
use rpcnet::cluster::ClusterMembership;

// Create cluster
let config = ClusterConfig::default()
    .with_bind_addr("0.0.0.0:7946".parse()?);
let cluster = ClusterMembership::new(config).await?;

// Join via seed nodes
cluster.join(vec!["seed.example.com:7946".parse()?]).await?;

// Tag node
cluster.set_tag("role", "worker");

// Subscribe to events
let mut events = cluster.subscribe();
while let Some(event) = events.recv().await {
    // Handle cluster events
}
```

**Key methods**:
- `new(config)` - Create cluster membership
- `join(seeds)` - Join cluster via seed nodes
- `leave()` - Gracefully leave cluster
- `set_tag(key, value)` - Set metadata tag
- `get_tag(key)` - Get metadata tag
- `nodes()` - Get all cluster nodes
- `subscribe()` - Subscribe to cluster events
- `local_node_id()` - Get local node ID

### WorkerRegistry

Tracks worker nodes with load balancing.

```rust
use rpcnet::cluster::{WorkerRegistry, LoadBalancingStrategy};

// Create registry
let registry = Arc::new(WorkerRegistry::new(
    cluster,
    LoadBalancingStrategy::LeastConnections
));

// Start monitoring
registry.start().await;

// Select worker
let worker = registry.select_worker(Some("role=worker")).await?;
println!("Selected: {} at {}", worker.label, worker.addr);

// Get all workers
let workers = registry.workers().await;
```

**Key methods**:
- `new(cluster, strategy)` - Create registry
- `start()` - Start monitoring cluster events
- `select_worker(filter)` - Select worker by tag filter
- `workers()` - Get all workers
- `worker_count()` - Get number of workers
- `subscribe()` - Subscribe to registry events

### NodeRegistry

Tracks all cluster nodes.

```rust
use rpcnet::cluster::NodeRegistry;

// Create registry
let registry = Arc::new(NodeRegistry::new(cluster));
registry.start().await;

// Get all nodes
let nodes = registry.nodes().await;

// Filter by tag
let directors = nodes.iter()
    .filter(|n| n.tags.get("role") == Some(&"director".to_string()))
    .collect::<Vec<_>>();
```

**Key methods**:
- `new(cluster)` - Create node registry
- `start()` - Start monitoring cluster
- `nodes()` - Get all nodes
- `node_count()` - Count nodes
- `subscribe()` - Subscribe to events

### ClusterClient

High-level API for calling workers.

```rust
use rpcnet::cluster::{ClusterClient, ClusterClientConfig};

// Create client
let config = ClusterClientConfig::default();
let client = Arc::new(ClusterClient::new(registry, config));

// Call any worker
let result = client.call_worker("compute", request, Some("role=worker")).await?;
```

**Key methods**:
- `new(registry, config)` - Create cluster client
- `call_worker(method, data, filter)` - Call any worker matching filter

## Configuration

### ServerConfig

```rust
use rpcnet::ServerConfig;

let config = ServerConfig::builder()
    .with_cert_and_key(cert, key)?           // TLS certificate and key
    .with_ca_cert(ca)?                        // CA certificate for client verification
    .with_max_concurrent_streams(100)?       // Max concurrent QUIC streams
    .with_max_idle_timeout(Duration::from_secs(30))? // Idle timeout
    .build();
```

### ClientConfig

```rust
use rpcnet::ClientConfig;

let config = ClientConfig::builder()
    .with_server_cert(cert)?                 // Server certificate
    .with_ca_cert(ca)?                       // CA certificate
    .with_connect_timeout(Duration::from_secs(5))? // Connection timeout
    .build();
```

### ClusterConfig

```rust
use rpcnet::cluster::ClusterConfig;

let config = ClusterConfig::default()
    .with_bind_addr("0.0.0.0:7946".parse()?)
    .with_gossip_interval(Duration::from_secs(1))
    .with_health_check_interval(Duration::from_secs(2))
    .with_phi_threshold(8.0);
```


## Code Generation

### RPC Trait Definition

```rust
use rpcnet::prelude::*;

#[rpc_trait]
pub trait MyService {
    async fn my_method(&self, arg1: String, arg2: i32) -> Result<Response>;
    async fn streaming(&self, request: Request) -> impl Stream<Item = Result<Chunk>>;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    pub data: Vec<u8>,
}
```

### Generate Code

```bash
rpcnet-gen --input my_service.rpc.rs --output src/generated
```

### Use Generated Code

```rust
mod generated;
use generated::my_service::*;

// Server side
#[rpc_impl]
impl MyService for Handler {
    async fn my_method(&self, arg1: String, arg2: i32) -> Result<Response> {
        // Implementation
    }
}

// Client side
let client = MyServiceClient::connect(addr, config).await?;
let response = client.my_method("test".to_string(), 42).await?;
```

## Streaming

### Server-Side Streaming

```rust
#[rpc_trait]
pub trait StreamService {
    async fn stream_data(&self, count: usize) -> impl Stream<Item = Result<Data>>;
}

#[rpc_impl]
impl StreamService for Handler {
    async fn stream_data(&self, count: usize) -> impl Stream<Item = Result<Data>> {
        futures::stream::iter(0..count).map(|i| {
            Ok(Data { value: i })
        })
    }
}
```

### Client-Side Streaming

```rust
#[rpc_trait]
pub trait UploadService {
    async fn upload(&self, stream: impl Stream<Item = Chunk>) -> Result<Summary>;
}

// Client usage
let chunks = futures::stream::iter(vec![chunk1, chunk2, chunk3]);
let summary = client.upload(chunks).await?;
```

### Bidirectional Streaming

```rust
#[rpc_trait]
pub trait ChatService {
    async fn chat(&self, stream: impl Stream<Item = Message>) 
        -> impl Stream<Item = Result<Message>>;
}
```

## Load Balancing Strategies

```rust
use rpcnet::cluster::LoadBalancingStrategy;

// Round Robin - even distribution
LoadBalancingStrategy::RoundRobin

// Random - stateless selection
LoadBalancingStrategy::Random

// Least Connections - pick least loaded (recommended)
LoadBalancingStrategy::LeastConnections
```

## Cluster Events

```rust
use rpcnet::cluster::ClusterEvent;

let mut events = cluster.subscribe();
while let Some(event) = events.recv().await {
    match event {
        ClusterEvent::NodeJoined(node) => {
            println!("Node {} joined at {}", node.id, node.addr);
        }
        ClusterEvent::NodeLeft(node) => {
            println!("Node {} left", node.id);
        }
        ClusterEvent::NodeFailed(node) => {
            println!("Node {} failed", node.id);
        }
        ClusterEvent::NodeUpdated(node) => {
            println!("Node {} updated", node.id);
        }
        ClusterEvent::PartitionDetected(minority, majority) => {
            println!("Partition detected!");
        }
    }
}
```

## Error Handling

```rust
use rpcnet::{Error, ErrorKind};

match client.call("method", args).await {
    Ok(response) => {
        // Handle success
    }
    Err(e) => {
        match e.kind() {
            ErrorKind::ConnectionFailed => {
                // Connection issue, retry with different worker
            }
            ErrorKind::Timeout => {
                // Request timed out
            }
            ErrorKind::SerializationError => {
                // Data serialization failed
            }
            ErrorKind::ApplicationError => {
                // Application-level error from handler
            }
            _ => {
                // Other errors
            }
        }
    }
}
```

## Common Patterns

### Health Check Endpoint

```rust
#[rpc_trait]
pub trait HealthService {
    async fn health(&self) -> Result<HealthStatus>;
}

#[derive(Serialize, Deserialize)]
pub struct HealthStatus {
    pub healthy: bool,
    pub version: String,
    pub uptime_secs: u64,
}
```

### Graceful Shutdown

```rust
use tokio::signal;

async fn run(mut server: Server, cluster: Arc<ClusterMembership>) -> Result<()> {
    let server_task = tokio::spawn(async move { server.run().await });
    
    signal::ctrl_c().await?;
    
    // Leave cluster gracefully
    cluster.leave().await?;
    
    // Wait for in-flight requests
    server.shutdown().await?;
    
    Ok(())
}
```

### Connection Retry

```rust
async fn call_with_retry<T>(
    f: impl Fn() -> Pin<Box<dyn Future<Output = Result<T>>>>,
    max_retries: usize,
) -> Result<T> {
    for attempt in 0..max_retries {
        match f().await {
            Ok(result) => return Ok(result),
            Err(e) if attempt < max_retries - 1 => {
                tokio::time::sleep(Duration::from_millis(100 * 2_u64.pow(attempt as u32))).await;
            }
            Err(e) => return Err(e),
        }
    }
    unreachable!()
}
```

## Environment Variables

Common environment variables used in examples:

```bash
# Director
DIRECTOR_ADDR=127.0.0.1:61000
RUST_LOG=info

# Worker
WORKER_LABEL=worker-1
WORKER_ADDR=127.0.0.1:62001
DIRECTOR_ADDR=127.0.0.1:61000

# Client
CLIENT_ID=client-1

# Logging
RUST_LOG=rpcnet=debug,my_app=info
```

## Feature Flags

```toml
[dependencies]
rpcnet = { version = "0.2", features = ["cluster", "metrics"] }
```

Available features:
- `cluster` - Enable cluster features (WorkerRegistry, ClusterClient, etc.)
- `metrics` - Enable Prometheus metrics
- `codegen` - Enable code generation support (always included in v0.2+)

## Quick Examples

### Simple RPC Server

```rust
use rpcnet::prelude::*;

#[rpc_trait]
pub trait Echo {
    async fn echo(&self, msg: String) -> Result<String>;
}

#[rpc_impl]
impl Echo for Handler {
    async fn echo(&self, msg: String) -> Result<String> {
        Ok(msg)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let config = ServerConfig::builder()
        .with_cert_and_key(cert, key)?
        .build();
    
    let mut server = Server::new(config);
    server.register_service(Arc::new(Handler));
    server.bind("0.0.0.0:8080").await?;
    server.run().await?;
    Ok(())
}
```

### Simple RPC Client

```rust
#[tokio::main]
async fn main() -> Result<()> {
    let config = ClientConfig::builder()
        .with_server_cert(cert)?
        .build();
    
    let client = EchoClient::connect("localhost:8080", config).await?;
    let response = client.echo("Hello!".to_string()).await?;
    println!("Response: {}", response);
    Ok(())
}
```

## Next Steps

- **[Examples]examples.md** - Complete example programs
- **[Cluster Tutorial]../cluster/tutorial.md** - Build a cluster
- **[API Documentation]https://docs.rs/rpcnet** - Full API docs