forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.rs
More file actions
2641 lines (2397 loc) · 96.2 KB
/
Copy pathnetwork.rs
File metadata and controls
2641 lines (2397 loc) · 96.2 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
//! Network transport layer for Nulang's distributed actor runtime.
//!
//! This module enables actors on different machines to send messages to each
//! other transparently over TCP. It defines a binary wire protocol, manages
//! connection pooling, and runs background threads for asynchronous I/O.
//!
//! # Architecture
//!
//! Each node runs a [`NetworkTransport`] that:
//! 1. Listens on a TCP socket for incoming connections from peer nodes.
//! 2. Maintains a pool of active [`TcpConnection`]s to remote nodes.
//! 3. Receives [`Packet`]s from peers and exposes them via [`receive`][NetworkTransport::receive].
//! 4. Sends [`Packet`]s to peers via an internal outgoing queue.
//!
//! # Wire Protocol
//!
//! Every packet on the wire is length-prefixed:
//! ```text
//! [0..4] message length (u32, big-endian, includes this header)
//! [4..8] magic: "NUL0"
//! [8] packet type discriminant
//! [9..17] sequence number (u64, big-endian)
//! [17..] type-specific payload
//! ```
//!
//! A 16-byte versioned handshake is exchanged immediately after the TCP
//! connection is established, *before* either side starts sending framed
//! packets: `[magic "NUL0"][version u32][node_id u64]`. A peer whose wire
//! version does not match [`crate::format::constants::WIRE_VERSION`] is
//! refused, never silently reinterpreted. See `SPEC2.md` §"Format Stability".
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
// ---------------------------------------------------------------------------
// Imports from the rest of the crate
// ---------------------------------------------------------------------------
use super::cluster::{NodeGossip, NodeStatus};
use super::crdt_manager::{CrdtDeltaOp, CrdtOp};
use super::MessagePriority;
use super::NodeId;
use crate::vm::Value;
use tracing::warn;
// ---------------------------------------------------------------------------
// TLS configuration
// ---------------------------------------------------------------------------
/// TLS configuration for the NUL0 wire protocol.
///
/// When `Some`, every TCP connection is upgraded to TLS immediately after
/// the TCP connect/accept but *before* the NUL0 versioned handshake.
///
/// `SelfSigned` uses `rcgen` to generate a self-signed certificate;
/// this is suitable for development and testing.
#[derive(Clone)]
pub enum TlsConfig {
/// Use a self-signed certificate generated via rcgen.
SelfSigned,
}
impl TlsConfig {
fn server_config(&self) -> io::Result<rustls::ServerConfig> {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
let cert_der =
rustls::pki_types::CertificateDer::from(cert.cert.der().clone().into_owned());
let key_der = rustls::pki_types::PrivateKeyDer::from(
rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()),
);
rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![cert_der], key_der)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
fn client_config(&self) -> io::Result<rustls::ClientConfig> {
use rustls::client::danger::{
HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,
};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
#[derive(Debug)]
struct NoVerification;
impl ServerCertVerifier for NoVerification {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
vec![
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::ECDSA_NISTP256_SHA256,
SignatureScheme::ED25519,
]
}
}
Ok(rustls::ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(std::sync::Arc::new(NoVerification))
.with_no_client_auth())
}
}
// ---------------------------------------------------------------------------
// TransportStream — abstracts over raw TCP and TLS-wrapped streams
// ---------------------------------------------------------------------------
/// A duplex transport stream that can be either a plain `TcpStream` or a
/// TLS-wrapped connection. TLS streams are shared behind `Arc<Mutex<>>`
/// because `rustls::StreamOwned` cannot be cloned the way `TcpStream` can.
pub(crate) enum TransportStream {
Raw(TcpStream),
TlsServer(
std::sync::Arc<std::sync::Mutex<rustls::StreamOwned<rustls::ServerConnection, TcpStream>>>,
),
TlsClient(
std::sync::Arc<std::sync::Mutex<rustls::StreamOwned<rustls::ClientConnection, TcpStream>>>,
),
}
impl TransportStream {
/// Create a clone suitable for the reader half of a duplex connection.
/// For raw TCP this duplicates the file descriptor; for TLS this clones
/// the `Arc` so reader and writer share the same TLS session.
fn try_clone(&self) -> io::Result<TransportStream> {
match self {
TransportStream::Raw(s) => Ok(TransportStream::Raw(s.try_clone()?)),
TransportStream::TlsServer(s) => Ok(TransportStream::TlsServer(s.clone())),
TransportStream::TlsClient(s) => Ok(TransportStream::TlsClient(s.clone())),
}
}
fn shutdown(&self) -> io::Result<()> {
match self {
TransportStream::Raw(s) => s.shutdown(std::net::Shutdown::Both),
TransportStream::TlsServer(s) => {
let mut locked = s.lock().unwrap();
let _ = locked.conn.send_close_notify();
locked.get_ref().shutdown(std::net::Shutdown::Both)
}
TransportStream::TlsClient(s) => {
let mut locked = s.lock().unwrap();
let _ = locked.conn.send_close_notify();
locked.get_ref().shutdown(std::net::Shutdown::Both)
}
}
}
}
impl Read for TransportStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
TransportStream::Raw(s) => s.read(buf),
TransportStream::TlsServer(s) => s.lock().unwrap().read(buf),
TransportStream::TlsClient(s) => s.lock().unwrap().read(buf),
}
}
}
impl Write for TransportStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self {
TransportStream::Raw(s) => s.write(buf),
TransportStream::TlsServer(s) => s.lock().unwrap().write(buf),
TransportStream::TlsClient(s) => s.lock().unwrap().write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
TransportStream::Raw(s) => s.flush(),
TransportStream::TlsServer(s) => s.lock().unwrap().flush(),
TransportStream::TlsClient(s) => s.lock().unwrap().flush(),
}
}
}
fn tls_wrap_server(tcp: TcpStream, config: &TlsConfig) -> io::Result<TransportStream> {
let cfg = config.server_config()?;
let conn = rustls::ServerConnection::new(std::sync::Arc::new(cfg))
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(TransportStream::TlsServer(std::sync::Arc::new(
std::sync::Mutex::new(rustls::StreamOwned::new(conn, tcp)),
)))
}
fn tls_wrap_client(tcp: TcpStream, config: &TlsConfig) -> io::Result<TransportStream> {
let cfg = config.client_config()?;
let name = rustls::pki_types::ServerName::try_from("localhost")
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let conn = rustls::ClientConnection::new(std::sync::Arc::new(cfg), name)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(TransportStream::TlsClient(std::sync::Arc::new(
std::sync::Mutex::new(rustls::StreamOwned::new(conn, tcp)),
)))
}
// ---------------------------------------------------------------------------
// TransportAddr — network address for TCP or Unix domain sockets
// ---------------------------------------------------------------------------
/// Address for the NUL0 protocol. TCP is the default; Unix domain sockets
/// enable same-host eBPF sockmap redirection in NLC deployments.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransportAddr {
Tcp(SocketAddr),
#[cfg(unix)]
Unix(std::path::PathBuf),
}
impl TransportAddr {
pub fn tcp(addr: SocketAddr) -> Self {
TransportAddr::Tcp(addr)
}
#[cfg(unix)]
pub fn unix(path: impl Into<std::path::PathBuf>) -> Self {
TransportAddr::Unix(path.into())
}
}
impl std::fmt::Display for TransportAddr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TransportAddr::Tcp(a) => write!(f, "{}", a),
#[cfg(unix)]
TransportAddr::Unix(p) => write!(f, "unix:{}", p.display()),
}
}
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Magic bytes that prefix every packet payload (after the length header).
/// The single source of truth is [`crate::format::constants::WIRE_MAGIC`];
/// this re-exports it for the packet framer.
const MAGIC: &[u8] = &crate::format::constants::WIRE_MAGIC;
/// Total size of the fixed packet header: 4 magic + 1 type + 8 seq.
const PACKET_HEADER_LEN: usize = 13;
/// TCP read / write timeout applied to every connection.
const IO_TIMEOUT: Duration = Duration::from_secs(30);
/// How long the sender thread waits on the outgoing channel before
/// re-checking the shutdown flag.
const CHANNEL_RECV_TIMEOUT: Duration = Duration::from_millis(100);
// ---------------------------------------------------------------------------
// Versioned handshake helpers (magic + version + node_id = 16 bytes)
// ---------------------------------------------------------------------------
/// Write the 16-byte NUL0 versioned handshake to a stream.
fn write_handshake<W: Write>(w: &mut W, node_id: NodeId) -> io::Result<()> {
w.write_all(&crate::format::constants::WIRE_MAGIC)?;
w.write_all(&crate::format::constants::WIRE_VERSION.to_be_bytes())?;
w.write_all(&node_id.0.to_be_bytes())?;
w.flush()
}
/// Read the 16-byte NUL0 versioned handshake from a stream, validating the
/// magic and the wire protocol version. Returns the peer's node id. A
/// mismatched magic or version is a hard error: the connection is refused
/// rather than the peer's packets being reinterpreted under the wrong layout.
fn read_handshake<R: Read>(r: &mut R) -> io::Result<NodeId> {
let mut buf = [0u8; crate::format::constants::WIRE_HANDSHAKE_LEN];
r.read_exact(&mut buf)?;
if &buf[0..4] != crate::format::constants::WIRE_MAGIC {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"wire handshake: bad magic, expected {:?}, got {:?}",
crate::format::constants::WIRE_MAGIC,
&buf[0..4]
),
));
}
let version = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
if version != crate::format::constants::WIRE_VERSION {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"wire handshake: peer speaks wire version {version}, this runtime speaks {}",
crate::format::constants::WIRE_VERSION
),
));
}
let node_id = NodeId(u64::from_be_bytes([
buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15],
]));
Ok(node_id)
}
/// Maximum length (in bytes) of a single packet payload we are willing to
/// deserialize — a simple DoS protection.
const MAX_PACKET_LEN: u32 = 16 * 1024 * 1024; // 16 MiB
/// Capacity of the bounded internal channels.
const CHANNEL_CAPACITY: usize = 1024;
// Packet type discriminants.
const TYPE_ACTOR_MESSAGE: u8 = 0;
const TYPE_HEARTBEAT: u8 = 1;
const TYPE_ACK: u8 = 2;
const TYPE_SPAWN_REQUEST: u8 = 3;
const TYPE_SPAWN_RESPONSE: u8 = 4;
const TYPE_CRDT_SYNC: u8 = 5;
const TYPE_GOSSIP: u8 = 6;
const TYPE_CRDT_DELTA_SYNC: u8 = 7;
const TYPE_FETCH_BEHAVIOR_REQUEST: u8 = 8;
const TYPE_FETCH_BEHAVIOR_RESPONSE: u8 = 9;
// ---------------------------------------------------------------------------
// NodeId
// ---------------------------------------------------------------------------
// NodeId is imported from super::cluster::NodeId
// ---------------------------------------------------------------------------
// Packet
// ---------------------------------------------------------------------------
/// A packet sent over the network between Nulang nodes.
#[derive(Debug, Clone, PartialEq)]
pub enum Packet {
/// Send a message to an actor on the target node.
///
/// The behavior is identified by **name**, not by id: behavior ids are
/// per-actor-table indices and are meaningless across nodes. The
/// receiving node resolves the name against the target actor's behavior
/// table (the same rule local sends use in `Runtime::behavior_id_for`).
ActorMessage {
target_actor: u64,
behavior_name: String,
/// Optional BLAKE3 content hash of the expected behavior implementation.
/// Set by the sender if the behavior has a known content hash in the
/// sender's module; the receiver MAY verify it against the local
/// behavior table during delivery (see process_network_packets).
content_hash: Option<[u8; 32]>,
payload: Vec<Value>,
/// UTF-8 content for every `Value::string(id)` in `payload`: on the
/// wire a string-id value indexes **this table**, never the sender's
/// or receiver's constant pool (a pool id is meaningless across
/// nodes). The sending runtime populates the table from the sender's
/// module pool (`distributed::resolve_wire_strings`); the receiving
/// runtime interns each entry into the target actor's module pool
/// (`distributed::intern_wire_strings`).
string_table: Vec<String>,
sender_actor: u64,
sender_node: NodeId,
priority: MessagePriority,
},
/// Heartbeat / ping between nodes.
Heartbeat {
node_id: NodeId,
timestamp: u64, // millis since epoch
},
/// Acknowledge receipt of a packet.
Ack { packet_seq: u64 },
/// Request to spawn an actor remotely.
SpawnRequest {
request_id: u64,
behavior_name: String,
/// Optional BLAKE3 content hash for cross-node behavior identity
/// verification. The receiver MAY check this against the local
/// `spawnable_behaviors` entry.
content_hash: Option<[u8; 32]>,
initial_state: Vec<(String, Value)>,
bytecode: Option<Vec<u8>>,
},
/// Response to a spawn request.
SpawnResponse {
request_id: u64,
actor_id: u64,
success: bool,
},
/// CRDT synchronization packet.
CrdtSync { ops: Vec<CrdtOp> },
/// Delta-state CRDT synchronization packet.
///
/// Each op is tagged as a delta (changes since the sender's last sync)
/// or a full-state snapshot — see [`CrdtDeltaOp`]. Receivers merge
/// deltas into entries they already hold and apply full-state ops like
/// [`CrdtSync`](Packet::CrdtSync). The full-state `CrdtSync` packet
/// remains available as the join/reset fallback.
CrdtDeltaSync { ops: Vec<CrdtDeltaOp> },
/// Cluster membership gossip.
///
/// Carries the sender's (compact) membership view; the receiver merges
/// it via [`ClusterState::merge_membership`](crate::runtime::cluster::ClusterState::merge_membership),
/// where higher incarnation numbers win. This is what gives membership
/// transitive propagation: a node relays what it knows, so a chain of
/// pairwise seeds still converges to a full mesh.
Gossip { members: Vec<NodeGossip> },
/// Request bytecode for a behavior identified by its BLAKE3 content hash.
///
/// Sent by a node that receives a message for a behavior it doesn't have.
/// The sender replies with `FetchBehaviorResponse` containing the compiled
/// bytecode (as an NBC blob — see `src/format/nbc.rs`).
FetchBehaviorRequest {
/// The BLAKE3 content hash of the behavior being requested.
content_hash: [u8; 32],
},
/// Response to a `FetchBehaviorRequest`, carrying the compiled bytecode.
FetchBehaviorResponse {
/// Echoes the content hash from the request for correlation.
content_hash: [u8; 32],
/// Behavior name (for the receiver's behavior table).
behavior_name: String,
/// Compiled NBC bytecode blob. `None` if the requested behavior
/// is not known to the responding node.
nbc_bytes: Option<Vec<u8>>,
},
}
impl Packet {
// ------------------------------------------------------------------
// Public serialization API
// ------------------------------------------------------------------
/// Serialize the packet into bytes **without** the outer length prefix.
///
/// The returned vector starts with [`MAGIC`], followed by the type
/// discriminant, sequence number, and type-specific payload.
pub fn to_bytes(&self, seq: u64) -> Vec<u8> {
let mut buf = Vec::with_capacity(256);
// Magic
buf.extend_from_slice(MAGIC);
// Type discriminant
buf.push(self.discriminant());
// Sequence number (big-endian)
buf.extend_from_slice(&seq.to_be_bytes());
// Payload
self.write_payload(&mut buf);
buf
}
/// Deserialize a packet from bytes (starting at the magic bytes).
///
/// Returns `None` if the bytes are malformed or the discriminant is
/// unknown.
pub fn from_bytes(bytes: &[u8]) -> Option<(u64, Self)> {
if bytes.len() < PACKET_HEADER_LEN {
return None;
}
if &bytes[0..4] != MAGIC {
return None;
}
let discriminant = bytes[4];
let seq = u64::from_be_bytes([
bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12],
]);
let payload = &bytes[PACKET_HEADER_LEN..];
let packet = match discriminant {
TYPE_ACTOR_MESSAGE => Self::read_actor_message(payload)?,
TYPE_HEARTBEAT => Self::read_heartbeat(payload)?,
TYPE_ACK => Self::read_ack(payload)?,
TYPE_SPAWN_REQUEST => Self::read_spawn_request(payload)?,
TYPE_SPAWN_RESPONSE => Self::read_spawn_response(payload)?,
TYPE_CRDT_SYNC => Self::read_crdt_sync(payload)?,
TYPE_CRDT_DELTA_SYNC => Self::read_crdt_delta_sync(payload)?,
TYPE_GOSSIP => Self::read_gossip(payload)?,
TYPE_FETCH_BEHAVIOR_REQUEST => Self::read_fetch_behavior_request(payload)?,
TYPE_FETCH_BEHAVIOR_RESPONSE => Self::read_fetch_behavior_response(payload)?,
_ => return None,
};
Some((seq, packet))
}
// ------------------------------------------------------------------
// Internal helpers
fn discriminant(&self) -> u8 {
match self {
Packet::ActorMessage { .. } => TYPE_ACTOR_MESSAGE,
Packet::Heartbeat { .. } => TYPE_HEARTBEAT,
Packet::Ack { .. } => TYPE_ACK,
Packet::SpawnRequest { .. } => TYPE_SPAWN_REQUEST,
Packet::SpawnResponse { .. } => TYPE_SPAWN_RESPONSE,
Packet::CrdtSync { .. } => TYPE_CRDT_SYNC,
Packet::CrdtDeltaSync { .. } => TYPE_CRDT_DELTA_SYNC,
Packet::Gossip { .. } => TYPE_GOSSIP,
Packet::FetchBehaviorRequest { .. } => TYPE_FETCH_BEHAVIOR_REQUEST,
Packet::FetchBehaviorResponse { .. } => TYPE_FETCH_BEHAVIOR_RESPONSE,
}
}
fn write_payload(&self, buf: &mut Vec<u8>) {
match self {
Packet::ActorMessage {
target_actor,
behavior_name,
content_hash,
payload,
string_table,
sender_actor,
sender_node,
priority,
} => {
buf.extend_from_slice(&target_actor.to_be_bytes());
write_string(buf, behavior_name);
// content_hash: 1 byte flag + optional 32 bytes
write_optional_hash(buf, content_hash);
buf.extend_from_slice(&sender_actor.to_be_bytes());
buf.extend_from_slice(&sender_node.0.to_be_bytes());
buf.push(*priority as u8);
buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
for v in payload {
write_value(buf, v);
}
// String contents travel after the payload values; the
// string-id values above index this table.
buf.extend_from_slice(&(string_table.len() as u32).to_be_bytes());
for s in string_table {
write_string(buf, s);
}
}
Packet::Heartbeat { node_id, timestamp } => {
buf.extend_from_slice(&node_id.0.to_be_bytes());
buf.extend_from_slice(×tamp.to_be_bytes());
}
Packet::Ack { packet_seq } => {
buf.extend_from_slice(&packet_seq.to_be_bytes());
}
Packet::SpawnRequest {
request_id,
behavior_name,
content_hash,
initial_state,
bytecode,
} => {
buf.extend_from_slice(&request_id.to_be_bytes());
write_string(buf, behavior_name);
// content_hash: 1 byte flag + optional 32 bytes
write_optional_hash(buf, content_hash);
buf.extend_from_slice(&(initial_state.len() as u32).to_be_bytes());
for (key, value) in initial_state {
write_string(buf, key);
write_value(buf, value);
}
// Serialize optional bytecode: 0 length = None.
match bytecode {
Some(bytes) => {
buf.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
buf.extend_from_slice(bytes);
}
None => {
buf.extend_from_slice(&0u32.to_be_bytes());
}
}
}
Packet::SpawnResponse {
request_id,
actor_id,
success,
} => {
buf.extend_from_slice(&request_id.to_be_bytes());
buf.extend_from_slice(&actor_id.to_be_bytes());
buf.push(if *success { 1 } else { 0 });
}
Packet::CrdtSync { ops } => {
buf.extend_from_slice(&(ops.len() as u32).to_be_bytes());
for op in ops {
buf.extend_from_slice(&op.to_bytes());
}
}
Packet::CrdtDeltaSync { ops } => {
buf.extend_from_slice(&(ops.len() as u32).to_be_bytes());
for op in ops {
buf.extend_from_slice(&op.to_bytes());
}
}
Packet::Gossip { members } => {
buf.extend_from_slice(&(members.len() as u32).to_be_bytes());
for m in members {
buf.extend_from_slice(&m.node_id.0.to_be_bytes());
write_addr(buf, &m.address);
buf.push(status_to_u8(m.status));
buf.extend_from_slice(&m.incarnation.to_be_bytes());
}
}
Packet::FetchBehaviorRequest { content_hash } => {
buf.extend_from_slice(content_hash);
}
Packet::FetchBehaviorResponse {
content_hash,
behavior_name,
nbc_bytes,
} => {
buf.extend_from_slice(content_hash);
write_string(buf, behavior_name);
match nbc_bytes {
Some(bytes) => {
buf.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
buf.extend_from_slice(bytes);
}
None => {
buf.extend_from_slice(&0u32.to_be_bytes());
}
}
}
}
}
// --- Deserialisation helpers for each variant ---------------------
fn read_actor_message(payload: &[u8]) -> Option<Self> {
if payload.len() < 12 {
return None;
}
let target_actor = read_u64(payload, 0)?;
let (behavior_name, name_len) = read_string(payload, 8)?;
let mut offset = 8usize.checked_add(name_len)?;
// content_hash: 1 byte flag + optional 32 bytes
let (content_hash, hash_consumed) = read_optional_hash(payload, offset)?;
offset = offset.checked_add(hash_consumed)?;
if payload.len() < offset + 21 {
return None;
}
let sender_actor = read_u64(payload, offset)?;
let sender_node = NodeId(read_u64(payload, offset + 8)?);
let priority = match payload.get(offset + 16).copied()? {
0 => MessagePriority::System,
1 => MessagePriority::Normal,
2 => MessagePriority::Bulk,
_ => return None,
};
let count = read_u32(payload, offset + 17)? as usize;
offset = offset.checked_add(21)?;
let mut values = Vec::with_capacity(count.min(1024));
for _ in 0..count {
let (v, consumed) = read_value(payload, offset)?;
values.push(v);
offset = offset.checked_add(consumed)?;
if offset > payload.len() {
return None;
}
}
// String table: contents for the payload's string-id values.
let table_count = read_u32(payload, offset)? as usize;
offset = offset.checked_add(4)?;
let mut string_table = Vec::with_capacity(table_count.min(1024));
for _ in 0..table_count {
let (s, consumed) = read_string(payload, offset)?;
string_table.push(s);
offset = offset.checked_add(consumed)?;
}
Some(Packet::ActorMessage {
target_actor,
behavior_name,
content_hash,
payload: values,
string_table,
sender_actor,
sender_node,
priority,
})
}
fn read_heartbeat(payload: &[u8]) -> Option<Self> {
if payload.len() < 16 {
return None;
}
let node_id = NodeId(read_u64(payload, 0)?);
let timestamp = read_u64(payload, 8)?;
Some(Packet::Heartbeat { node_id, timestamp })
}
fn read_ack(payload: &[u8]) -> Option<Self> {
let packet_seq = read_u64(payload, 0)?;
Some(Packet::Ack { packet_seq })
}
fn read_spawn_request(payload: &[u8]) -> Option<Self> {
if payload.len() < 8 {
return None;
}
let request_id = read_u64(payload, 0)?;
let (behavior_name, consumed) = read_string(payload, 8)?;
let mut offset = 8 + consumed;
// content_hash: 1 byte flag + optional 32 bytes
let (content_hash, hash_consumed) = read_optional_hash(payload, offset)?;
offset = offset.checked_add(hash_consumed)?;
let count = read_u32(payload, offset)? as usize;
offset += 4;
let mut initial_state = Vec::with_capacity(count.min(256));
for _ in 0..count {
let (key, consumed_key) = read_string(payload, offset)?;
offset = offset.checked_add(consumed_key)?;
let (value, consumed_val) = read_value(payload, offset)?;
offset = offset.checked_add(consumed_val)?;
initial_state.push((key, value));
}
// Deserialize optional bytecode: 0 length = None.
let bytecode_len = read_u32(payload, offset)? as usize;
offset += 4;
let bytecode = if bytecode_len > 0 {
if offset + bytecode_len > payload.len() {
return None;
}
Some(payload[offset..offset + bytecode_len].to_vec())
} else {
None
};
Some(Packet::SpawnRequest {
request_id,
behavior_name,
content_hash,
initial_state,
bytecode,
})
}
fn read_spawn_response(payload: &[u8]) -> Option<Self> {
if payload.len() < 17 {
return None;
}
let request_id = read_u64(payload, 0)?;
let actor_id = read_u64(payload, 8)?;
let success = payload.get(16).copied()? != 0;
Some(Packet::SpawnResponse {
request_id,
actor_id,
success,
})
}
fn read_crdt_sync(payload: &[u8]) -> Option<Self> {
if payload.len() < 4 {
return None;
}
let count = read_u32(payload, 0)? as usize;
let mut offset = 4usize;
let mut ops = Vec::with_capacity(count.min(1024));
for _ in 0..count {
if offset >= payload.len() {
return None;
}
// Each CrdtOp: [id:u64][type:u8][len:u32][payload]
if offset + 13 > payload.len() {
return None;
}
// Parse id + type + len manually to compute op byte length
let op_payload_len = u32::from_be_bytes([
payload[offset + 9],
payload[offset + 10],
payload[offset + 11],
payload[offset + 12],
]) as usize;
let total_op_len = 13 + op_payload_len;
if offset + total_op_len > payload.len() {
return None;
}
let op = CrdtOp::from_bytes(&payload[offset..offset + total_op_len])?;
offset += total_op_len;
ops.push(op);
}
Some(Packet::CrdtSync { ops })
}
fn read_crdt_delta_sync(payload: &[u8]) -> Option<Self> {
if payload.len() < 4 {
return None;
}
let count = read_u32(payload, 0)? as usize;
let mut offset = 4usize;
let mut ops = Vec::with_capacity(count.min(1024));
for _ in 0..count {
// Each CrdtDeltaOp: [is_delta:u8][id:u64][type:u8][len:u32][payload]
if offset + 14 > payload.len() {
return None;
}
// Parse flag + id + type + len manually to compute op byte length
let op_payload_len = u32::from_be_bytes([
payload[offset + 10],
payload[offset + 11],
payload[offset + 12],
payload[offset + 13],
]) as usize;
let total_op_len = 14 + op_payload_len;
if offset + total_op_len > payload.len() {
return None;
}
let op = CrdtDeltaOp::from_bytes(&payload[offset..offset + total_op_len])?;
offset += total_op_len;
ops.push(op);
}
Some(Packet::CrdtDeltaSync { ops })
}
fn read_gossip(payload: &[u8]) -> Option<Self> {
if payload.len() < 4 {
return None;
}
let count = read_u32(payload, 0)? as usize;
let mut offset = 4usize;
let mut members = Vec::with_capacity(count.min(1024));
for _ in 0..count {
// Each entry: [node_id:u64][addr][status:u8][incarnation:u64]
if offset + 8 > payload.len() {
return None;
}
let node_id = NodeId(read_u64(payload, offset)?);
offset += 8;
let (address, consumed) = read_addr(payload, offset)?;
offset = offset.checked_add(consumed)?;
if offset + 9 > payload.len() {
return None;
}
let status = status_from_u8(*payload.get(offset)?)?;
offset += 1;
let incarnation = read_u64(payload, offset)?;
offset += 8;
members.push(NodeGossip {
node_id,
address,
status,
incarnation,
});
}
Some(Packet::Gossip { members })
}
fn read_fetch_behavior_request(payload: &[u8]) -> Option<Self> {
if payload.len() < 32 {
return None;
}
let mut content_hash = [0u8; 32];
content_hash.copy_from_slice(&payload[..32]);
Some(Packet::FetchBehaviorRequest { content_hash })
}
fn read_fetch_behavior_response(payload: &[u8]) -> Option<Self> {
if payload.len() < 34 {
return None;
}
let mut content_hash = [0u8; 32];
content_hash.copy_from_slice(&payload[..32]);
let (behavior_name, name_len) = read_string(payload, 32)?;
let off = 32 + name_len;
if payload.len() < off + 4 {
return None;
}
let byte_len = u32::from_be_bytes([
payload[off],
payload[off + 1],
payload[off + 2],
payload[off + 3],
]) as usize;
let nbc_bytes = if byte_len == 0 {
None
} else {
let start = off + 4;
if payload.len() < start + byte_len {
return None;
}
Some(payload[start..start + byte_len].to_vec())
};
Some(Packet::FetchBehaviorResponse {
content_hash,
behavior_name,
nbc_bytes,
})
}
}
// ---------------------------------------------------------------------------
// Value (de)serialization helpers
// ---------------------------------------------------------------------------
// Type tags for Value variants.
const VAL_INT: u8 = 0;
const VAL_FLOAT: u8 = 1;
const VAL_BOOL: u8 = 2;
const VAL_STRING: u8 = 3;
const VAL_UNIT: u8 = 4;
const VAL_NIL: u8 = 5;
/// Write a [`Value`] into `buf`.
fn write_value(buf: &mut Vec<u8>, v: &Value) {
if let Some(i) = v.as_int() {
buf.push(VAL_INT);
buf.extend_from_slice(&i.to_be_bytes());
} else if let Some(f) = v.as_float() {
buf.push(VAL_FLOAT);
buf.extend_from_slice(&f.to_be_bytes());
} else if let Some(b) = v.as_bool() {
buf.push(VAL_BOOL);
buf.push(if b { 1 } else { 0 });
} else if let Some(id) = v.as_string_id() {
// The id indexes the enclosing packet's string table, not any
// constant pool — see `Packet::ActorMessage::string_table`.
buf.push(VAL_STRING);
buf.extend_from_slice(&id.to_be_bytes());
} else if v.is_unit() {
buf.push(VAL_UNIT);
} else if v.is_nil() {
buf.push(VAL_NIL);
} else {
// Fall back to writing raw bits as float (for NaN floats or other tagged NaNs)
buf.push(VAL_FLOAT);
buf.extend_from_slice(&v.as_raw().to_be_bytes());
}
}
/// A [`Value`] is wire-safe only if it can cross to another node without
/// silent corruption: int, float, bool, nil, or unit always qualify. A heap
/// pointer is process-local, so those are always rejected. A string-id is
/// safe only when `strings_ok` — i.e. the enclosing packet carries a string
/// table with the content (actor messages do; spawn requests do not).
fn value_is_wire_safe(v: &Value, strings_ok: bool) -> bool {
!(v.is_ptr() || v.is_actor_ref() || v.is_closure()) && (strings_ok || !v.is_string())
}
/// True if every payload [`Value`] carried by `packet` is wire-safe.
///
/// Only actor messages and spawn requests carry `Value`s; all other packet
/// kinds serialize plain scalars and are always safe to send. Actor-message
/// strings must additionally index the packet's string table — a string id
/// without a table entry is a dangling reference and is rejected. Spawn
/// requests keep strings rejected entirely: remotely-spawned actors run
/// native handlers and have no module pool to intern content into.
fn packet_payload_wire_safe(packet: &Packet) -> bool {
match packet {
Packet::ActorMessage {
payload,
string_table,
..
} => payload.iter().all(|v| {
value_is_wire_safe(v, true)
&& v.as_string_id()
.map_or(true, |id| (id as usize) < string_table.len())
}),
Packet::SpawnRequest { initial_state, .. } => initial_state
.iter()
.all(|(_, v)| value_is_wire_safe(v, false)),
_ => true,
}
}
/// Read a [`Value`] from `bytes` starting at `offset`.
///
/// Returns `(Value, bytes_consumed)`.
fn read_value(bytes: &[u8], offset: usize) -> Option<(Value, usize)> {
let tag = *bytes.get(offset)?;
match tag {
VAL_INT => {
let v = read_i64(bytes, offset + 1)?;
Some((Value::int(v), 1 + 8))
}
VAL_FLOAT => {
let bits = read_u64(bytes, offset + 1)?;
Some((Value::float(f64::from_bits(bits)), 1 + 8))
}
VAL_BOOL => {
let b = *bytes.get(offset + 1)? != 0;