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
3511 lines (3220 loc) · 128 KB
/
Copy pathnetwork.rs
File metadata and controls
3511 lines (3220 loc) · 128 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, HashSet};
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, 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::supervision::RemoteLink;
use super::MessagePriority;
use super::NodeId;
use crate::vm::Value;
use tracing::warn;
// ---------------------------------------------------------------------------
// TLS configuration
// ---------------------------------------------------------------------------
/// TLS configuration for the NUL0 wire protocol.
///
/// When `MutualTls` is active, every TCP connection is upgraded to TLS
/// immediately after TCP connect/accept but *before* the NUL0 versioned
/// handshake. Both sides present certificates signed by the same cluster
/// CA; each side verifies the peer's certificate against that CA, and node
/// identity is derived from the certificate fingerprint (BLAKE3) rather
/// than the spoofable socket-address hash.
///
/// `PlaintextInsecure` is the explicit opt-out for development and testing.
#[derive(Clone)]
pub enum TlsConfig {
/// Mutual TLS with a cluster CA.
///
/// Both server and client present certificates signed by the same CA.
/// The CA certificate is used to verify the peer; the server certificate
/// and key are presented to peers. Node identity is derived from the
/// server certificate's DER fingerprint via BLAKE3.
MutualTls {
/// PEM-encoded CA certificate that signed both server and client certs.
ca_cert_pem: Vec<u8>,
/// PEM-encoded server certificate (presented to connecting peers).
server_cert_pem: Vec<u8>,
/// PEM-encoded server private key (RSA or ECDSA, PKCS#8 format).
server_key_pem: Vec<u8>,
/// Expected server name for TLS certificate verification.
/// Defaults to `"localhost"` when `None`.
server_name: Option<String>,
},
/// Plaintext with no encryption or authentication.
///
/// Explicit opt-out. Node identity is derived from a hash of the bind
/// address. Insecure; not recommended for production deployments.
PlaintextInsecure,
}
impl TlsConfig {
/// Returns `true` when plaintext (insecure) transport is configured.
pub fn is_plaintext(&self) -> bool {
matches!(self, TlsConfig::PlaintextInsecure)
}
/// Return the configured server name for TLS certificate verification.
/// Returns `None` for variants that don't use mutual TLS.
pub fn server_name(&self) -> Option<&str> {
match self {
TlsConfig::MutualTls { server_name, .. } => server_name.as_deref(),
_ => None,
}
}
/// Build a `rustls::ServerConfig` for accepting TLS connections.
///
/// For `MutualTls`: configures the server certificate + key, requires
/// client authentication, and verifies client certificates against the
/// configured CA.
fn server_config(&self) -> io::Result<rustls::ServerConfig> {
match self {
TlsConfig::MutualTls { .. } => {
let (ca, cert, key) = self.mutual_tls_material()?;
let ca_cert = parse_pem_cert(ca)?;
let server_cert = parse_pem_cert_chain(cert)?;
let server_key = parse_pem_key(key)?;
let mut client_auth_roots = rustls::RootCertStore::empty();
client_auth_roots.add(ca_cert).map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("bad CA cert: {e}"))
})?;
let client_verifier = rustls::server::WebPkiClientVerifier::builder(
std::sync::Arc::new(client_auth_roots),
)
.build()
.map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("client verifier: {e}"))
})?;
rustls::ServerConfig::builder()
.with_client_cert_verifier(client_verifier)
.with_single_cert(server_cert, server_key)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
TlsConfig::PlaintextInsecure => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"TlsConfig::PlaintextInsecure has no server config",
)),
}
}
fn client_config(&self) -> io::Result<rustls::ClientConfig> {
match self {
TlsConfig::MutualTls { .. } => {
let (ca, cert, key) = self.mutual_tls_material()?;
let ca_cert = parse_pem_cert(ca)?;
let client_cert = parse_pem_cert_chain(cert)?;
let client_key = parse_pem_key(key)?;
let mut roots = rustls::RootCertStore::empty();
roots.add(ca_cert).map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("bad CA cert: {e}"))
})?;
rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_client_auth_cert(client_cert, client_key)
.map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("client config: {e}"))
})
}
TlsConfig::PlaintextInsecure => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"TlsConfig::PlaintextInsecure has no client config",
)),
}
}
/// Extract the (ca_cert_pem, server_cert_pem, server_key_pem) triple
/// for `MutualTls`, or return an error for other variants.
fn mutual_tls_material(&self) -> io::Result<(&[u8], &[u8], &[u8])> {
match self {
TlsConfig::MutualTls {
ca_cert_pem,
server_cert_pem,
server_key_pem,
..
} => Ok((ca_cert_pem, server_cert_pem, server_key_pem)),
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a MutualTls config",
)),
}
}
/// The DER-encoded server certificate, for NodeId derivation.
/// Returns `None` for `PlaintextInsecure`.
pub fn server_cert_der(&self) -> Option<Vec<u8>> {
match self {
TlsConfig::MutualTls {
server_cert_pem, ..
} => {
let certs = rustls_pemfile::certs(&mut server_cert_pem.as_slice())
.collect::<Result<Vec<_>, _>>()
.ok()?;
certs.first().map(|c| c.clone().to_vec())
}
TlsConfig::PlaintextInsecure => None,
}
}
}
/// Parse a single PEM-encoded X.509 certificate.
fn parse_pem_cert(pem: &[u8]) -> io::Result<rustls::pki_types::CertificateDer<'static>> {
let certs: Vec<rustls::pki_types::CertificateDer> =
rustls_pemfile::certs(&mut std::io::BufReader::new(pem))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("PEM cert: {e}")))?;
certs
.into_iter()
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty PEM cert"))
}
/// Parse a chain of PEM-encoded X.509 certificates (at least one).
fn parse_pem_cert_chain(pem: &[u8]) -> io::Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
let certs: Vec<rustls::pki_types::CertificateDer> =
rustls_pemfile::certs(&mut std::io::BufReader::new(pem))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("PEM cert chain: {e}"))
})?;
if certs.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"empty PEM cert chain",
));
}
Ok(certs)
}
/// Parse a PEM-encoded private key (PKCS#8 or RSA).
fn parse_pem_key(pem: &[u8]) -> io::Result<rustls::pki_types::PrivateKeyDer<'static>> {
let key = rustls_pemfile::private_key(&mut std::io::BufReader::new(pem))
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("PEM key: {e}")))?
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty PEM key"))?;
Ok(key)
}
// ---------------------------------------------------------------------------
// 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())),
}
}
/// Attempt a graceful TLS close (send `close_notify` + shut down the
/// underlying TCP socket). If the TLS session lock is held by a reader
/// thread blocked on I/O, skip the graceful close to avoid deadlock —
/// the OS will clean up the socket when the process exits.
fn shutdown(&self) -> io::Result<()> {
match self {
TransportStream::Raw(s) => s.shutdown(std::net::Shutdown::Both),
TransportStream::TlsServer(s) => {
if let Ok(mut locked) = s.try_lock() {
let _ = locked.conn.send_close_notify();
locked.get_ref().shutdown(std::net::Shutdown::Both)
} else {
Ok(())
}
}
TransportStream::TlsClient(s) => {
if let Ok(mut locked) = s.try_lock() {
let _ = locked.conn.send_close_notify();
locked.get_ref().shutdown(std::net::Shutdown::Both)
} else {
Ok(())
}
}
}
}
/// Set the underlying TCP stream's read timeout. For TLS streams, must
/// acquire the session lock.
fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
match self {
TransportStream::Raw(s) => s.set_read_timeout(timeout),
TransportStream::TlsServer(s) => {
let locked = s.lock().unwrap();
locked.get_ref().set_read_timeout(timeout)
}
TransportStream::TlsClient(s) => {
let locked = s.lock().unwrap();
locked.get_ref().set_read_timeout(timeout)
}
}
}
/// Return the peer's certificate fingerprint as a `NodeId`, if TLS is
/// active and the peer presented a certificate.
///
/// Used to verify that the NUL0 handshake's claimed `node_id` matches
/// the cryptographic identity established by the TLS session.
fn peer_cert_node_id(&self) -> Option<NodeId> {
let certs: Option<Vec<rustls::pki_types::CertificateDer>> = match self {
TransportStream::TlsServer(s) => {
let locked = s.lock().unwrap();
locked.conn.peer_certificates().map(|c| c.to_vec())
}
TransportStream::TlsClient(s) => {
let locked = s.lock().unwrap();
locked.conn.peer_certificates().map(|c| c.to_vec())
}
TransportStream::Raw(_) => return None,
};
certs
.and_then(|mut c| {
if c.is_empty() {
None
} else {
Some(c.swap_remove(0))
}
})
.map(|cert| NodeId::from_cert_der(&cert))
}
}
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))?;
// Read timeout is set after the handshake in connection_reader/connect.
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_str: String = config.server_name().unwrap_or("localhost").to_owned();
let name = rustls::pki_types::ServerName::try_from(name_str)
.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))?;
// Read timeout is set after the handshake in connection_reader/connect.
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;
const TYPE_LINK: u8 = 10;
const TYPE_MONITOR: u8 = 11;
const TYPE_DOWN: u8 = 12;
const TYPE_CRDT_OP: u8 = 13;
const TYPE_MIGRATE_ACTOR: u8 = 14;
// ---------------------------------------------------------------------------
// 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,
/// Optional trace-id carried across nodes so a span begun on the
/// sending node can continue on the receiving node (SPEC2 §15.3).
trace_id: Option<String>,
},
/// 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: Arc<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: Arc<Vec<CrdtDeltaOp>> },
/// Low-bandwidth op-based CRDT replication: ships individual operations
/// (e.g. "increment GCounter #5 by 1") rather than full or delta state.
/// Full-state [`CrdtSync`](Packet::CrdtSync) and delta [`CrdtDeltaSync`](Packet::CrdtDeltaSync)
/// remain as the join/repair fallback.
CrdtOp { op: CrdtOp },
/// 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>>,
},
/// Register a link between a local watcher and a remote target.
Link {
watcher: RemoteLink,
target: RemoteLink,
},
/// Register a monitor between a local watcher and a remote target.
Monitor {
watcher: RemoteLink,
target: RemoteLink,
},
/// Notify that an actor has exited (propagation of `DOWN`).
Down { target: RemoteLink, reason: String },
/// Migrate an actor to a different node.
///
/// Carries the actor's durable state snapshot plus its NBC-encoded
/// bytecode module so the target node can reconstruct and resume the
/// actor without a shared persistence store.
MigrateActor {
actor_id: u64,
/// NBC-encoded bytecode module (behaviors, metadata, constants).
nbc_bytes: Vec<u8>,
/// JSON-serialized [`ActorSnapshot`](crate::runtime::persistence::ActorSnapshot).
snapshot_json: 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.
/// 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_MIGRATE_ACTOR => Self::read_migrate_actor(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_CRDT_OP => Self::read_crdt_op(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)?,
TYPE_LINK => Self::read_link(payload)?,
TYPE_MONITOR => Self::read_monitor(payload)?,
TYPE_DOWN => Self::read_down(payload)?,
_ => return None,
};
Some((seq, packet))
}
fn read_link(payload: &[u8]) -> Option<Self> {
let watcher_node = NodeId(u64::from_be_bytes(payload.get(0..8)?.try_into().ok()?));
let watcher_actor = u64::from_be_bytes(payload.get(8..16)?.try_into().ok()?);
let target_node = NodeId(u64::from_be_bytes(payload.get(16..24)?.try_into().ok()?));
let target_actor = u64::from_be_bytes(payload.get(24..32)?.try_into().ok()?);
Some(Packet::Link {
watcher: RemoteLink {
node_id: watcher_node,
actor_id: watcher_actor,
},
target: RemoteLink {
node_id: target_node,
actor_id: target_actor,
},
})
}
fn read_monitor(payload: &[u8]) -> Option<Self> {
let watcher_node = NodeId(u64::from_be_bytes(payload.get(0..8)?.try_into().ok()?));
let watcher_actor = u64::from_be_bytes(payload.get(8..16)?.try_into().ok()?);
let target_node = NodeId(u64::from_be_bytes(payload.get(16..24)?.try_into().ok()?));
let target_actor = u64::from_be_bytes(payload.get(24..32)?.try_into().ok()?);
Some(Packet::Monitor {
watcher: RemoteLink {
node_id: watcher_node,
actor_id: watcher_actor,
},
target: RemoteLink {
node_id: target_node,
actor_id: target_actor,
},
})
}
fn read_down(payload: &[u8]) -> Option<Self> {
let target_node = NodeId(u64::from_be_bytes(payload.get(0..8)?.try_into().ok()?));
let target_actor = u64::from_be_bytes(payload.get(8..16)?.try_into().ok()?);
let (reason, _) = read_string(payload, 16)?;
Some(Packet::Down {
target: RemoteLink {
node_id: target_node,
actor_id: target_actor,
},
reason,
})
}
fn read_migrate_actor(payload: &[u8]) -> Option<Self> {
if payload.len() < 12 {
return None;
}
let actor_id = u64::from_be_bytes(payload[0..8].try_into().ok()?);
let nbc_len = u32::from_be_bytes(payload[8..12].try_into().ok()?) as usize;
if payload.len() < 12 + nbc_len + 4 {
return None;
}
let nbc_bytes = payload[12..12 + nbc_len].to_vec();
let json_off = 12 + nbc_len;
let json_len =
u32::from_be_bytes(payload[json_off..json_off + 4].try_into().ok()?) as usize;
if payload.len() < json_off + 4 + json_len {
return None;
}
let snapshot_json = payload[json_off + 4..json_off + 4 + json_len].to_vec();
Some(Packet::MigrateActor {
actor_id,
nbc_bytes,
snapshot_json,
})
}
fn read_crdt_op(payload: &[u8]) -> Option<Self> {
CrdtOp::from_bytes(payload).map(|op| Packet::CrdtOp { op })
}
// ------------------------------------------------------------------
// 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::CrdtOp { .. } => TYPE_CRDT_OP,
Packet::Gossip { .. } => TYPE_GOSSIP,
Packet::FetchBehaviorRequest { .. } => TYPE_FETCH_BEHAVIOR_REQUEST,
Packet::FetchBehaviorResponse { .. } => TYPE_FETCH_BEHAVIOR_RESPONSE,
Packet::Link { .. } => TYPE_LINK,
Packet::Monitor { .. } => TYPE_MONITOR,
Packet::Down { .. } => TYPE_DOWN,
Packet::MigrateActor { .. } => TYPE_MIGRATE_ACTOR,
}
}
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,
trace_id,
} => {
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);
}
// trace_id: 1-byte flag + optional content (string).
match trace_id {
Some(tid) => {
buf.push(1);
write_string(buf, tid);
}
None => buf.push(0),
}
}
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);
write_optional_hash(buf, content_hash);
buf.extend_from_slice(&(initial_state.len() as u32).to_be_bytes());
for (k, v) in initial_state {
write_string(buf, k);
write_value(buf, v);
}
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.iter() {
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.iter() {
buf.extend_from_slice(&op.to_bytes());
}
}
Packet::CrdtOp { op } => {
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());
}
}
}
Packet::Link { watcher, target } => {
buf.extend_from_slice(&watcher.node_id.0.to_be_bytes());
buf.extend_from_slice(&watcher.actor_id.to_be_bytes());
buf.extend_from_slice(&target.node_id.0.to_be_bytes());
buf.extend_from_slice(&target.actor_id.to_be_bytes());
}
Packet::Monitor { watcher, target } => {
buf.extend_from_slice(&watcher.node_id.0.to_be_bytes());
buf.extend_from_slice(&watcher.actor_id.to_be_bytes());
buf.extend_from_slice(&target.node_id.0.to_be_bytes());
buf.extend_from_slice(&target.actor_id.to_be_bytes());
}
Packet::Down { target, reason } => {
buf.extend_from_slice(&target.node_id.0.to_be_bytes());
buf.extend_from_slice(&target.actor_id.to_be_bytes());
write_string(buf, reason);
}
Packet::MigrateActor {
actor_id,
nbc_bytes,
snapshot_json,
} => {
buf.extend_from_slice(&actor_id.to_be_bytes());
buf.extend_from_slice(&(nbc_bytes.len() as u32).to_be_bytes());
buf.extend_from_slice(nbc_bytes);
buf.extend_from_slice(&(snapshot_json.len() as u32).to_be_bytes());
buf.extend_from_slice(snapshot_json);
}
}
}
// --- 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)?;