forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistributed.rs
More file actions
2610 lines (2404 loc) · 101 KB
/
Copy pathdistributed.rs
File metadata and controls
2610 lines (2404 loc) · 101 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Distributed Actor Address Resolution for Nulang.
//!
//! This module provides **location-transparent actor addressing**, allowing
//! actors to send messages to other actors regardless of whether they reside
//! on the same node or a remote node in the cluster.
//!
//! # Architecture
//!
//! ```text
//! Actor (local) ActorAddress::Local{actor_id}
//! | |
//! v v
//! send_distributed() ----> AddressResolver::resolve()
//! |
//! +-----------+-----------+
//! | |
//! Local actor Remote actor
//! | |
//! Runtime:: NetworkTransport::
//! send_message() send(packet)
//! |
//! v
//! Packet::ActorMessage
//! ```
//!
//! The [`ActorAddress`] enum is the core abstraction: it can refer to either a
//! local actor (same node) or a remote actor (different node). The runtime
//! uses this to route messages to the correct destination without the sender
//! knowing the physical location of the target actor.
//!
//! # Key Types
//!
//! - [`ActorAddress`] — location-transparent actor reference.
//! - [`AddressResolver`] — resolves addresses to local lookups or network routes.
//! - [`RemoteActorCache`] — LRU cache of recently-contacted remote actors.
//! - [`DistributedRuntime`] — trait extending [`Runtime`] with distributed ops.
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant};
// ---------------------------------------------------------------------------
// Imports from sibling modules in the runtime
// ---------------------------------------------------------------------------
use super::mailbox::{Message, MessagePriority};
use super::network::{NetworkTransport, Packet};
use super::{ClusterState, NodeId, NodeStatus};
use crate::runtime::Runtime;
use crate::types::ExitReason;
use crate::vm::Value;
use tracing::warn;
// Message wrapper for distributed communication
#[derive(Debug, Clone, PartialEq)]
pub struct DistributedMessage(pub Message);
impl From<Message> for DistributedMessage {
fn from(msg: Message) -> Self {
DistributedMessage(msg)
}
}
impl From<DistributedMessage> for Message {
fn from(dm: DistributedMessage) -> Self {
dm.0
}
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Default maximum number of entries in the remote actor cache.
const DEFAULT_CACHE_SIZE: usize = 10_000;
/// Default TTL for cache entries in seconds. Stale entries are evicted on access.
const CACHE_TTL_SECS: u64 = 60;
// ---------------------------------------------------------------------------
// ActorAddress
// ---------------------------------------------------------------------------
/// A location-transparent address for an actor.
///
/// An `ActorAddress` can refer to either a local actor (same node) or a
/// remote actor (different node). The runtime uses this to route messages
/// to the correct destination without the sender knowing the location.
///
/// # Example
///
/// ```ignore
/// use nulang::runtime::distributed::ActorAddress;
/// use nulang::runtime::cluster::NodeId;
///
/// let local = ActorAddress::local(42);
/// assert!(local.is_local());
///
/// let remote = ActorAddress::remote(NodeId(7), 42);
/// assert!(remote.is_remote());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActorAddress {
/// Actor on this node.
Local { actor_id: u64 },
/// Actor on a remote node.
Remote { node_id: NodeId, actor_id: u64 },
}
impl ActorAddress {
/// Create a local address.
pub fn local(actor_id: u64) -> Self {
ActorAddress::Local { actor_id }
}
/// Create a remote address.
pub fn remote(node_id: NodeId, actor_id: u64) -> Self {
ActorAddress::Remote { node_id, actor_id }
}
/// Get the actor ID regardless of location.
pub fn actor_id(&self) -> u64 {
match self {
ActorAddress::Local { actor_id } => *actor_id,
ActorAddress::Remote { actor_id, .. } => *actor_id,
}
}
/// Get the node ID (returns `NodeId::LOCAL` for local actors).
pub fn node_id(&self) -> NodeId {
match self {
ActorAddress::Local { .. } => NodeId::LOCAL,
ActorAddress::Remote { node_id, .. } => *node_id,
}
}
/// Check if this is a local address.
pub fn is_local(&self) -> bool {
matches!(self, ActorAddress::Local { .. })
}
/// Check if this is a remote address.
pub fn is_remote(&self) -> bool {
matches!(self, ActorAddress::Remote { .. })
}
}
// ---------------------------------------------------------------------------
// RemoteActorInfo
// ---------------------------------------------------------------------------
/// Cached information about a remote actor.
#[derive(Debug, Clone)]
pub struct RemoteActorInfo {
/// Node the actor lives on.
pub node_id: NodeId,
/// Actor ID on the remote node.
pub actor_id: u64,
/// When this cache entry was last accessed.
pub last_accessed: Instant,
/// How many messages have been sent to this actor (approximate).
pub message_count: u64,
}
// ---------------------------------------------------------------------------
// RemoteActorCache
// ---------------------------------------------------------------------------
/// Cache of remote actors that this node knows about.
///
/// When we send a message to a remote actor, we cache its address so
/// that subsequent sends don't need to resolve it again. The cache
/// also tracks which remote actors have sent us messages (so we can
/// reply).
///
/// Uses a simple LRU eviction policy: when the cache exceeds `max_entries`,
pub struct RemoteActorCache {
/// Map: (remote node, actor id) → cached info.
entries: HashMap<(NodeId, u64), RemoteActorInfo>,
/// Maximum number of entries before eviction.
max_entries: usize,
/// Access order for LRU eviction — most recent at the back.
access_order: VecDeque<(NodeId, u64)>,
/// How long an entry can live before being evicted as stale.
ttl: Duration,
}
impl RemoteActorCache {
/// Create a new cache with the given maximum capacity and per-entry TTL.
pub fn new(max_entries: usize, ttl: Duration) -> Self {
RemoteActorCache {
entries: HashMap::with_capacity(max_entries.min(1024)),
max_entries: max_entries.max(1), // Ensure at least 1
access_order: VecDeque::new(),
ttl,
}
}
/// Create a new cache with the default size and TTL.
pub fn with_defaults() -> Self {
Self::new(DEFAULT_CACHE_SIZE, Duration::from_secs(CACHE_TTL_SECS))
}
/// Look up a remote actor in the cache.
///
/// On a hit, the entry is moved to the most-recently-used position.
pub fn get(&mut self, node_id: NodeId, actor_id: u64) -> Option<&RemoteActorInfo> {
let key = (node_id, actor_id);
// Check staleness first (immutable borrow) to avoid double mutable borrow.
let is_stale = self
.entries
.get(&key)
.map(|info| info.last_accessed.elapsed() > self.ttl)
.unwrap_or(false);
if is_stale {
self.entries.remove(&key);
self.access_order.retain(|&k| k != key);
return None;
}
if let Some(info) = self.entries.get_mut(&key) {
// Update LRU position: remove and re-insert at back.
self.access_order.retain(|&k| k != key);
self.access_order.push_back(key);
// Update last_accessed timestamp.
info.last_accessed = Instant::now();
Some(info)
} else {
None
}
}
/// Add or update a remote actor in the cache.
///
/// If the cache is at capacity, the least-recently-used entry is evicted.
pub fn put(&mut self, node_id: NodeId, actor_id: u64) {
let key = (node_id, actor_id);
// If already present, just update position and timestamp.
if let Some(info) = self.entries.get_mut(&key) {
self.access_order.retain(|&k| k != key);
self.access_order.push_back(key);
info.last_accessed = Instant::now();
return;
}
// Evict if at capacity.
if self.entries.len() >= self.max_entries {
if let Some(evict_key) = self.access_order.pop_front() {
self.entries.remove(&evict_key);
}
}
// Insert new entry.
let info = RemoteActorInfo {
node_id,
actor_id,
last_accessed: Instant::now(),
message_count: 0,
};
self.entries.insert(key, info);
self.access_order.push_back(key);
}
/// Remove a remote actor from the cache.
pub fn remove(&mut self, node_id: NodeId, actor_id: u64) {
let key = (node_id, actor_id);
self.entries.remove(&key);
self.access_order.retain(|&k| k != key);
}
/// Remove every cached entry whose actor lives on the given node.
///
/// Called when a node is declared `Failed` so sends to its actors fail
/// fast with an unresolvable result instead of stale-resolving to a
/// node that is no longer reachable.
pub fn remove_node(&mut self, node_id: NodeId) {
self.entries.retain(|&(n, _), _| n != node_id);
self.access_order
.retain(|key| self.entries.contains_key(key));
}
/// Get the N most recently accessed remote actors.
///
/// Returns them in MRU order (most recent first).
pub fn most_active(&self, n: usize) -> Vec<&RemoteActorInfo> {
self.access_order
.iter()
.rev()
.filter_map(|key| self.entries.get(key))
.take(n)
.collect()
}
/// Increment the message count for a cached entry.
///
/// No-op if the entry is not in the cache.
fn increment_message_count(&mut self, node_id: NodeId, actor_id: u64) {
let key = (node_id, actor_id);
if let Some(info) = self.entries.get_mut(&key) {
info.message_count += 1;
}
}
/// Current number of cached entries.
pub fn len(&self) -> usize {
self.entries.len()
}
/// Check if the cache is empty.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Evict all entries older than the TTL. Call this periodically to
/// prevent the cache from filling with stale entries for dead actors.
pub fn evict_stale(&mut self) {
let cutoff = Instant::now() - self.ttl;
self.entries.retain(|_, info| info.last_accessed >= cutoff);
self.access_order
.retain(|key| self.entries.get(key).is_some());
}
}
// ---------------------------------------------------------------------------
// ResolveResult
// ---------------------------------------------------------------------------
/// Result of resolving an actor address.
#[derive(Debug, Clone, PartialEq)]
pub enum ResolveResult {
/// Actor is local — look it up in the local actor table.
Local { actor_id: u64 },
/// Actor is remote — send this packet to the given node.
Remote { node_id: NodeId, actor_id: u64 },
/// Cannot resolve — node is not in the cluster or actor is unknown.
Unresolvable { reason: String },
}
// ---------------------------------------------------------------------------
// ResolverStats
// ---------------------------------------------------------------------------
/// Statistics for the address resolver.
#[derive(Debug, Default, Clone, Copy, serde::Serialize)]
pub struct ResolverStats {
/// Number of addresses resolved to local actors.
pub local_resolves: u64,
/// Number of addresses resolved to remote actors.
pub remote_resolves: u64,
/// Number of failed resolves (unhealthy node, unknown actor, etc.).
pub failed_resolves: u64,
/// Number of cache hits during resolution.
pub cache_hits: u64,
/// Number of cache misses during resolution.
pub cache_misses: u64,
}
// ---------------------------------------------------------------------------
// AddressResolver
// ---------------------------------------------------------------------------
/// Resolves actor addresses to either local actor lookups or network routes.
///
/// This is the core of location transparency: given an [`ActorAddress`],
/// the resolver either finds the local actor or prepares a network packet
/// to send to the remote node.
///
/// The resolver maintains a [`RemoteActorCache`] to avoid repeated cluster
/// lookups for hot remote actors, and tracks statistics for observability.
pub struct AddressResolver {
local_node: NodeId,
remote_cache: RemoteActorCache,
stats: ResolverStats,
}
impl AddressResolver {
/// Create a new resolver for the given local node.
pub fn new(local_node: NodeId) -> Self {
AddressResolver {
local_node,
remote_cache: RemoteActorCache::with_defaults(),
stats: ResolverStats::default(),
}
}
/// Resolve an actor address.
///
/// For local addresses, returns [`ResolveResult::Local`].
/// For remote addresses, checks the cluster membership to verify
/// the node is healthy, then returns [`ResolveResult::Remote`].
pub fn resolve(&mut self, cluster: &ClusterState, address: ActorAddress) -> ResolveResult {
match address {
ActorAddress::Local { actor_id } => {
self.stats.local_resolves += 1;
ResolveResult::Local { actor_id }
}
ActorAddress::Remote { node_id, actor_id } => {
self.resolve_remote(cluster, node_id, actor_id)
}
}
}
/// Resolve from raw `node_id` + `actor_id` (used when receiving a message).
///
/// Checks the cluster to verify the remote node is a known, healthy member.
/// Updates the remote actor cache on success.
pub fn resolve_remote(
&mut self,
cluster: &ClusterState,
node_id: NodeId,
actor_id: u64,
) -> ResolveResult {
// Fast path: local node.
if node_id == self.local_node || node_id == NodeId::LOCAL {
self.stats.local_resolves += 1;
return ResolveResult::Local { actor_id };
}
// Periodic eviction sweep — every 100th remote resolve, clean stale entries.
if self.stats.remote_resolves % 100 == 0 {
self.remote_cache.evict_stale();
}
// Check the cache first.
if self.remote_cache.get(node_id, actor_id).is_some() {
self.stats.cache_hits += 1;
self.stats.remote_resolves += 1;
return ResolveResult::Remote { node_id, actor_id };
}
self.stats.cache_misses += 1;
// Verify the node is in the cluster and healthy.
match cluster.get_node(node_id) {
Some(info) => {
if info.status != NodeStatus::Healthy {
self.stats.failed_resolves += 1;
return ResolveResult::Unresolvable {
reason: format!(
"node {:?} is not healthy (status: {:?})",
node_id, info.status
),
};
}
// Healthy node — cache the actor and return remote result.
self.remote_cache.put(node_id, actor_id);
self.stats.remote_resolves += 1;
ResolveResult::Remote { node_id, actor_id }
}
None => {
self.stats.failed_resolves += 1;
ResolveResult::Unresolvable {
reason: format!("node {:?} is not known in the cluster", node_id),
}
}
}
}
/// Record that we successfully sent to a remote actor.
///
/// Updates the cache and increments the per-actor message count.
pub fn record_remote_send(&mut self, node_id: NodeId, actor_id: u64) {
self.remote_cache.put(node_id, actor_id);
self.remote_cache.increment_message_count(node_id, actor_id);
}
/// Record that we received from a remote actor.
///
/// Updates the cache so we can reply efficiently.
pub fn record_remote_receive(&mut self, node_id: NodeId, actor_id: u64) {
self.remote_cache.put(node_id, actor_id);
}
/// Build a network packet for sending a message to a remote actor.
///
/// The packet carries the behavior **name** (not a behavior id, which is
/// a per-actor-table index and meaningless across nodes) plus the
/// sender's node ID so the remote node can route replies back.
/// `string_table` holds the UTF-8 content for every string-id value in
/// `payload` (see [`Packet::ActorMessage::string_table`]); pass an empty
/// vec when the payload carries no strings.
/// `content_hash` is an optional BLAKE3 hash of the expected behavior
/// implementation; `None` means no hash verification is requested.
pub fn build_packet(
&self,
target_actor: u64,
behavior_name: &str,
payload: Vec<Value>,
sender_actor: u64,
priority: MessagePriority,
string_table: Vec<String>,
content_hash: Option<[u8; 32]>,
trace_id: Option<String>,
) -> Packet {
Packet::ActorMessage {
target_actor,
behavior_name: behavior_name.to_string(),
content_hash,
payload,
string_table,
sender_actor,
sender_node: NodeId(self.local_node.0),
priority,
trace_id,
}
}
/// Parse a received network packet into a message for local delivery.
///
/// Returns `Some((target_actor_id, behavior_name, message, string_table, content_hash))`
/// if the packet is an actor message that should be delivered locally.
/// The message's `behavior_id` is left as `0` — the caller must resolve
/// `behavior_name` against the target actor's behavior table before
/// enqueueing (see [`process_network_packets`]). `string_table` carries
/// the content for any string-id values in the payload, which the caller
/// must intern into the target actor's module pool before delivery.
/// `content_hash` is an optional BLAKE3 hash for cross-node behavior
/// identity verification.
/// Returns `None` for other packet types (e.g., heartbeats, spawn
/// requests).
///
/// Also updates the remote cache with the sender information.
pub fn parse_packet(
&mut self,
packet: Packet,
) -> Option<(u64, String, Message, Vec<String>, Option<[u8; 32]>)> {
match packet {
Packet::ActorMessage {
target_actor,
behavior_name,
content_hash,
payload,
string_table,
sender_actor,
sender_node,
priority,
trace_id,
} => {
// Record the sender in our cache so we can reply.
let sender_cluster_node = NodeId(sender_node.0);
self.record_remote_receive(sender_cluster_node, sender_actor);
let msg = Message {
behavior_id: 0, // resolved from behavior_name at delivery
payload: Arc::new(payload),
sender: sender_actor,
priority,
trace_id,
};
Some((target_actor, behavior_name, msg, string_table, content_hash))
}
// Non-actor-message packets are not parsed here.
_ => None,
}
}
/// Get statistics about the resolver.
pub fn stats(&self) -> ResolverStats {
self.stats
}
/// Get a reference to the remote actor cache.
pub fn cache(&self) -> &RemoteActorCache {
&self.remote_cache
}
/// Get a mutable reference to the remote actor cache.
pub fn cache_mut(&mut self) -> &mut RemoteActorCache {
&mut self.remote_cache
}
/// Drop every cached entry for the given node.
///
/// Called when the node is declared `Failed` so subsequent sends fail
/// fast instead of stale-resolving to a dead node.
pub fn invalidate_node(&mut self, node_id: NodeId) {
self.remote_cache.remove_node(node_id);
}
/// Get the local node ID.
pub fn local_node(&self) -> NodeId {
self.local_node
}
}
// ---------------------------------------------------------------------------
// DistributedRuntime trait
// ---------------------------------------------------------------------------
/// Extension methods for [`Runtime`] that add distributed capabilities.
///
/// These methods are called by the integration layer (Stage B1) to
/// wire distributed messaging into the existing [`Runtime`].
///
/// # Example
///
/// ```ignore
/// use nulang_runtime::distributed::{ActorAddress, DistributedRuntimeImpl};
///
/// let mut runtime = Runtime::new();
/// let mut transport = crate::runtime::network::TcpTransport::bind(addr, crate::runtime::network::TlsConfig::PlaintextInsecure).unwrap();
/// let mut cluster = ClusterState::new(local_node, addr);
/// let mut resolver = AddressResolver::new(local_node);
///
/// // Send to a remote actor as if it were local
/// let target = ActorAddress::remote(remote_node, remote_actor_id);
/// DistributedRuntimeImpl::send_distributed(
/// &mut runtime, &mut transport, &cluster, &mut resolver,
/// target, "handle_msg", &[Value::int(42)],
/// );
/// ```
pub trait DistributedRuntime {
/// Send a message to an actor using a location-transparent address.
///
/// If the actor is local, delegates to the normal [`Runtime::send_message`].
/// If the actor is remote, serializes the message and sends it
/// over the network transport.
fn send_distributed(
&mut self,
transport: &mut dyn NetworkTransport,
cluster: &ClusterState,
resolver: &mut AddressResolver,
target: ActorAddress,
behavior: &str,
args: &[Value],
);
/// Process incoming network packets.
///
/// Reads all packets from the transport and delivers actor messages
/// to their target actors. Handles heartbeats by forwarding to the
/// cluster state, merges gossip, and answers spawn requests (which is
/// why the transport is taken mutably: replies go back over the wire).
fn process_network_packets(
&mut self,
transport: &mut dyn NetworkTransport,
cluster: &mut ClusterState,
resolver: &mut AddressResolver,
);
/// Spawn an actor on a specific node.
///
/// If `node` is the local node, behaves like normal spawn.
/// If `node` is remote, sends a spawn request over the network.
fn spawn_on_node(
&mut self,
transport: &mut dyn NetworkTransport,
node: NodeId,
behavior_name: &str,
initial_state: Vec<(String, Value)>,
) -> ActorAddress;
}
// ---------------------------------------------------------------------------
// Concrete implementation via wrapper struct
//
// Since Runtime is defined in mod.rs and we can't add trait impls to it
// from here without orphan rules issues, we provide a wrapper struct
// that holds references to all the components. This is the pattern
// recommended for integration (Stage B1).
// ---------------------------------------------------------------------------
/// Lightweight wrapper that holds a mutable reference to the [`Runtime`].
///
/// Used to implement the [`DistributedRuntime`] trait without consuming
/// the runtime. The other distributed components (transport, cluster,
/// resolver) are passed as parameters to the trait methods, avoiding
/// borrow-checker aliasing issues.
pub struct DistributedRuntimeImpl<'a> {
pub runtime: &'a mut Runtime,
}
impl<'a> DistributedRuntimeImpl<'a> {
/// Create a new distributed runtime wrapper.
pub fn new(runtime: &'a mut Runtime) -> Self {
DistributedRuntimeImpl { runtime }
}
}
impl<'a> DistributedRuntime for DistributedRuntimeImpl<'a> {
fn send_distributed(
&mut self,
transport: &mut dyn NetworkTransport,
cluster: &ClusterState,
resolver: &mut AddressResolver,
target: ActorAddress,
behavior: &str,
args: &[Value],
) {
send_distributed(
self.runtime,
transport,
cluster,
resolver,
target,
behavior,
args,
)
}
fn process_network_packets(
&mut self,
transport: &mut dyn NetworkTransport,
cluster: &mut ClusterState,
resolver: &mut AddressResolver,
) {
process_network_packets(self.runtime, transport, cluster, resolver)
}
fn spawn_on_node(
&mut self,
_transport: &mut dyn NetworkTransport,
node: NodeId,
_behavior_name: &str,
_initial_state: Vec<(String, Value)>,
) -> ActorAddress {
// The trait method doesn't receive cluster/resolver, so we can
// only handle local spawns here. For remote spawns, use the
// `spawn_on_node` free function which takes all components.
if node == NodeId::LOCAL {
// Local spawn would need the behavior_name and initial_state.
// This is a limitation of the trait API — use the free function.
ActorAddress::local(0)
} else {
// Cannot determine if node is local without resolver.
// Return a placeholder; callers should use the free function.
ActorAddress::remote(node, 0)
}
}
}
// ---------------------------------------------------------------------------
// Free functions (simpler integration alternative)
// ---------------------------------------------------------------------------
/// Send a message to an actor using a location-transparent address.
///
/// This is the simplest way to send a distributed message — no trait
/// objects or wrapper structs needed.
///
/// # Example
///
/// ```ignore
/// use nulang_runtime::distributed::{ActorAddress, send_distributed};
///
/// let target = ActorAddress::remote(remote_node, actor_id);
/// send_distributed(&mut runtime, &mut transport, &cluster, &mut resolver,
/// target, "handle", &[Value::int(42)]);
/// ```
pub fn send_distributed(
runtime: &mut Runtime,
transport: &mut dyn NetworkTransport,
cluster: &ClusterState,
resolver: &mut AddressResolver,
target: ActorAddress,
behavior: &str,
args: &[Value],
) {
match resolver.resolve(cluster, target) {
ResolveResult::Local { actor_id } => {
runtime.send_message(actor_id, behavior, args);
}
ResolveResult::Remote { node_id, actor_id } => {
// Remember the bare id → node mapping so a LATER bare actor-ref
// Value (no node id) can route here too (RFC-0007).
crate::runtime::distribution::record_remote_ref(runtime, node_id, actor_id);
// String payloads must cross the wire by CONTENT: a bare string
// id indexes the sender's module constant pool and means nothing
// (or the wrong thing) on the receiving node. Resolve each
// string arg against the sender's pool and carry the contents
// in the packet's string table.
let (payload, string_table) = match resolve_wire_strings(runtime, args) {
Some(resolved) => resolved,
None => {
warn!(
"nulang-net: dropping message to actor {} on node {:?}: string payload cannot be resolved to content (no sender module context)",
actor_id, node_id
);
let sender = runtime.current_actor.unwrap_or(0);
notify_delivery_failed(runtime, sender, "string payload unresolvable");
return;
}
};
// Remote sends carry the behavior name and an optional content
// hash; the receiving node resolves the name and MAY verify the
// hash against its own behavior table on delivery.
let content_hash = try_lookup_content_hash(runtime, behavior);
// Carry the current handler's trace span across the wire so the
// remote side continues the same causal chain. The current span
// (not a synthetic child) crosses because `traceparent` has no
// parent field — the receiver creates its own child span.
let trace_id = runtime.current_trace.as_ref().map(|t| t.to_traceparent());
let packet = resolver.build_packet(
actor_id,
behavior,
payload,
runtime.current_actor.unwrap_or(0),
MessagePriority::Normal,
string_table,
content_hash,
trace_id,
);
if let Some(node_info) = cluster.get_node(node_id) {
let net_node_id = NodeId(node_id.0);
transport.send(net_node_id, node_info.address, packet);
} else {
// The node resolved as remote but is no longer in the
// membership table (it left between resolve and send). Log
// the drop rather than losing the message silently.
warn!(
"nulang-net: dropping message to actor {} on node {:?}: node missing from cluster membership",
actor_id, node_id
);
let sender = runtime.current_actor.unwrap_or(0);
notify_delivery_failed(runtime, sender, "target node left cluster");
}
}
ResolveResult::Unresolvable { reason } => {
warn!("nulang-net: dropping message to {:?}: {}", target, reason);
let sender = runtime.current_actor.unwrap_or(0);
notify_delivery_failed(runtime, sender, &reason);
}
}
}
/// Notify a sender that their message could not be delivered.
///
/// Delivers a system message (behavior 0) to the sender actor with a
/// failure code in the payload: `[failure_code: Int, _reserved: Nil]`.
/// Codes: 0=unresolvable, 1=node left cluster, 2=string payload unresolvable,
/// 3=string intern failed on receiver, 4=target actor not found, 5=unknown.
/// Non-existent senders (id 0) are silently skipped.
pub(crate) fn notify_delivery_failed(runtime: &mut Runtime, sender_id: u64, reason: &str) {
if sender_id == 0 {
return;
}
if !runtime.actors.get(&sender_id).is_some() {
return;
}
let code = delivery_failure_code(reason);
let fail_payload = vec![Value::int(code), Value::nil()];
runtime.send_message_by_id(sender_id, 0, &fail_payload);
}
/// Map a delivery-failure reason string to an integer code.
fn delivery_failure_code(reason: &str) -> i64 {
match reason {
"unresolvable" => 0,
"target node left cluster" => 1,
"string payload unresolvable" => 2,
"string intern failed on receiver" => 3,
"target actor not found" => 4,
_ => 5,
}
}
/// Map the wire reason tag (from [`ExitReason::tag`]) back to an
/// [`ExitReason`]. The wire carries only the tag string; the original
/// message/description payload is not transmitted.
fn exit_reason_from_tag(tag: &str) -> ExitReason {
match tag {
"normal" => ExitReason::Normal,
"kill" => ExitReason::Kill,
"killed" => ExitReason::Killed,
"shutdown" => ExitReason::Shutdown(None),
"noconnection" => ExitReason::NoConnection,
"error" => ExitReason::Error("remote exit".to_string()),
_ => ExitReason::Custom(tag.to_string()),
}
}
/// Verify that the target actor's behavior at the given index has a matching
/// content hash. Returns `true` if verification passes (or if the local
/// behavior entry has no hash — backward compatibility preserves nodes whose
/// modules were compiled before content hashing was added).
fn verify_behavior_hash(
runtime: &Runtime,
target_actor: u64,
behavior_id: u16,
sender_hash: &[u8; 32],
) -> bool {
let actor = match runtime.actors.get(&target_actor) {
Some(a) => a,
None => return false,
};
// Check the per-actor behavior table first (native handler).
if actor.behavior_table.get(behavior_id as usize).is_some() {
return true; // Native handlers have no hash — accept.
}
let module = match &actor.bytecode_module {
Some(m) => m,
None => return false,
};
let entry = match module.behaviors.get(behavior_id as usize) {
Some(e) => e,
None => return false,
};
match &entry.content_hash {
Some(local_hash) => local_hash == sender_hash,
None => true, // No local hash — backward compatible, accept.
}
}
/// Try to look up the content hash for a behavior name in the current
/// actor's bytecode module. Returns `None` if no current actor context,
/// no bytecode module, or the behavior has no content hash.
///
/// This is a best-effort lookup: the sender's module may not define the
/// target behavior (cross-module sends), in which case no hash is
/// transmitted and no receiver-side verification is performed.
fn try_lookup_content_hash(runtime: &Runtime, behavior_name: &str) -> Option<[u8; 32]> {
let actor_id = runtime.current_actor?;
let actor = runtime.actors.get(&actor_id)?;
let module = actor.bytecode_module.as_ref()?;
let suffix = format!(".{}", behavior_name);
module
.behaviors
.iter()
.find(|b| b.name == behavior_name || b.name.ends_with(&suffix))
.and_then(|b| b.content_hash)
}
/// Process all incoming network packets and deliver actor messages.
///
/// Heartbeats are forwarded to the cluster state, gossip is merged into
/// the membership table, actor messages are parsed and delivered to the
/// target actor's mailbox, and spawn requests are answered with a
/// [`Packet::SpawnResponse`] (hence the mutable transport).
///
/// Send a transport-level acknowledgement for a successfully processed packet.
fn ack_packet(
transport: &mut dyn NetworkTransport,
cluster: &ClusterState,
from_node: NodeId,
seq: u64,
) {
let addr = cluster
.get_node(from_node)
.map(|n| n.address)
.or_else(|| transport.connection_addr(from_node));
if let Some(addr) = addr {
transport.send(from_node, addr, Packet::Ack { packet_seq: seq });
}
}
pub fn process_network_packets(
runtime: &mut Runtime,
transport: &mut dyn NetworkTransport,
cluster: &mut ClusterState,
resolver: &mut AddressResolver,
) {
let packets = transport.receive();
for incoming in packets {
match incoming.packet {
Packet::Heartbeat { node_id, .. } => {
let cluster_node_id = NodeId(node_id.0);
// The IncomingPacket doesn't carry the sender's address
// directly, so prefer the address already recorded in the
// membership table. For a previously-unknown node (e.g. a
// fresh joiner's first heartbeat to its seed) fall back to
// the transport's connection table — this is the discovery
// path by which a seed first learns about a joiner.
let known_addr = cluster
.get_node(cluster_node_id)
.map(|info| info.address)
.or_else(|| transport.connection_addr(cluster_node_id));
if let Some(addr) = known_addr {
cluster.handle_heartbeat(cluster_node_id, addr);
}
ack_packet(transport, cluster, incoming.from_node, incoming.seq);
}
Packet::Gossip { members } => {
// Merge the sender's membership view into ours; higher
// incarnation numbers win (see ClusterState::merge_membership).
// Each entry carries its own listen address, so no extra
// connection bookkeeping is needed for the relayed nodes.
// The sender's self-entry is authoritative: it overrides a
// heartbeat-discovered ephemeral source-port address for
// the sending node (see `merge_membership_from_sender`).
cluster.merge_membership_from_sender(members, incoming.from_node);
ack_packet(transport, cluster, incoming.from_node, incoming.seq);
}
Packet::SpawnRequest {
request_id,
behavior_name,
initial_state,
bytecode: _,
content_hash: _,
} => {
// MVP: remote spawn only supports behaviors the receiving
// runtime has explicitly registered via
// `Runtime::register_spawnable_behavior`. An unknown name
// replies `success: false` — the tolerated-no-crash
// counterpart of local send's unknown-behavior fallback.
let handler = runtime.spawnable_behaviors.get(&behavior_name).copied();
let (actor_id, success) = match handler {
Some(handler) => {
let id = runtime.spawn_actor(Box::new(move || initial_state));
if let Some(actor) = runtime.actors.get_mut(&id) {
actor.register_behavior(behavior_name, handler);
}
(id, true)