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
use std::collections::HashMap;
use std::sync::Arc;

use arc_swap::ArcSwap;

use tonic::{Request, Response, Status};

use orlando_core::{ClusterId, GrainActivator, GrainId};

use crate::auth::ClusterAuth;
use crate::connection_pool::ConnectionPool;
use crate::cross_cluster_directory::CrossClusterDirectory;
use crate::hash_ring::HashRing;
use crate::message_registry::MessageRegistry;
use crate::network_message::Encoding;
use crate::proto::grain_transport_server::GrainTransport;
use crate::proto::{ForwardInvokeRequest, InvokeRequest, InvokeResponse};

/// Maximum number of forwarding hops before a request is rejected.
/// Prevents infinite forwarding loops when the ring is stale on multiple silos.
const MAX_HOPS: u32 = 3;
const HOP_COUNT_KEY: &str = "__orlando_hop_count";

/// Maximum payload size accepted for deserialization (64 MB).
const MAX_PAYLOAD_SIZE: usize = 64 * 1024 * 1024;

pub struct GrainTransportService {
    registry: Arc<MessageRegistry>,
    activator: Arc<dyn GrainActivator>,
    ring: Arc<ArcSwap<HashRing>>,
    pool: Arc<ConnectionPool>,
    local_silo_id: String,
    auth: Option<Arc<dyn ClusterAuth>>,
    // Cross-cluster (GSI) fields -- None when multi-cluster is not configured
    cross_cluster_dir: Option<Arc<dyn CrossClusterDirectory>>,
    local_cluster_id: Option<ClusterId>,
    peer_endpoints: Option<Arc<HashMap<ClusterId, String>>>,
}

impl GrainTransportService {
    pub fn new(
        registry: Arc<MessageRegistry>,
        activator: Arc<dyn GrainActivator>,
        ring: Arc<ArcSwap<HashRing>>,
        pool: Arc<ConnectionPool>,
        local_silo_id: String,
        auth: Option<Arc<dyn ClusterAuth>>,
    ) -> Self {
        Self {
            registry,
            activator,
            ring,
            pool,
            local_silo_id,
            auth,
            cross_cluster_dir: None,
            local_cluster_id: None,
            peer_endpoints: None,
        }
    }

    /// Enable cross-cluster forwarding (GSI).
    pub fn with_cross_cluster(
        mut self,
        dir: Arc<dyn CrossClusterDirectory>,
        local_cluster_id: ClusterId,
        peer_endpoints: Arc<HashMap<ClusterId, String>>,
    ) -> Self {
        self.cross_cluster_dir = Some(dir);
        self.local_cluster_id = Some(local_cluster_id);
        self.peer_endpoints = Some(peer_endpoints);
        self
    }

    /// Check all other silos for an active grain. Returns the endpoint of the owner if found.
    async fn lookup_grain_cluster_wide(
        &self,
        grain_type: &str,
        grain_key: &str,
    ) -> Option<String> {
        let members: Vec<crate::hash_ring::SiloAddress> = {
            let ring = self.ring.load();
            ring.members()
                .into_iter()
                .filter(|m| m.silo_id != self.local_silo_id)
                .collect()
        };

        if members.is_empty() {
            return None;
        }

        // Parallel lookup — fire all RPCs concurrently, return on first hit
        let mut tasks = tokio::task::JoinSet::new();
        for member in members {
            let pool = self.pool.clone();
            let gt = grain_type.to_string();
            let gk = grain_key.to_string();
            tasks.spawn(async move {
                let mut client = pool.get_membership(&member.endpoint()).await.ok()?;
                let resp = tokio::time::timeout(
                    std::time::Duration::from_secs(2),
                    client.lookup_grain(crate::proto::LookupGrainRequest {
                        grain_type: gt,
                        grain_key: gk,
                    }),
                )
                .await
                .ok()?
                .ok()?;
                let inner = resp.into_inner();
                if inner.active {
                    Some(inner.endpoint)
                } else {
                    None
                }
            });
        }

        while let Some(result) = tasks.join_next().await {
            if let Ok(Some(endpoint)) = result {
                tasks.abort_all();
                return Some(endpoint);
            }
        }

        None
    }

    /// Check the hash ring to determine which silo owns a grain.
    /// Returns None if this silo owns it (or ring is empty), Some(endpoint) if remote.
    fn find_owner(&self, grain_type: &str, grain_key: &str) -> Option<String> {
        let ring_key = format!("{}/{}", grain_type, grain_key);
        let ring = self.ring.load();
        match ring.get(&ring_key) {
            Some(target) if target.silo_id != self.local_silo_id => Some(target.endpoint()),
            _ => None,
        }
    }

    /// Check if a grain is owned by another cluster and forward if so.
    /// Returns Some(response) if forwarded, None if we should handle locally.
    async fn check_cross_cluster(
        &self,
        req: &InvokeRequest,
    ) -> Result<Option<Response<InvokeResponse>>, Status> {
        let (dir, local_cid, peers) = match (
            &self.cross_cluster_dir,
            &self.local_cluster_id,
            &self.peer_endpoints,
        ) {
            (Some(d), Some(c), Some(p)) => (d, c, p),
            _ => return Ok(None),
        };

        // Resolve the type to its registered &'static str. An unknown type
        // cannot be owned by any cluster and must never be leaked into a
        // &'static str (memory-exhaustion DoS), so fall through to local
        // dispatch, where it is rejected with UnknownGrainType.
        let Some(type_name) = self.registry.resolve_grain_type(&req.grain_type) else {
            return Ok(None);
        };
        let grain_id = GrainId {
            type_name,
            key: req.grain_key.clone(),
        };

        match dir.lookup(&grain_id).await {
            Ok(Some(ownership)) => {
                if ownership.cluster_id == *local_cid {
                    // We own it, proceed with local dispatch
                    return Ok(None);
                }
                // Forward to the owning cluster
                if let Some(endpoint) = peers.get(&ownership.cluster_id) {
                    tracing::debug!(
                        grain_type = %req.grain_type,
                        grain_key = %req.grain_key,
                        target_cluster = %ownership.cluster_id,
                        "forwarding grain call to owning cluster"
                    );
                    let response = self.forward_to_cluster(endpoint, req, local_cid).await?;
                    return Ok(Some(response));
                }
                // Unknown peer cluster, fall through to local
                Ok(None)
            }
            Ok(None) => {
                // Check data residency constraints before claiming ownership
                if let Some(allowed) = self.registry.allowed_clusters(&req.grain_type) {
                    if !allowed.contains(&local_cid.as_str()) {
                        // This cluster is not allowed to host this grain.
                        // Forward to the first allowed cluster we know about.
                        for cluster_name in allowed {
                            let target_id = ClusterId::new(*cluster_name);
                            if let Some(endpoint) = peers.get(&target_id) {
                                tracing::debug!(
                                    grain_type = %req.grain_type,
                                    grain_key = %req.grain_key,
                                    target_cluster = %target_id,
                                    "data residency: forwarding to allowed cluster"
                                );
                                let response =
                                    self.forward_to_cluster(endpoint, req, local_cid).await?;
                                return Ok(Some(response));
                            }
                        }
                        // No reachable allowed cluster — reject
                        return Err(Status::failed_precondition(format!(
                            "grain type {} is restricted to clusters {:?} but none are reachable",
                            req.grain_type, allowed
                        )));
                    }
                }

                // Not registered anywhere and we're allowed. Register as owner.
                let _ = dir.register(&grain_id, local_cid, 1).await;
                Ok(None)
            }
            Err(e) => {
                tracing::warn!(error = %e, "cross-cluster directory lookup failed, falling back to local");
                Ok(None)
            }
        }
    }

    /// Forward a grain call to another cluster's gateway service.
    async fn forward_to_cluster(
        &self,
        endpoint: &str,
        req: &InvokeRequest,
        local_cluster_id: &ClusterId,
    ) -> Result<Response<InvokeResponse>, Status> {
        let mut client = self
            .pool
            .get_gateway(endpoint)
            .await
            .map_err(|e| Status::unavailable(format!("cross-cluster connection failed: {}", e)))?;

        let forward_req = ForwardInvokeRequest {
            grain_type: req.grain_type.clone(),
            grain_key: req.grain_key.clone(),
            message_type: req.message_type.clone(),
            payload: req.payload.clone(),
            encoding: req.encoding,
            request_context: req.request_context.clone(),
            source_cluster_id: local_cluster_id.to_string(),
            message_version: req.message_version,
        };

        let response = client
            .forward_invoke(forward_req)
            .await
            .map_err(|e| Status::internal(format!("cross-cluster forward failed: {}", e)))?;

        let inner = response.into_inner();
        Ok(Response::new(InvokeResponse {
            payload: inner.payload,
            error: inner.error,
            encoding: inner.encoding,
        }))
    }
}

#[tonic::async_trait]
impl GrainTransport for GrainTransportService {
    async fn invoke(
        &self,
        request: Request<InvokeRequest>,
    ) -> Result<Response<InvokeResponse>, Status> {
        // Auth check
        if let Some(ref auth) = self.auth {
            auth.authenticate(request.metadata())?;
        }
        let req = request.into_inner();
        let encoding = Encoding::from_proto(req.encoding);

        // Reject oversized payloads before deserialization
        if req.payload.len() > MAX_PAYLOAD_SIZE {
            return Err(Status::invalid_argument(format!(
                "payload size {} exceeds maximum of {} bytes",
                req.payload.len(),
                MAX_PAYLOAD_SIZE,
            )));
        }

        // Gateway forwarding: if this grain belongs on a different silo, forward the request
        if let Some(endpoint) = self.find_owner(&req.grain_type, &req.grain_key) {
            // Check hop count to prevent infinite forwarding loops
            let hop_count: u32 = req
                .request_context
                .get(HOP_COUNT_KEY)
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);

            if hop_count >= MAX_HOPS {
                return Err(Status::internal(format!(
                    "maximum forwarding hops ({}) exceeded — possible routing loop",
                    MAX_HOPS,
                )));
            }

            tracing::debug!(
                grain_type = %req.grain_type,
                grain_key = %req.grain_key,
                target = %endpoint,
                hop = hop_count + 1,
                "forwarding grain call to owner silo"
            );

            let mut client = self
                .pool
                .get_transport(&endpoint)
                .await
                .map_err(|e| Status::unavailable(e.to_string()))?;

            // Increment hop count and forward
            let mut fwd_context = req.request_context.clone();
            fwd_context.insert(HOP_COUNT_KEY.to_string(), (hop_count + 1).to_string());

            let response = client
                .invoke(self.pool.authorized_request(InvokeRequest {
                    grain_type: req.grain_type,
                    grain_key: req.grain_key,
                    message_type: req.message_type,
                    payload: req.payload,
                    encoding: req.encoding,
                    request_context: fwd_context,
                    message_version: req.message_version,
                }))
                .await
                .map_err(|e| Status::internal(e.to_string()))?;

            return Ok(response);
        }

        // Cross-cluster check (GSI): if another cluster owns this grain, forward there
        if let Some(response) = self.check_cross_cluster(&req).await? {
            return Ok(response);
        }

        // Before local dispatch: check if grain is already active locally
        let already_local = if let Some(type_name) = self.registry.grain_type_str(&req.grain_type) {
            let grain_id = orlando_core::GrainId {
                type_name,
                key: req.grain_key.clone(),
            };
            self.activator
                .get_sender(&grain_id)
                .map_or(false, |s| !s.is_closed())
        } else {
            false
        };

        // If not active locally, check cluster-wide to prevent duplicate activation
        if !already_local
            && let Some(endpoint) =
                self.lookup_grain_cluster_wide(&req.grain_type, &req.grain_key)
                    .await
        {
            // Parse hop count (shared with the gateway forwarding path)
            let hop_count: u32 = req
                .request_context
                .get(HOP_COUNT_KEY)
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);

            if hop_count >= MAX_HOPS {
                return Err(Status::internal(format!(
                    "maximum forwarding hops ({}) exceeded during directory lookup",
                    MAX_HOPS,
                )));
            }

            tracing::debug!(
                grain_type = %req.grain_type,
                grain_key = %req.grain_key,
                target = %endpoint,
                hop = hop_count + 1,
                "grain active on another silo, forwarding to prevent duplicate activation"
            );

            let mut client = self
                .pool
                .get_transport(&endpoint)
                .await
                .map_err(|e| Status::unavailable(e.to_string()))?;

            let mut fwd_context = req.request_context.clone();
            fwd_context.insert(HOP_COUNT_KEY.to_string(), (hop_count + 1).to_string());

            let response = client
                .invoke(self.pool.authorized_request(InvokeRequest {
                    grain_type: req.grain_type,
                    grain_key: req.grain_key,
                    message_type: req.message_type,
                    payload: req.payload,
                    encoding: req.encoding,
                    request_context: fwd_context,
                    message_version: req.message_version,
                }))
                .await
                .map_err(|e| Status::internal(e.to_string()))?;

            return Ok(response);
        }

        // Local dispatch — pass request context through to the grain handler
        match self
            .registry
            .dispatch(
                &req.grain_type,
                req.grain_key,
                &req.message_type,
                req.message_version,
                req.payload,
                encoding,
                req.request_context,
                self.activator.clone(),
            )
            .await
        {
            Ok((payload, response_encoding)) => Ok(Response::new(InvokeResponse {
                payload,
                error: String::new(),
                encoding: response_encoding.to_proto(),
            })),
            Err(e) => Ok(Response::new(InvokeResponse {
                payload: Vec::new(),
                error: e.to_string(),
                encoding: encoding.to_proto(),
            })),
        }
    }
}