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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
// Copyright (c) Sean Lawlor
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree.
//! A [NodeSession] is an individual connection between a specific pair of
//! `node()`s and all of its authentication and communication for that
//! pairing
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::net::SocketAddr;
use ractor::message::SerializedMessage;
use ractor::pg::{get_scoped_local_members, which_scopes_and_groups, GroupChangeMessage};
use ractor::registry::PidLifecycleEvent;
use ractor::rpc::CallResult;
use ractor::{Actor, ActorId, ActorProcessingErr, ActorRef, SpawnErr, SupervisionEvent};
use rand::Rng;
use tokio::time::Duration;
use super::auth;
use crate::net::session::SessionMessage;
use crate::node::NodeConnectionMode;
use crate::protocol::auth as auth_protocol;
use crate::protocol::control as control_protocol;
use crate::protocol::node as node_protocol;
use crate::remote_actor::{RemoteActor, RemoteActorMessage};
use crate::NodeServerMessage;
const MIN_PING_LATENCY_MS: u64 = 1000;
const MAX_PING_LATENCY_MS: u64 = 5000;
#[cfg(test)]
mod tests;
#[derive(Debug)]
enum AuthenticationState {
AsClient(auth::ClientAuthenticationProcess),
AsServer(auth::ServerAuthenticationProcess),
}
impl AuthenticationState {
fn is_ok(&self) -> bool {
match self {
Self::AsClient(c) => matches!(c, auth::ClientAuthenticationProcess::Ok),
Self::AsServer(s) => matches!(s, auth::ServerAuthenticationProcess::Ok(_)),
}
}
fn is_close(&self) -> bool {
match self {
Self::AsClient(c) => matches!(c, auth::ClientAuthenticationProcess::Close),
Self::AsServer(s) => matches!(s, auth::ServerAuthenticationProcess::Close),
}
}
}
/// Represents a remote connection to a `node()`. The [NodeSession] is the main
/// handler for all inter-node communication and handles
///
/// 1. The state of the authentication handshake
/// 2. Control messages for actor synchronization + group membership changes
/// 3. `RemoteActor`s wishing to send messages to their remote counterparts on the
/// remote system (and receive replies)
///
/// A [NodeSession] can either be a client or server session, depending on the connection sequence.
/// If it was an incoming request to the [crate::NodeServer] then it's a "server" session, as
/// the server spawned this actor. Otherwise it's an outgoing "client" request.
///
/// If the [NodeSession] is a client session, it will start the authentication handshake with
/// a `auth_protocol::NameMessage` announcing this node's name to the remote system for deduplication
/// and starting the rest of the handshake. For full authentication pattern details, see
///
/// 1. `src/protocol/auth.proto`
/// 2. `src/node/auth.rs`
///
/// Lastly the node's have an intern-node "ping" operation which occurs to keep the TCP session alive
/// and additionally measure peer latency.
pub struct NodeSession {
node_id: crate::NodeId,
is_server: bool,
cookie: String,
node_server: ActorRef<NodeServerMessage>,
this_node_name: auth_protocol::NameMessage,
connection_mode: super::NodeConnectionMode,
}
impl NodeSession {
/// Construct a new [NodeSession] with the supplied
/// arguments
///
/// * `node_id`: This peer's node id
/// * `is_server`: Is a server-received session (if false, this is the client)
/// * `cookie`: The authorization cookie
/// * `node_server`: The parent node server
/// * `node_name`: This node's name and connection details
/// * `connection_mode`: The connection mode for peer connections
pub fn new(
node_id: crate::NodeId,
is_server: bool,
cookie: String,
node_server: ActorRef<NodeServerMessage>,
node_name: auth_protocol::NameMessage,
connection_mode: super::NodeConnectionMode,
) -> Self {
Self {
node_id,
is_server,
cookie,
node_server,
this_node_name: node_name,
connection_mode,
}
}
}
impl NodeSession {
async fn handle_auth(
&self,
state: &mut NodeSessionState,
message: auth_protocol::AuthenticationMessage,
myself: ActorRef<super::NodeSessionMessage>,
) {
if state.auth.is_ok() {
// nothing to do, we're already authenticated
return;
}
if state.auth.is_close() {
tracing::info!(
"Node Session {} is shutting down due to authentication failure",
self.node_id
);
// we need to shutdown, the session needs to be terminated
myself.stop(Some("auth_fail".to_string()));
if let Some(tcp) = &state.tcp {
tcp.stop(Some("auth_fail".to_string()));
}
}
match &state.auth {
AuthenticationState::AsClient(client_auth) => {
let mut next = client_auth.next(message, &self.cookie);
match &next {
auth::ClientAuthenticationProcess::WaitingForServerChallenge(server_status) => {
match server_status.status() {
auth_protocol::server_status::Status::Ok => {
// this handshake will continue
}
auth_protocol::server_status::Status::OkSimultaneous => {
// this handshake will continue, but there is another handshake underway
// that will be shut down (i.e. this was a server connection and we're currently trying
// a client connection)
}
auth_protocol::server_status::Status::NotOk => {
// The handshake will not continue, as there's already another client handshake underway
// which itself initiated (Simultaneous connect where the other connection's name is > this node
// name)
next = auth::ClientAuthenticationProcess::Close;
}
auth_protocol::server_status::Status::NotAllowed => {
// unspecified auth reason
next = auth::ClientAuthenticationProcess::Close;
}
auth_protocol::server_status::Status::Alive => {
// A connection to the node is already alive, which means either the
// node is confused in its connection state or the previous TCP connection is
// breaking down. Send ClientStatus
// TODO: check the status properly
state.tcp_send_auth(auth_protocol::AuthenticationMessage {
msg: Some(
auth_protocol::authentication_message::Msg::ClientStatus(
auth_protocol::ClientStatus { status: true },
),
),
});
}
}
}
auth::ClientAuthenticationProcess::WaitingForServerChallengeAck(
server_challenge_value,
reply_to_server,
our_challenge,
_expected_digest,
) => {
// record the name
let name_message = auth_protocol::NameMessage {
name: server_challenge_value.name.clone(),
flags: server_challenge_value.flags.clone(),
connection_string: server_challenge_value.connection_string.clone(),
};
state.name = Some(name_message.clone());
// tell the node server that we now know this peer's name information
let _ = self
.node_server
.cast(super::NodeServerMessage::UpdateSession {
actor_id: myself.get_id(),
name: name_message,
});
// send the client challenge to the server
let reply = auth_protocol::AuthenticationMessage {
msg: Some(auth_protocol::authentication_message::Msg::ClientChallenge(
auth_protocol::ChallengeReply {
digest: reply_to_server.to_vec(),
challenge: *our_challenge,
},
)),
};
state.tcp_send_auth(reply);
}
_ => {
// no message to send
}
}
if let auth::ClientAuthenticationProcess::Close = &next {
tracing::info!(
"Node Session {} is shutting down due to authentication failure",
self.node_id
);
myself.stop(Some("auth_fail".to_string()));
}
if let auth::ClientAuthenticationProcess::Ok = &next {
tracing::info!("Node Session {} is authenticated", self.node_id);
}
tracing::debug!("Next client auth state: {:?}", next);
state.auth = AuthenticationState::AsClient(next);
}
AuthenticationState::AsServer(server_auth) => {
let mut next = server_auth.next(message, &self.cookie);
match &next {
auth::ServerAuthenticationProcess::HavePeerName(peer_name) => {
// store the peer node's name in the session state
state.name = Some(peer_name.clone());
// send the status message, followed by the server's challenge
let server_status_result = self
.node_server
.call(
|tx| super::NodeServerMessage::CheckSession {
peer_name: peer_name.clone(),
reply: tx,
},
Some(Duration::from_millis(500)),
)
.await;
// tell the node server that we now know this peer's name information
let _ = self
.node_server
.cast(super::NodeServerMessage::UpdateSession {
actor_id: myself.get_id(),
name: peer_name.clone(),
});
match server_status_result {
Err(_) | Ok(CallResult::Timeout) | Ok(CallResult::SenderError) => {
next = auth::ServerAuthenticationProcess::Close;
}
Ok(CallResult::Success(reply)) => {
let server_status: auth_protocol::server_status::Status =
reply.into();
// Send the server's status message
let status_msg = auth_protocol::AuthenticationMessage {
msg: Some(
auth_protocol::authentication_message::Msg::ServerStatus(
auth_protocol::ServerStatus {
status: server_status.into(),
},
),
),
};
state.tcp_send_auth(status_msg);
match server_status {
auth_protocol::server_status::Status::Ok
| auth_protocol::server_status::Status::OkSimultaneous => {
// Good to proceed, start a challenge
next = next.start_challenge(&self.cookie);
if let auth::ServerAuthenticationProcess::WaitingOnClientChallengeReply(
challenge,
_digest,
) = &next
{
let challenge_msg = auth_protocol::AuthenticationMessage {
msg: Some(
auth_protocol::authentication_message::Msg::ServerChallenge(
auth_protocol::Challenge {
name: self.this_node_name.name.clone(),
flags: self.this_node_name.flags.clone(),
challenge: *challenge,
connection_string: self.this_node_name.connection_string.clone(),
},
),
),
};
state.tcp_send_auth(challenge_msg);
}
}
auth_protocol::server_status::Status::NotOk
| auth_protocol::server_status::Status::NotAllowed => {
next = auth::ServerAuthenticationProcess::Close;
}
auth_protocol::server_status::Status::Alive => {
// we sent the `Alive` status, so we're waiting on the client to confirm their status
// before continuing
next = auth::ServerAuthenticationProcess::WaitingOnClientStatus;
}
}
}
}
}
auth::ServerAuthenticationProcess::Ok(digest) => {
let client_challenge_reply = auth_protocol::AuthenticationMessage {
msg: Some(auth_protocol::authentication_message::Msg::ServerAck(
auth_protocol::ChallengeAck {
digest: digest.to_vec(),
},
)),
};
state.tcp_send_auth(client_challenge_reply);
}
_ => {
// no message to send
}
}
if let auth::ServerAuthenticationProcess::Close = &next {
tracing::info!(
"Node Session {} is shutting down due to authentication failure",
self.node_id
);
myself.stop(Some("auth_fail".to_string()));
}
if let auth::ServerAuthenticationProcess::Ok(_) = &next {
tracing::info!("Node Session {} is authenticated", self.node_id);
}
tracing::debug!("Next server auth state: {:?}", next);
state.auth = AuthenticationState::AsServer(next);
}
}
}
fn handle_node(
&self,
state: &mut NodeSessionState,
message: node_protocol::NodeMessage,
myself: ActorRef<super::NodeSessionMessage>,
) {
if !state.auth.is_ok() {
tracing::warn!("Inter-node message received on unauthenticated NodeSession");
return;
}
if let Some(msg) = message.msg {
match msg {
node_protocol::node_message::Msg::Cast(cast_args) => {
if let Some(actor) =
ractor::registry::where_is_pid(ActorId::Local(cast_args.to))
{
let _ = actor.send_serialized(SerializedMessage::Cast {
variant: cast_args.variant,
args: cast_args.what,
metadata: cast_args.metadata,
});
}
}
node_protocol::node_message::Msg::Call(call_args) => {
let to = call_args.to;
let tag = call_args.tag;
if let Some(actor) =
ractor::registry::where_is_pid(ActorId::Local(call_args.to))
{
let (tx, rx) = ractor::concurrency::oneshot();
// send off the transmission in the serialized format, letting the message's own deserialization handle
// the conversion
let maybe_timeout = call_args.timeout_ms.map(Duration::from_millis);
if let Some(timeout) = maybe_timeout {
let _ = actor.send_serialized(SerializedMessage::Call {
args: call_args.what,
reply: (tx, timeout).into(),
variant: call_args.variant,
metadata: call_args.metadata,
});
} else {
let _ = actor.send_serialized(SerializedMessage::Call {
args: call_args.what,
reply: tx.into(),
variant: call_args.variant,
metadata: call_args.metadata,
});
}
// kick off a background task to reply to the channel request, threading the tag and who to reply to
#[allow(clippy::let_underscore_future)]
let _ = ractor::concurrency::spawn(async move {
if let Some(timeout) = maybe_timeout {
if let Ok(Ok(result)) =
ractor::concurrency::timeout(timeout, rx).await
{
let reply = node_protocol::node_message::Msg::Reply(
node_protocol::CallReply {
tag,
to,
what: result,
},
);
let _ = ractor::cast!(
myself,
super::NodeSessionMessage::SendMessage(
node_protocol::NodeMessage { msg: Some(reply) }
)
);
}
} else if let Ok(result) = rx.await {
let reply = node_protocol::node_message::Msg::Reply(
node_protocol::CallReply {
tag,
to,
what: result,
},
);
let _ = ractor::cast!(
myself,
super::NodeSessionMessage::SendMessage(
node_protocol::NodeMessage { msg: Some(reply) }
)
);
}
});
}
}
node_protocol::node_message::Msg::Reply(call_reply_args) => {
if let Some(actor) = state.remote_actors.get(&call_reply_args.to) {
let _ = actor.send_serialized(SerializedMessage::CallReply(
call_reply_args.tag,
call_reply_args.what,
));
}
}
}
}
}
async fn handle_control(
&self,
state: &mut NodeSessionState,
message: control_protocol::ControlMessage,
myself: ActorRef<super::NodeSessionMessage>,
) -> Result<(), ActorProcessingErr> {
if !state.auth.is_ok() {
tracing::warn!("Control message received on unauthenticated NodeSession");
return Ok(());
}
if let Some(msg) = message.msg {
match msg {
control_protocol::control_message::Msg::Spawn(spawned_actors) => {
for net_actor in spawned_actors.actors {
if let Err(spawn_err) = self
.get_or_spawn_remote_actor(
&myself,
net_actor.name,
net_actor.pid,
state,
)
.await
{
tracing::error!("Failed to spawn remote actor with {spawn_err}");
} else {
tracing::debug!("Spawned remote actor");
}
}
}
control_protocol::control_message::Msg::Terminate(termination) => {
for pid in termination.ids {
if let Some(actor) = state.remote_actors.remove(&pid) {
actor
.stop_and_wait(Some("remote".to_string()), None)
.await?;
tracing::debug!(
"Actor {pid} on node {} exited, terminating local `RemoteActor` {}",
self.node_id,
actor.get_id()
);
}
}
}
control_protocol::control_message::Msg::Ping(ping) => {
state.tcp_send_control(control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::Pong(
control_protocol::Pong {
timestamp: ping.timestamp,
},
)),
});
}
control_protocol::control_message::Msg::Pong(pong) => {
let ts: std::time::SystemTime = pong
.timestamp
.expect("Timestamp missing in Pong")
.try_into()
.expect("Failed to convert Pong(Timestamp) to SystemTime");
let delta_ms = std::time::SystemTime::now()
.duration_since(ts)
.expect("Time went backwards")
.as_millis();
tracing::debug!("Ping -> Pong took {delta_ms}ms");
if delta_ms > 50 {
tracing::warn!(
"Super long ping detected {} - {} ({delta_ms}ms)",
state.local_addr,
state.peer_addr,
);
}
// schedule next ping
state.schedule_tcp_ping();
}
control_protocol::control_message::Msg::PgJoin(join) => {
let mut cells = vec![];
for control_protocol::Actor { name, pid } in join.actors {
match self
.get_or_spawn_remote_actor(&myself, name, pid, state)
.await
{
Ok(actor) => {
cells.push(actor.get_cell());
}
Err(spawn_err) => {
tracing::error!("Failed to spawn remote actor with '{spawn_err}'");
}
}
}
// join the remote actors to the local PG group
if !cells.is_empty() {
tracing::debug!(
"PG Join group '{}' for {} remote actors",
join.group,
cells.len()
);
ractor::pg::join(join.group, cells);
}
}
control_protocol::control_message::Msg::PgLeave(leave) => {
let mut cells = vec![];
for control_protocol::Actor { pid, .. } in leave.actors {
if let Some(actor) = state.remote_actors.get(&pid) {
cells.push(actor.get_cell());
}
}
// join the remote actors to the local PG group
if !cells.is_empty() {
tracing::debug!(
"PG Leave group '{}' for {} remote actors",
leave.group,
cells.len()
);
ractor::pg::leave(leave.group, cells);
}
}
control_protocol::control_message::Msg::EnumerateNodeSessions(whos_asking) => {
let existing_sessions = ractor::call_t!(
self.node_server,
crate::NodeServerMessage::GetSessions,
500
);
if let Ok(sessions) = existing_sessions {
tracing::info!(
"{:?}",
sessions
.values()
.map(|s| s.peer_name.clone())
.collect::<Vec<_>>()
);
let names = sessions
.into_values()
.filter_map(|local_session| local_session.peer_name)
.filter(|local_session| {
// don't send back the node who's asking so we don't trigger self-connections
whos_asking.name != local_session.name
&& whos_asking.connection_string
!= local_session.connection_string
})
.collect::<Vec<_>>();
let reply_message = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::NodeSessions(
control_protocol::NodeSessions { sessions: names },
)),
};
state.tcp_send_control(reply_message);
}
}
control_protocol::control_message::Msg::NodeSessions(sessions) => {
if let NodeConnectionMode::Transitive = self.connection_mode {
let existing_sessions = if let Ok(sessions) = ractor::call_t!(
self.node_server,
crate::NodeServerMessage::GetSessions,
500
) {
sessions
.into_values()
.filter_map(|v| v.peer_name.map(|p| [p.name, p.connection_string]))
.flatten()
.collect()
} else {
HashSet::new()
};
for session_name in sessions.sessions.into_iter() {
// check if we're already connected to this host or if it's a request to self-connect,
// if so ignore
if !(existing_sessions.contains(&session_name.name)
|| existing_sessions.contains(&session_name.connection_string)
|| session_name.name == self.this_node_name.name
|| session_name.connection_string
== self.this_node_name.connection_string)
{
// we aren't connected to this peer, start connecting
let node_server = self.node_server.clone();
ractor::concurrency::spawn(async move {
if let Err(connect_err) = super::client::connect(
&node_server,
session_name.connection_string.clone(),
)
.await
{
tracing::warn!("Node transitive connection, failed to connect to {} with '{connect_err}'", session_name.connection_string);
}
});
}
}
}
}
}
}
Ok(())
}
/// Called once the session is authenticated
fn after_authenticated(
&self,
myself: ActorRef<super::NodeSessionMessage>,
state: &mut NodeSessionState,
) {
tracing::info!(
"Session authenticated on NodeSession {} - ({:?})",
self.node_id,
state.peer_addr
);
// startup the ping healthcheck activity
state.schedule_tcp_ping();
// trigger enumeration of the remote peer's node sessions for transitive connections
if let NodeConnectionMode::Transitive = self.connection_mode {
state.tcp_send_control(control_protocol::ControlMessage {
msg: Some(
control_protocol::control_message::Msg::EnumerateNodeSessions(
self.this_node_name.clone(),
),
),
});
}
// setup PID monitoring
ractor::registry::pid_registry::monitor(myself.get_cell());
// Scan all PIDs and spawn them on the remote host
let pids = ractor::registry::pid_registry::get_all_pids()
.into_iter()
.filter(|act| act.supports_remoting())
.map(|a| control_protocol::Actor {
name: a.get_name(),
pid: a.get_id().pid(),
})
.collect::<Vec<_>>();
if !pids.is_empty() {
let msg = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::Spawn(
control_protocol::Spawn { actors: pids },
)),
};
state.tcp_send_control(msg);
}
// setup scope monitoring
ractor::pg::monitor_scope(
ractor::pg::ALL_SCOPES_NOTIFICATION.to_string(),
myself.get_cell(),
);
// setup PG monitoring
ractor::pg::monitor(
ractor::pg::ALL_GROUPS_NOTIFICATION.to_string(),
myself.get_cell(),
);
// Scan all scopes with their PG groups + synchronize them
let scopes_and_groups = which_scopes_and_groups();
for key in scopes_and_groups {
let local_members = get_scoped_local_members(&key.get_scope(), &key.get_group())
.into_iter()
.filter(|v| v.supports_remoting())
.map(|act| control_protocol::Actor {
name: act.get_name(),
pid: act.get_id().pid(),
})
.collect::<Vec<_>>();
if !local_members.is_empty() {
let control_message = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::PgJoin(
control_protocol::PgJoin {
scope: key.get_scope(),
group: key.get_group(),
actors: local_members,
},
)),
};
state.tcp_send_control(control_message);
}
}
// TODO: subscribe to the named registry and synchronize it? What happes on a name clash? How would this be handled
// if both sessions had a "node_a" for example? Which resolves, local only?
}
/// Get a given remote actor, or spawn it if it doesn't exist.
async fn get_or_spawn_remote_actor(
&self,
myself: &ActorRef<super::NodeSessionMessage>,
actor_name: Option<String>,
actor_pid: u64,
state: &mut NodeSessionState,
) -> Result<ActorRef<RemoteActorMessage>, SpawnErr> {
match state.remote_actors.get(&actor_pid) {
Some(actor) => Ok(actor.clone()),
_ => {
let (remote_actor, _) = RemoteActor
.spawn_linked(
myself.clone(),
actor_name,
actor_pid,
self.node_id,
myself.get_cell(),
)
.await?;
state.remote_actors.insert(actor_pid, remote_actor.clone());
Ok(remote_actor)
}
}
}
}
/// The state of the node session
pub struct NodeSessionState {
tcp: Option<ActorRef<crate::net::session::SessionMessage>>,
peer_addr: SocketAddr,
local_addr: SocketAddr,
name: Option<auth_protocol::NameMessage>,
auth: AuthenticationState,
remote_actors: HashMap<u64, ActorRef<RemoteActorMessage>>,
}
impl NodeSessionState {
fn is_tcp_actor(&self, actor: ActorId) -> bool {
self.tcp
.as_ref()
.map(|t| t.get_id() == actor)
.unwrap_or(false)
}
fn tcp_send_auth(&self, msg: auth_protocol::AuthenticationMessage) {
if let Some(tcp) = &self.tcp {
let net_msg = crate::protocol::NetworkMessage {
message: Some(crate::protocol::meta::network_message::Message::Auth(msg)),
};
let _ = ractor::cast!(tcp, SessionMessage::Send(net_msg));
}
}
fn tcp_send_node(&self, msg: node_protocol::NodeMessage) {
if let Some(tcp) = &self.tcp {
let net_msg = crate::protocol::NetworkMessage {
message: Some(crate::protocol::meta::network_message::Message::Node(msg)),
};
let _ = ractor::cast!(tcp, SessionMessage::Send(net_msg));
}
}
fn tcp_send_control(&self, msg: control_protocol::ControlMessage) {
if let Some(tcp) = &self.tcp {
let net_msg = crate::protocol::NetworkMessage {
message: Some(crate::protocol::meta::network_message::Message::Control(
msg,
)),
};
let _ = ractor::cast!(tcp, SessionMessage::Send(net_msg));
}
}
fn schedule_tcp_ping(&self) {
if let Some(tcp) = &self.tcp {
#[allow(clippy::let_underscore_future)]
let _ = tcp.send_after(Self::get_send_delay(), || {
let ping = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::Ping(
control_protocol::Ping {
timestamp: Some(prost_types::Timestamp::from(
std::time::SystemTime::now(),
)),
},
)),
};
let net_msg = crate::protocol::NetworkMessage {
message: Some(crate::protocol::meta::network_message::Message::Control(
ping,
)),
};
SessionMessage::Send(net_msg)
});
}
}
fn get_send_delay() -> Duration {
Duration::from_millis(
rand::thread_rng().gen_range(MIN_PING_LATENCY_MS..MAX_PING_LATENCY_MS),
)
}
}
#[ractor::async_trait]
impl Actor for NodeSession {
type Msg = super::NodeSessionMessage;
type Arguments = crate::net::NetworkStream;
type State = NodeSessionState;
async fn pre_start(
&self,
myself: ActorRef<Self::Msg>,
stream: Self::Arguments,
) -> Result<Self::State, ActorProcessingErr> {
let peer_addr = stream.peer_addr();
let local_addr = stream.local_addr();
// startup the TCP socket handler for message write + reading
let actor = crate::net::session::Session::spawn_linked(
myself.clone(),
stream,
peer_addr,
local_addr,
myself.get_cell(),
)
.await?;
let state = Self::State {
tcp: Some(actor),
name: None,
auth: if self.is_server {
AuthenticationState::AsServer(auth::ServerAuthenticationProcess::init())
} else {
AuthenticationState::AsClient(auth::ClientAuthenticationProcess::init())
},
remote_actors: HashMap::new(),
peer_addr,
local_addr,
};
// If a client-connection, startup the handshake
if !self.is_server {
state.tcp_send_auth(auth_protocol::AuthenticationMessage {
msg: Some(auth_protocol::authentication_message::Msg::Name(
self.this_node_name.clone(),
)),
});
}
Ok(state)
}
async fn post_stop(
&self,
myself: ActorRef<Self::Msg>,
_state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
// unhook monitoring sessions
ractor::pg::demonitor_scope(
ractor::pg::ALL_SCOPES_NOTIFICATION.to_string(),
myself.get_id(),
);
ractor::pg::demonitor(
ractor::pg::ALL_GROUPS_NOTIFICATION.to_string(),
myself.get_id(),
);
ractor::registry::pid_registry::demonitor(myself.get_id());
Ok(())
}
async fn handle(
&self,
myself: ActorRef<Self::Msg>,
message: Self::Msg,
state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
if let Some(peer) = &state.name {
if self.this_node_name.connection_string == peer.connection_string
|| self.this_node_name.name == peer.name
{
// self-connection detected, exit session
tracing::warn!("Cannot establish a connection to self. Exiting");
myself.stop(Some("self_connection".to_string()));
return Ok(());
}
}
match message {
Self::Msg::MessageReceived(maybe_network_message) if state.tcp.is_some() => {
if let Some(network_message) = maybe_network_message.message {
match network_message {
crate::protocol::meta::network_message::Message::Auth(auth_message) => {
let p_state = state.auth.is_ok();
self.handle_auth(state, auth_message, myself.clone()).await;
// If we were not originally authenticated, but now we are, startup the node sync'ing logic
if !p_state && state.auth.is_ok() {
self.node_server.cast(
NodeServerMessage::ConnectionAuthenticated(myself.get_id()),
)?;
self.after_authenticated(myself, state);
}
}
crate::protocol::meta::network_message::Message::Node(node_message) => {
self.handle_node(state, node_message, myself);
}
crate::protocol::meta::network_message::Message::Control(
control_message,
) => {
self.handle_control(state, control_message, myself).await?;
}
}
}
}
Self::Msg::SendMessage(node_message) if state.tcp.is_some() => {
state.tcp_send_node(node_message);
}
Self::Msg::GetAuthenticationState(reply) => {
let _ = reply.send(state.auth.is_ok());
}
_ => {
// no-op, ignore
}
}
Ok(())
}
async fn handle_supervisor_evt(
&self,
myself: ActorRef<Self::Msg>,
message: SupervisionEvent,
state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
match message {
SupervisionEvent::ActorStarted(_) => {}
SupervisionEvent::ActorFailed(actor, msg) => {
if state.is_tcp_actor(actor.get_id()) {
tracing::error!(
"Node session {:?}'s TCP session panicked with '{msg}'",
state.name
);
myself.stop(Some("tcp_session_err".to_string()));
} else if let Some(actor) = state.remote_actors.remove(&actor.get_id().pid()) {
tracing::warn!(
"Node session {:?} had a remote actor ({}) panic with {msg}",
state.name,
actor.get_id(),
);
actor.kill();
// NOTE: This is a legitimate panic of the `RemoteActor`, not the actor on the remote machine panicking (which
// is handled by the remote actor's supervisor). Therefore we should re-spawn the actor, and if we can't we
// should ourself die. Something is seriously wrong...
let pid = actor.get_id().pid();
let name = actor.get_name();
let _ = self
.get_or_spawn_remote_actor(&myself, name, pid, state)
.await?;
} else {
tracing::error!("NodeSesion {:?} received an unknown child panic superivision message from {} - '{msg}'",
state.name,
actor.get_id()
);
}
}
SupervisionEvent::ActorTerminated(actor, _, maybe_reason) => {
if state.is_tcp_actor(actor.get_id()) {
tracing::info!("NodeSession {:?} connection closed", state.name);
myself.stop(Some("tcp_session_closed".to_string()));
// TODO: resilient connection?
} else if let Some(actor) = state.remote_actors.remove(&actor.get_id().pid()) {
tracing::debug!(
"NodeSession {:?} received a child exit with reason '{maybe_reason:?}'",
state.name
);
actor
.stop_and_wait(Some("remote_exit".to_string()), None)
.await?;
} else {
tracing::warn!("NodeSession {:?} received an unknown child actor exit event from {} - '{maybe_reason:?}'",
state.name,
actor.get_id(),
);
}
}
// ======== Lifecycle event handlers (PG groups + PID registry) ======== //
SupervisionEvent::ProcessGroupChanged(change) => match change {
GroupChangeMessage::Join(scope, group, actors) => {
let filtered = actors
.into_iter()
.filter(|act| act.supports_remoting())
.map(|act| control_protocol::Actor {
name: act.get_name(),
pid: act.get_id().pid(),
})
.collect::<Vec<_>>();
if !filtered.is_empty() {
let msg = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::PgJoin(
control_protocol::PgJoin {
scope,
group,
actors: filtered,
},
)),
};
state.tcp_send_control(msg);
}
}
GroupChangeMessage::Leave(scope, group, actors) => {
let filtered = actors
.into_iter()
.filter(|act| act.supports_remoting())
.map(|act| control_protocol::Actor {
name: act.get_name(),
pid: act.get_id().pid(),
})
.collect::<Vec<_>>();
if !filtered.is_empty() {
let msg = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::PgLeave(
control_protocol::PgLeave {
scope,
group,
actors: filtered,
},
)),
};
state.tcp_send_control(msg);
}
}
},
SupervisionEvent::PidLifecycleEvent(pid) => match pid {
PidLifecycleEvent::Spawn(who) => {
if who.supports_remoting() {
let msg = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::Spawn(
control_protocol::Spawn {
actors: vec![control_protocol::Actor {
pid: who.get_id().pid(),
name: who.get_name(),
}],
},
)),
};
state.tcp_send_control(msg);
}
}
PidLifecycleEvent::Terminate(who) => {
if who.supports_remoting() {
let msg = control_protocol::ControlMessage {
msg: Some(control_protocol::control_message::Msg::Terminate(
control_protocol::Terminate {
ids: vec![who.get_id().pid()],
},
)),
};
state.tcp_send_control(msg);
}
}
},
}
Ok(())
}
}