orlando-cluster 0.1.0

A virtual actor framework in Rust, inspired by Microsoft Orleans.
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
520
521
522
523
524
525
526
527
528
529
//! Lightweight TCP transport for silo-to-silo grain calls.
//!
//! Uses length-delimited frames over raw TCP with bincode serialization,
//! targeting 15-40us latency for internal grain dispatch. gRPC remains
//! the transport for external clients.

use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use bytes::Bytes;
use dashmap::DashMap;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{watch, Mutex};
use tokio_util::codec::{Framed, LengthDelimitedCodec};

use orlando_core::GrainActivator;

use crate::connection_pool::ConnectionPool;
use crate::error::ClusterError;
use crate::hash_ring::HashRing;
use crate::message_registry::MessageRegistry;
use crate::network_message::Encoding;

// ---------------------------------------------------------------------------
// Wire types
// ---------------------------------------------------------------------------

/// Request sent over the TCP wire. Mirrors the gRPC `InvokeRequest` but avoids
/// protobuf overhead — pure bincode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TcpInvokeRequest {
    pub request_id: u64,
    pub grain_type: String,
    pub grain_key: String,
    pub message_type: String,
    pub payload: Vec<u8>,
    pub context: HashMap<String, String>,
}

/// Response sent over the TCP wire.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TcpInvokeResponse {
    pub request_id: u64,
    pub success: bool,
    pub payload: Vec<u8>,
    pub error: Option<String>,
}

// ---------------------------------------------------------------------------
// Server
// ---------------------------------------------------------------------------

/// TCP transport server that listens for incoming silo-to-silo grain calls.
pub struct TcpTransportServer {
    registry: Arc<MessageRegistry>,
    activator: Arc<dyn GrainActivator>,
    ring: Arc<std::sync::RwLock<HashRing>>,
    pool: Arc<ConnectionPool>,
    local_silo_id: String,
}

impl fmt::Debug for TcpTransportServer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TcpTransportServer")
            .field("local_silo_id", &self.local_silo_id)
            .finish_non_exhaustive()
    }
}

impl TcpTransportServer {
    pub fn new(
        registry: Arc<MessageRegistry>,
        activator: Arc<dyn GrainActivator>,
        ring: Arc<std::sync::RwLock<HashRing>>,
        pool: Arc<ConnectionPool>,
        local_silo_id: String,
    ) -> Self {
        Self {
            registry,
            activator,
            ring,
            pool,
            local_silo_id,
        }
    }

    /// Run the TCP listener until the shutdown signal fires.
    pub async fn serve(
        self: Arc<Self>,
        addr: SocketAddr,
        mut shutdown: watch::Receiver<bool>,
    ) -> Result<(), ClusterError> {
        let listener = TcpListener::bind(addr)
            .await
            .map_err(|e| ClusterError::Transport(format!("tcp bind failed: {}", e)))?;

        tracing::info!(%addr, "tcp transport listening");

        loop {
            tokio::select! {
                accept = listener.accept() => {
                    match accept {
                        Ok((stream, peer)) => {
                            tracing::debug!(%peer, "tcp transport: accepted connection");
                            let server = self.clone();
                            tokio::spawn(async move {
                                if let Err(e) = server.handle_connection(stream).await {
                                    tracing::debug!(error = %e, "tcp connection handler error");
                                }
                            });
                        }
                        Err(e) => {
                            tracing::debug!(error = %e, "tcp accept error");
                        }
                    }
                }
                _ = shutdown.changed() => {
                    tracing::info!("tcp transport shutting down");
                    break;
                }
            }
        }

        Ok(())
    }

    async fn handle_connection(self: Arc<Self>, stream: TcpStream) -> Result<(), ClusterError> {
        stream
            .set_nodelay(true)
            .map_err(|e| ClusterError::Transport(e.to_string()))?;

        let mut framed = Framed::new(stream, build_codec());

        while let Some(frame) = framed.next().await {
            let frame = frame.map_err(|e| ClusterError::Transport(e.to_string()))?;

            let (request, _): (TcpInvokeRequest, _) =
                bincode::serde::decode_from_slice(&frame, bincode::config::standard())
                    .map_err(|e| ClusterError::Deserialization(e.to_string()))?;

            let server = self.clone();

            // Dispatch inline (not spawned) to keep ordering per connection.
            // Callers wanting concurrency use multiple connections or request IDs
            // via the multiplexed client.
            let response = server.dispatch(request).await;

            let encoded = bincode::serde::encode_to_vec(&response, bincode::config::standard())
                .map_err(|e| ClusterError::Serialization(e.to_string()))?;

            framed
                .send(Bytes::from(encoded))
                .await
                .map_err(|e| ClusterError::Transport(e.to_string()))?;
        }

        Ok(())
    }

    async fn dispatch(&self, request: TcpInvokeRequest) -> TcpInvokeResponse {
        // Check if grain belongs on a different silo (gateway forwarding)
        let forward_endpoint = {
            let ring_key = format!("{}/{}", request.grain_type, request.grain_key);
            let ring = self.ring.read().expect("ring lock poisoned");
            match ring.get(&ring_key) {
                Some(target) if target.silo_id != self.local_silo_id => {
                    Some(target.endpoint())
                }
                _ => None,
            }
        };

        if let Some(endpoint) = forward_endpoint {
            tracing::debug!(
                grain_type = %request.grain_type,
                grain_key = %request.grain_key,
                target = %endpoint,
                "tcp: forwarding grain call to owner silo via grpc"
            );

            // Forward via gRPC (TCP forwarding would require knowing peer TCP ports)
            let client = self.pool.get_transport(&endpoint).await;
            match client {
                Ok(mut c) => {
                    let grpc_req = crate::proto::InvokeRequest {
                        grain_type: request.grain_type,
                        grain_key: request.grain_key,
                        message_type: request.message_type,
                        payload: request.payload,
                        encoding: 0, // bincode
                        request_context: request.context,
                        message_version: 0,
                    };
                    match c.invoke(grpc_req).await {
                        Ok(resp) => {
                            let inner = resp.into_inner();
                            let success = inner.error.is_empty();
                            TcpInvokeResponse {
                                request_id: request.request_id,
                                success,
                                payload: inner.payload,
                                error: if success {
                                    None
                                } else {
                                    Some(inner.error)
                                },
                            }
                        }
                        Err(e) => TcpInvokeResponse {
                            request_id: request.request_id,
                            success: false,
                            payload: Vec::new(),
                            error: Some(e.to_string()),
                        },
                    }
                }
                Err(e) => TcpInvokeResponse {
                    request_id: request.request_id,
                    success: false,
                    payload: Vec::new(),
                    error: Some(e.to_string()),
                },
            }
        } else {
            // Local dispatch
            match self
                .registry
                .dispatch(
                    &request.grain_type,
                    request.grain_key,
                    &request.message_type,
                    0, // message_version
                    request.payload,
                    Encoding::Bincode,
                    request.context,
                    self.activator.clone(),
                )
                .await
            {
                Ok((payload, _encoding)) => TcpInvokeResponse {
                    request_id: request.request_id,
                    success: true,
                    payload,
                    error: None,
                },
                Err(e) => TcpInvokeResponse {
                    request_id: request.request_id,
                    success: false,
                    payload: Vec::new(),
                    error: Some(e.to_string()),
                },
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Client
// ---------------------------------------------------------------------------

/// A single TCP connection to a peer silo that supports sequential request/response.
struct TcpTransportConnection {
    framed: Framed<TcpStream, LengthDelimitedCodec>,
}

impl TcpTransportConnection {
    async fn connect(addr: &str) -> Result<Self, ClusterError> {
        let stream = TcpStream::connect(addr)
            .await
            .map_err(|e| ClusterError::Transport(format!("tcp connect to {}: {}", addr, e)))?;

        stream
            .set_nodelay(true)
            .map_err(|e| ClusterError::Transport(e.to_string()))?;

        Ok(Self {
            framed: Framed::new(stream, build_codec()),
        })
    }

    async fn invoke(
        &mut self,
        request: TcpInvokeRequest,
    ) -> Result<TcpInvokeResponse, ClusterError> {
        let encoded = bincode::serde::encode_to_vec(&request, bincode::config::standard())
            .map_err(|e| ClusterError::Serialization(e.to_string()))?;

        self.framed
            .send(Bytes::from(encoded))
            .await
            .map_err(|e| ClusterError::Transport(e.to_string()))?;

        let frame = self
            .framed
            .next()
            .await
            .ok_or_else(|| ClusterError::Transport("tcp connection closed".to_string()))?
            .map_err(|e| ClusterError::Transport(e.to_string()))?;

        let (response, _): (TcpInvokeResponse, _) =
            bincode::serde::decode_from_slice(&frame, bincode::config::standard())
                .map_err(|e| ClusterError::Deserialization(e.to_string()))?;

        Ok(response)
    }
}

// ---------------------------------------------------------------------------
// Client (public API wrapping a connection)
// ---------------------------------------------------------------------------

/// TCP transport client for sending grain invoke requests to a peer silo.
pub struct TcpTransportClient {
    /// The peer endpoint (host:port).
    endpoint: String,
    /// The underlying connection, wrapped in a mutex for sequential access.
    /// For concurrency, use `TcpConnectionPool` which manages multiple clients.
    conn: Mutex<Option<TcpTransportConnection>>,
    next_request_id: AtomicU64,
}

impl fmt::Debug for TcpTransportClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TcpTransportClient")
            .field("endpoint", &self.endpoint)
            .finish_non_exhaustive()
    }
}

impl TcpTransportClient {
    /// Create a new client targeting the given endpoint. Connection is lazy.
    pub fn new(endpoint: String) -> Self {
        Self {
            endpoint,
            conn: Mutex::new(None),
            next_request_id: AtomicU64::new(1),
        }
    }

    /// Send an invoke request and return the response.
    pub async fn invoke(
        &self,
        grain_type: String,
        grain_key: String,
        message_type: String,
        payload: Vec<u8>,
        context: HashMap<String, String>,
    ) -> Result<TcpInvokeResponse, ClusterError> {
        let request_id = self.next_request_id.fetch_add(1, Ordering::Relaxed);

        let request = TcpInvokeRequest {
            request_id,
            grain_type,
            grain_key,
            message_type,
            payload,
            context,
        };

        let mut guard = self.conn.lock().await;

        // Lazy connect
        if guard.is_none() {
            *guard = Some(TcpTransportConnection::connect(&self.endpoint).await?);
        }

        let conn = guard.as_mut().expect("connection just established");
        match conn.invoke(request.clone()).await {
            Ok(resp) => Ok(resp),
            Err(_) => {
                // Reconnect once on failure
                tracing::debug!(endpoint = %self.endpoint, "tcp: reconnecting after error");
                let mut new_conn =
                    TcpTransportConnection::connect(&self.endpoint).await?;
                let resp = new_conn.invoke(request).await?;
                *guard = Some(new_conn);
                Ok(resp)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Connection pool
// ---------------------------------------------------------------------------

/// Manages TCP connections to peer silos. Each endpoint gets a lazily-created
/// `TcpTransportClient`.
#[derive(Debug, Default)]
pub struct TcpConnectionPool {
    clients: DashMap<String, Arc<TcpTransportClient>>,
}

impl TcpConnectionPool {
    pub fn new() -> Self {
        Self {
            clients: DashMap::new(),
        }
    }

    /// Get or create a TCP client for the given endpoint.
    pub fn get_client(&self, endpoint: &str) -> Arc<TcpTransportClient> {
        if let Some(client) = self.clients.get(endpoint) {
            return client.clone();
        }

        let client = Arc::new(TcpTransportClient::new(endpoint.to_string()));
        self.clients
            .insert(endpoint.to_string(), client.clone());
        client
    }

    /// Remove a client for the given endpoint (e.g. on silo departure).
    pub fn remove(&self, endpoint: &str) {
        self.clients.remove(endpoint);
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn build_codec() -> LengthDelimitedCodec {
    LengthDelimitedCodec::builder()
        .max_frame_length(16 * 1024 * 1024) // 16 MiB max frame
        .new_codec()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::time::Duration;

    use orlando_core::GrainActivator;
    use crate::hash_ring::HashRing;
    use crate::message_registry::MessageRegistry;

    /// Round-trip test: start a TCP server, connect a client, send an invoke,
    /// and get a response. The registry has no handlers registered, so we
    /// expect an error response (unknown grain type) — but the wire protocol
    /// round-trip is exercised.
    #[tokio::test]
    async fn tcp_round_trip_unknown_grain() {
        let registry = Arc::new(MessageRegistry::new());
        let ring = Arc::new(std::sync::RwLock::new(HashRing::new(10)));
        let pool = Arc::new(ConnectionPool::new());

        // Use the GrainDirectory as the activator (same as production)
        let directory = Arc::new(orlando_runtime::GrainDirectory::new());
        let activator: Arc<dyn GrainActivator> = directory;

        let server = Arc::new(TcpTransportServer::new(
            registry,
            activator,
            ring,
            pool,
            "test-silo".to_string(),
        ));

        let (shutdown_tx, shutdown_rx) = watch::channel(false);

        // Bind to an OS-assigned port
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("local_addr");
        drop(listener); // release so the server can bind

        let server_handle = {
            let server = server.clone();
            tokio::spawn(async move {
                let _ = server.serve(addr, shutdown_rx).await;
            })
        };

        // Give the server a moment to start listening
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Client side
        let client = TcpTransportClient::new(addr.to_string());
        let response = client
            .invoke(
                "NonExistentGrain".to_string(),
                "key-1".to_string(),
                "SomeMessage".to_string(),
                vec![1, 2, 3],
                HashMap::new(),
            )
            .await
            .expect("invoke should succeed at transport level");

        assert!(!response.success, "should fail because grain type is unknown");
        assert!(
            response.error.as_deref().unwrap_or("").contains("unknown grain type"),
            "error should mention unknown grain type, got: {:?}",
            response.error
        );

        // Shut down
        let _ = shutdown_tx.send(true);
        let _ = server_handle.await;
    }

    /// Test that TcpConnectionPool returns the same client for repeated lookups.
    #[test]
    fn tcp_pool_returns_same_client() {
        let pool = TcpConnectionPool::new();
        let c1 = pool.get_client("127.0.0.1:9999");
        let c2 = pool.get_client("127.0.0.1:9999");
        assert!(Arc::ptr_eq(&c1, &c2));
    }

    /// Test that TcpConnectionPool returns different clients for different endpoints.
    #[test]
    fn tcp_pool_different_endpoints() {
        let pool = TcpConnectionPool::new();
        let c1 = pool.get_client("127.0.0.1:9999");
        let c2 = pool.get_client("127.0.0.1:8888");
        assert!(!Arc::ptr_eq(&c1, &c2));
    }
}