repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
achanda/ipnetwork
https://github.com/achanda/ipnetwork/blob/f01575cbf2fc596c0a1761c122aa92525cbb7974/benches/parse_bench.rs
benches/parse_bench.rs
use criterion::{criterion_group, criterion_main, Criterion}; use ipnetwork::{Ipv4Network, Ipv6Network}; use std::net::{Ipv4Addr, Ipv6Addr}; fn parse_ipv4_prefix_benchmark(c: &mut Criterion) { c.bench_function("parse ipv4 prefix", |b| { b.iter(|| "127.1.0.0/24".parse::<Ipv4Network>().unwrap()) }); } fn parse_ipv6_benchmark(c: &mut Criterion) { c.bench_function("parse ipv6", |b| { b.iter(|| "FF01:0:0:17:0:0:0:2/64".parse::<Ipv6Network>().unwrap()) }); } fn parse_ipv4_netmask_benchmark(c: &mut Criterion) { c.bench_function("parse ipv4 netmask", |b| { b.iter(|| "127.1.0.0/255.255.255.0".parse::<Ipv4Network>().unwrap()) }); } fn contains_ipv4_benchmark(c: &mut Criterion) { let cidr = "74.125.227.0/25".parse::<Ipv4Network>().unwrap(); c.bench_function("contains ipv4", |b| { b.iter(|| { cidr.contains(Ipv4Addr::new(74, 125, 227, 4)) }) }); } fn contains_ipv6_benchmark(c: &mut Criterion) { let cidr = "FF01:0:0:17:0:0:0:2/65".parse::<Ipv6Network>().unwrap(); c.bench_function("contains ipv6", |b| { b.iter(|| { cidr.contains(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0x7fff, 0, 0, 0x2)) }) }); } criterion_group!( benches, parse_ipv4_prefix_benchmark, parse_ipv6_benchmark, parse_ipv4_netmask_benchmark, contains_ipv4_benchmark, contains_ipv6_benchmark ); criterion_main!(benches);
rust
Apache-2.0
f01575cbf2fc596c0a1761c122aa92525cbb7974
2026-01-04T20:19:08.816812Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-test-client/src/main.rs
hydra-test-client/src/main.rs
use std::net::SocketAddr; use std::time::Duration; use hydra::Message; use hydra::Node; use hydra::NodeOptions; use hydra::Pid; use hydra::Process; #[hydra::main] async fn main() { Node::start( "hydra-test-client", NodeOptions::new() .listen_address("127.0.0.1:1338".parse::<SocketAddr>().unwrap()) .broadcast_address("127.0.0.1:1338".parse::<SocketAddr>().unwrap()), ); let address: SocketAddr = "127.0.0.1:1337".parse().unwrap(); Node::monitor(("hydra-test-main", address)); Process::sleep(Duration::from_secs(5)).await; println!("Nodes: {:?}", Node::list()); for i in 0..8 { Process::spawn(async move { let pid = Process::current(); let mut pid2: Option<Pid> = None; loop { if let Some(pid2) = pid2 { Process::send(pid2, pid); } else { Process::send( (format!("bench-receive{}", i), ("hydra-test-main", address)), pid, ); } let pidd = Process::receive::<Pid>().await; if let Message::User(pidd) = pidd { pid2 = Some(pidd); } } }); } Process::sleep(Duration::from_secs(1000)).await; }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-test-main/src/main.rs
hydra-test-main/src/main.rs
use std::net::SocketAddr; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; use hydra::Message; use hydra::Node; use hydra::NodeOptions; use hydra::Pid; use hydra::Process; static COUNTER: AtomicU64 = AtomicU64::new(0); #[hydra::main] async fn main() { Node::start( "hydra-test-main", NodeOptions::new() .listen_address("127.0.0.1:1337".parse::<SocketAddr>().unwrap()) .broadcast_address("127.0.0.1:1337".parse::<SocketAddr>().unwrap()), ); for i in 0..8 { Process::spawn(async move { Process::register(Process::current(), format!("bench-receive{}", i)) .expect("Failed to register process!"); let pid = Process::current(); loop { let Message::User(pid2) = Process::receive::<Pid>().await else { panic!() }; COUNTER.fetch_add(1, Ordering::Relaxed); Process::send(pid2, pid); } }); } let mut start = Instant::now(); loop { Process::sleep(Duration::from_secs(1)).await; let elapsed = start.elapsed(); let count = COUNTER.load(Ordering::Relaxed); if count == 0 { tracing::info!("Waiting for first message..."); start = Instant::now(); continue; } let ops = count / elapsed.as_secs().max(1); tracing::info!("Msg/s: {}", ops); } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/reference.rs
hydra/src/reference.rs
use std::fmt::Debug; use std::net::SocketAddr; use std::num::NonZeroU64; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use serde::Deserialize; use serde::Serialize; use crate::INVALID_NODE_ID; use crate::LOCAL_NODE_ID; use crate::Node; use crate::node_lookup_local; use crate::node_lookup_remote; use crate::node_register; /// The representation of a [Reference] serialized for the wire. #[derive(Serialize, Deserialize)] enum ReferenceWire { WithNode(NonZeroU64, String, SocketAddr), NodeUnavailable(NonZeroU64), } /// A unique id that pertains to a specific node. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Reference { Local(NonZeroU64), Remote(NonZeroU64, u64), } impl Reference { /// Constructs a new unique [Reference] for this node. pub fn new() -> Self { static REF: AtomicU64 = AtomicU64::new(1); Self::Local(NonZeroU64::new(REF.fetch_add(1, Ordering::Relaxed)).unwrap()) } /// Constructs a new [Reference] from the given id, assigning it to the local node. pub(crate) fn local(id: u64) -> Self { Self::Local(NonZeroU64::new(id).unwrap()) } /// Constructs a new [Reference] from the given id, assigning it to the remote node. pub(crate) fn remote(id: u64, node: u64) -> Self { Self::Remote(NonZeroU64::new(id).unwrap(), node) } /// Returns `true` if this [Reference] is a local process. pub const fn is_local(&self) -> bool { matches!(self, Self::Local(_)) } /// Returns `true` if this [Reference] is a remote process. pub const fn is_remote(&self) -> bool { matches!(self, Self::Remote(_, _)) } /// Gets the id part of this [Reference]. pub(crate) const fn id(&self) -> u64 { match self { Self::Local(id) => id.get(), Self::Remote(id, _) => id.get(), } } /// Gets the node part of this [Reference]. pub(crate) const fn node(&self) -> u64 { match self { Self::Local(_) => LOCAL_NODE_ID, Self::Remote(_, node) => *node, } } } impl Default for Reference { fn default() -> Self { Self::new() } } impl Debug for Reference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Local(id) => write!(f, "Reference<0, {}>", id), Self::Remote(id, node) => write!(f, "Reference<{}, {}", node, id), } } } impl Serialize for Reference { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let reference: ReferenceWire = match self { Self::Local(id) => match node_lookup_local() { Some((name, address)) => ReferenceWire::WithNode(*id, name, address), None => ReferenceWire::NodeUnavailable(*id), }, Self::Remote(id, node) => match node_lookup_remote(*node) { Some((name, address)) => ReferenceWire::WithNode(*id, name, address), None => ReferenceWire::NodeUnavailable(*id), }, }; reference.serialize(serializer) } } impl<'de> Deserialize<'de> for Reference { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let node: ReferenceWire = ReferenceWire::deserialize(deserializer)?; match node { ReferenceWire::WithNode(id, node_name, node_address) => match node_lookup_local() { Some((name, address)) => { if name == node_name && address == node_address { Ok(Reference::Local(id)) } else { let node = node_register(Node::from((node_name, node_address)), false); Ok(Reference::Remote(id, node)) } } None => Ok(Reference::Remote(id, INVALID_NODE_ID)), }, ReferenceWire::NodeUnavailable(id) => Ok(Self::Remote(id, INVALID_NODE_ID)), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_item.rs
hydra/src/process_item.rs
use std::fmt::Debug; use crate::Dest; use crate::ExitReason; use crate::Message; use crate::Node; use crate::Pid; use crate::Reference; use crate::SystemMessage; /// Represents a single unit of computation or a message for the process. pub enum ProcessItem { /// Sent from a remote process in a different userspace. UserRemoteMessage(Vec<u8>), /// Sent from a process in the same userspace. UserLocalMessage(Box<dyn std::any::Any + Send>), /// Sent from the system. SystemMessage(SystemMessage), /// Sent from a monitor when a process goes down. MonitorProcessDown(Dest, Reference, ExitReason), /// Sent from a monitor when a node goes down. MonitorNodeDown(Node, Reference), /// Sent from a remote monitor to update the assigned pid. MonitorProcessUpdate(Reference, Pid), /// Sent from the system when an alias is deactivated externally. AliasDeactivated(u64), } impl From<SystemMessage> for ProcessItem { fn from(value: SystemMessage) -> Self { Self::SystemMessage(value) } } impl<T> From<Message<T>> for ProcessItem where T: Send + 'static, { fn from(value: Message<T>) -> Self { match value { Message::User(user) => Self::UserLocalMessage(Box::new(user)), Message::System(system) => Self::SystemMessage(system), } } } impl Debug for ProcessItem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::UserRemoteMessage(_) => write!(f, "UserRemoteMessage(..)"), Self::UserLocalMessage(_) => write!(f, "UserLocalMessage(..)"), Self::SystemMessage(system) => write!(f, "SystemMessage({:?})", system), Self::MonitorProcessDown(dest, reference, exit_reason) => write!( f, "MonitorProcessDown({:?}, {:?}, {:?})", dest, reference, exit_reason ), Self::MonitorNodeDown(node, reference) => { write!(f, "MonitorNodeDown({:?}, {:?})", node, reference) } Self::MonitorProcessUpdate(reference, process) => { write!(f, "MonitorProcessUpdate({:?}, {:?})", reference, process) } Self::AliasDeactivated(alias) => write!(f, "AliasDeactivated({:?})", alias), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/catch_unwind.rs
hydra/src/catch_unwind.rs
use std::future::Future; use std::panic::AssertUnwindSafe; use std::panic::UnwindSafe; use std::panic::catch_unwind; use std::pin::Pin; use std::task::Context; use std::task::Poll; use pin_project_lite::pin_project; pin_project! { /// A future that will catch panics and unwind them. pub struct AsyncCatchUnwind<Fut> where Fut: Future, { #[pin] future: Fut, } } impl<Fut> AsyncCatchUnwind<Fut> where Fut: Future + UnwindSafe, { /// Constructs a new [CatchUnwind] for the given future. pub fn new(future: Fut) -> Self { Self { future } } } impl<Fut> Future for AsyncCatchUnwind<Fut> where Fut: Future + UnwindSafe, { type Output = Result<Fut::Output, String>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let f = self.project().future; catch_unwind(AssertUnwindSafe(|| f.poll(cx))) .map_err(|x| { if x.is::<String>() { return *x.downcast::<String>().unwrap(); } else if x.is::<&str>() { return x.downcast::<&str>().unwrap().to_string(); } "Unknown error!".to_string() })? .map(Ok) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/restart.rs
hydra/src/restart.rs
/// Controls what a supervisor should consider to be a successful termination or not. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Restart { /// The child process is always restarted. Permanent, /// The child process is never restarted, regardless of the supervision strategy: any /// termination (even abnormal) is considered successful. Temporary, /// The child process is restarted if it terminates abnormally, i.e., with an exit reason other than /// `normal`, or `shutdown`. Transient, }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_remote.rs
hydra/src/node_remote.rs
use std::sync::Arc; use serde::Deserialize; use serde::Serialize; use tokio::net::TcpStream; use tokio_util::codec::Framed; use futures_util::SinkExt; use futures_util::StreamExt; use futures_util::stream; use futures_util::stream::SplitSink; use futures_util::stream::SplitStream; use crate::frame::Codec; use crate::frame::Frame; use crate::frame::Hello; use crate::frame::LinkDown; use crate::frame::MonitorDown; use crate::frame::MonitorUpdate; use crate::frame::Ping; use crate::frame::Pong; use crate::ExitReason; use crate::Local; use crate::Message; use crate::Node; use crate::NodeLocalSupervisor; use crate::NodeLocalSupervisorMessage; use crate::Pid; use crate::Process; use crate::ProcessItem; use crate::Reference; use crate::link_create; use crate::link_destroy; use crate::monitor_create; use crate::monitor_destroy; use crate::node_accept; use crate::node_forward_send; use crate::node_link_destroy; use crate::node_local_process; use crate::node_process_link_create; use crate::node_process_link_down; use crate::node_process_monitor_cleanup; use crate::node_process_monitor_destroy; use crate::node_process_monitor_down; use crate::node_register; use crate::node_register_workers; use crate::node_remote_supervisor_down; use crate::node_send_frame; use crate::process_exists_lock; use crate::process_exit; use crate::process_name_lookup; use crate::process_sender; type Reader = SplitStream<Framed<TcpStream, Codec>>; type Writer = SplitSink<Framed<TcpStream, Codec>, Frame>; #[derive(Serialize, Deserialize)] pub enum NodeRemoteSenderMessage { /// Occurs when a new outbound frame is ready to be sent over the socket. SendFrame(Local<Frame>), /// Occurs when a bunch of new outbound frames are ready to be sent over the socket. SendFrames(Local<Vec<Frame>>), } #[derive(Serialize, Deserialize)] pub enum NodeRemoteConnectorMessage { /// Occurs when the connector receives the local node supervisor information. LocalNodeSupervisor(Local<Arc<NodeLocalSupervisor>>), } #[derive(Serialize, Deserialize)] enum NodeRemoteSupervisorMessage { /// Occurs when the receiver has been sent a ping frame, so we must respond with a pong frame. SendPong, } struct NodeRemoteSupervisor { node: Node, process: Pid, local_supervisor: Arc<NodeLocalSupervisor>, } struct NodeRemoteConnector { node: Node, process: Pid, } impl Drop for NodeRemoteSupervisor { fn drop(&mut self) { node_remote_supervisor_down(self.node.clone(), self.process); } } impl Drop for NodeRemoteConnector { fn drop(&mut self) { node_remote_supervisor_down(self.node.clone(), self.process); } } async fn node_remote_sender(mut writer: Writer, supervisor: Arc<NodeRemoteSupervisor>) { let send_timeout = supervisor.local_supervisor.options.heartbeat_interval; loop { let Ok(message) = Process::timeout(send_timeout, Process::receive::<NodeRemoteSenderMessage>()).await else { writer .send(Ping.into()) .await .expect("Failed to send a message to the remote node!"); continue; }; match message { Message::User(NodeRemoteSenderMessage::SendFrame(frame)) => { writer .send(frame.into_inner()) .await .expect("Failed to send a message to the remote node!"); } Message::User(NodeRemoteSenderMessage::SendFrames(frames)) => { let mut stream = stream::iter(frames.into_inner().into_iter().map(Ok)); writer .send_all(&mut stream) .await .expect("Failed to send multiple messages to the remote node!"); } _ => unreachable!(), } } } async fn node_remote_receiver(mut reader: Reader, supervisor: Arc<NodeRemoteSupervisor>) { let recv_timeout = supervisor.local_supervisor.options.heartbeat_timeout; loop { let message = Process::timeout(recv_timeout, reader.next()) .await .expect("Remote node timed out!") .expect("Remote node went down!") .expect("Failed to receive a message from the remote node!"); match message { Frame::Hello(_) => unreachable!("Should never receive hello frame!"), Frame::Ping => { Process::send(supervisor.process, NodeRemoteSupervisorMessage::SendPong); } Frame::Pong => { // Maybe log this in metrics somewhere! } Frame::Send(send) => { node_forward_send(send); } Frame::Monitor(monitor) => { let node = node_register(supervisor.node.clone(), false); let from_id = monitor .from_id .expect("Must have a from_id for remote monitors!"); let from = Pid::remote(from_id, node); let reference = Reference::remote(monitor.reference_id, node); if monitor.install { if let Some(id) = monitor.process_id { let process = Pid::local(id); process_exists_lock(process, |exists| { if exists { monitor_create(process, reference, from, None); node_process_monitor_cleanup( supervisor.node.clone(), reference, process, ); } else { let mut monitor_down = MonitorDown::new(ExitReason::from("noproc")); monitor_down.monitors.push(reference.id()); node_send_frame(monitor_down.into(), node); } }); } else if let Some(name) = monitor.process_name { if let Some(id) = process_name_lookup(&name) { monitor_create(id, reference, from, None); let monitor_update = MonitorUpdate::new(from_id, id.id(), reference.id()); node_send_frame(monitor_update.into(), node); node_process_monitor_cleanup(supervisor.node.clone(), reference, id); } else { let mut monitor_down = MonitorDown::new(ExitReason::from("noproc")); monitor_down.monitors.push(reference.id()); node_send_frame(monitor_down.into(), node); } } else { panic!("Must have either a process id or process name for monitor!"); }; } else { monitor_destroy(Pid::local(monitor.process_id.unwrap()), reference); node_process_monitor_destroy(supervisor.node.clone(), reference); } } Frame::MonitorDown(monitor_down) => { for reference_id in monitor_down.monitors { node_process_monitor_down( supervisor.node.clone(), Reference::local(reference_id), monitor_down.exit_reason.clone(), ); } } Frame::MonitorUpdate(monitor_update) => { let node = node_register(supervisor.node.clone(), false); let reference = Reference::local(monitor_update.reference_id); let from = Pid::remote(monitor_update.from_id, node); process_sender(Pid::local(monitor_update.process_id)) .map(|sender| sender.send(ProcessItem::MonitorProcessUpdate(reference, from))); } Frame::Link(link) => { let node = node_register(supervisor.node.clone(), false); let process = Pid::local(link.process_id); let from = Pid::remote(link.from_id, node); if link.install { if link_create(process, from, false) { node_process_link_create(supervisor.node.clone(), from, process); } else { let mut link_down = LinkDown::new(link.process_id, ExitReason::from("noproc")); link_down.links.push(link.from_id); node_send_frame(link_down.into(), node); } } else { link_destroy(process, from); node_link_destroy(supervisor.node.clone(), from, process); } } Frame::LinkDown(link_down) => { let node = node_register(supervisor.node.clone(), false); let from = Pid::remote(link_down.from_id, node); for link in link_down.links { node_process_link_down( supervisor.node.clone(), Pid::local(link), from, link_down.exit_reason.clone(), ); } } Frame::Exit(exit) => { let node = node_register(supervisor.node.clone(), false); let process = Pid::local(exit.process_id); let from = Pid::remote(exit.from_id, node); process_exit(process, from, exit.exit_reason); } } } } async fn node_remote_supervisor( writer: Writer, reader: Reader, hello: Hello, supervisor: Arc<NodeLocalSupervisor>, ) { let node = Node::from((hello.name, hello.broadcast_address)); let supervisor = Arc::new(NodeRemoteSupervisor { node: node.clone(), process: Process::current(), local_supervisor: supervisor, }); Process::link(supervisor.process); if !node_accept(node.clone(), Process::current()) { panic!("Not accepting node supervisor!"); } let sender = Process::spawn_link(node_remote_sender(writer, supervisor.clone())); let receiver = Process::spawn_link(node_remote_receiver(reader, supervisor.clone())); node_register_workers(node, sender, receiver); loop { let message = Process::receive::<NodeRemoteSupervisorMessage>().await; match message { Message::User(NodeRemoteSupervisorMessage::SendPong) => { Process::send( sender, NodeRemoteSenderMessage::SendFrame(Local::new(Pong.into())), ); } _ => unreachable!(), } } } pub async fn node_remote_accepter(socket: TcpStream, supervisor: Arc<NodeLocalSupervisor>) { if let Err(error) = socket.set_nodelay(true) { #[cfg(feature = "tracing")] tracing::warn!(error = ?error, "Failed to set TCP_NODELAY on socket"); #[cfg(not(feature = "tracing"))] let _ = error; } let framed = Framed::new(socket, Codec::new()); let (mut writer, mut reader) = framed.split(); let hello = Hello::new( supervisor.name.clone(), supervisor.options.broadcast_address, ); let handshake_timeout = supervisor.options.handshake_timeout; Process::timeout(handshake_timeout, writer.send(hello.into())) .await .expect("Timed out while sending hello handshake packet!") .expect("Failed to send hello handshake packet!"); let frame = Process::timeout(handshake_timeout, reader.next()) .await .expect("Timed out while receiving hello handshake packet!") .unwrap() .expect("Failed to receive hello handshake packet!"); if let Frame::Hello(mut hello) = frame { if hello.validate() { Process::spawn(node_remote_supervisor(writer, reader, hello, supervisor)); return; } else { panic!("Node handshake failed validation!"); } } panic!("Received incorrect frame for node handshake!"); } pub async fn node_remote_connector(node: Node) { let connector = NodeRemoteConnector { node: node.clone(), process: Process::current(), }; let local = node_local_process().expect("Local node not started!"); Process::link(local); Process::send( local, NodeLocalSupervisorMessage::RequestLocalSupervisor(Process::current()), ); let Message::User(NodeRemoteConnectorMessage::LocalNodeSupervisor(supervisor)) = Process::receive::<NodeRemoteConnectorMessage>().await else { panic!("Received unexpected message in remote connector!"); }; let address = node .address() .expect("Must have an address for a remote node!"); let handshake_timeout = supervisor.options.handshake_timeout; let socket = Process::timeout(handshake_timeout, TcpStream::connect(address)) .await .expect("Timed out while connecting to the node!") .expect("Failed to connect to the node!"); if let Err(error) = socket.set_nodelay(true) { #[cfg(feature = "tracing")] tracing::warn!(error = ?error, "Failed to set TCP_NODELAY on socket"); #[cfg(not(feature = "tracing"))] let _ = error; } let framed = Framed::new(socket, Codec::new()); let (mut writer, mut reader) = framed.split(); let hello = Hello::new( supervisor.name.clone(), supervisor.options.broadcast_address, ); Process::timeout(handshake_timeout, writer.send(hello.into())) .await .expect("Timed out while sending hello handshake packet!") .expect("Failed to send hello handshake packet!"); let frame = Process::timeout(handshake_timeout, reader.next()) .await .expect("Timed out while receiving hello handshake packet!") .unwrap() .expect("Failed to receive hello handshake packet!"); if let Frame::Hello(mut hello) = frame { let matches = node == (hello.name.as_str(), hello.broadcast_address); if hello.validate() && matches { std::mem::forget(connector); return node_remote_supervisor(writer, reader, hello, supervisor.into_inner()).await; } else if !matches { panic!( "Node was not the expected node: {:?} (wanted) {:?} (received).", node, Node::from((hello.name, hello.broadcast_address)) ); } else { panic!("Node handshake failed validation!"); } } panic!("Received incorrect frame for node handshake!"); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_kernel.rs
hydra/src/node_kernel.rs
use crate::frame::Exit; use crate::frame::Frame; use crate::frame::Send; use crate::frame::SendTarget; use crate::ExitReason; use crate::Node; use crate::Pid; use crate::ProcessItem; use crate::Receivable; use crate::Reference; use crate::alias_retrieve; use crate::node_register; use crate::node_send_frame; use crate::process_name_lookup; use crate::process_sender; use crate::serialize_value; /// Forwards an incoming nodes send frame message to the target if it exists. pub fn node_forward_send(mut send: Send) { let is_single_target = send.targets.len() == 1; for target in send.targets { let message = if is_single_target { std::mem::take(&mut send.message) } else { send.message.clone() }; match target { SendTarget::Pid(id) => { process_sender(Pid::local(id.get())) .map(|sender| sender.send(ProcessItem::UserRemoteMessage(message))); } SendTarget::Named(name) => { process_name_lookup(&name) .and_then(process_sender) .map(|sender| sender.send(ProcessItem::UserRemoteMessage(message))); } SendTarget::Alias(alias) => { alias_retrieve(Reference::Local(alias)) .map(|alias| alias.sender.send(ProcessItem::UserRemoteMessage(message))); } } } } /// Sends an exit signal to the given pid. pub fn node_process_send_exit(pid: Pid, from: Pid, exit_reason: ExitReason) { let exit = Exit::new(pid.id(), from.id(), exit_reason); node_send_frame(Frame::from(exit), pid.node()); } /// Sends the given message to the remote node with the given pid. pub fn node_process_send_with_pid<M: Receivable>(pid: Pid, message: M) { let Pid::Remote(id, node) = pid else { panic!("Can't send to a local process!"); }; let message = serialize_value(&message); node_send_frame(Frame::from(Send::with_pid(id, message)), node); } /// Sends the given message to the remote node with the given alias. pub fn node_process_send_with_alias<M: Receivable>(reference: Reference, message: M) { let Reference::Remote(id, node) = reference else { panic!("Can't send to a local alias!"); }; let message = serialize_value(&message); node_send_frame(Frame::from(Send::with_alias(id, message)), node); } /// Sends the given message to the remote node with the given name/node. pub fn node_process_send_with_name<M: Receivable>(name: String, node: Node, message: M) { let message = serialize_value(&message); let node = node_register(node, false); node_send_frame(Frame::from(Send::with_name(name, message)), node); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node.rs
hydra/src/node.rs
use std::fmt::Debug; use std::net::SocketAddr; use serde::Deserialize; use serde::Serialize; use crate::NodeOptions; use crate::NodeState; use crate::PROCESS; use crate::Pid; use crate::Process; use crate::ProcessMonitor; use crate::Reference; use crate::node_alive; use crate::node_disconnect; use crate::node_forget; use crate::node_list; use crate::node_list_filtered; use crate::node_local_start; use crate::node_local_stop; use crate::node_lookup_local; use crate::node_monitor_create; use crate::node_monitor_destroy; use crate::node_register; use crate::node_set_cookie; /// Represents a [Node] serialized for the wire. #[derive(Serialize, Deserialize)] struct NodeWire { name: String, address: Option<SocketAddr>, } /// Represents a local or remote node of processes. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Node { Local, Remote(String, SocketAddr), } impl Node { /// Returns `true` if the local node is alive. pub fn alive() -> bool { node_alive() } /// Returns `true` if the node is the current node. pub const fn is_local(&self) -> bool { matches!(self, Node::Local) } /// Returns `true` if the node is a remote node. pub const fn is_remote(&self) -> bool { matches!(self, Node::Remote(_, _)) } /// Returns the current node. pub fn current() -> Node { Node::Local } /// Returns the adddress of the node if it's a remote node. pub fn address(&self) -> Option<SocketAddr> { match self { Node::Local => None, Node::Remote(_, address) => Some(*address), } } /// Returns the name of the node if it's a remote node. pub fn name(&self) -> Option<&str> { match self { Node::Local => None, Node::Remote(name, _) => Some(name), } } /// Connects to the given node if we're not already connected. pub fn connect<T: Into<Node>>(node: T) { let node = node.into(); let Node::Remote(name, address) = node else { panic!("Can't connect to self!"); }; node_register(Node::from((name, address)), true); } /// Forcefully disconnects from the given node. pub fn disconnect<T: Into<Node>>(node: T) { let node = node.into(); if !matches!(node, Node::Remote(_, _)) { panic!("Can't disconnect from self!"); } node_disconnect(node); } /// Forcefully disconnects, and forgets this node completely. /// /// All existing [Pid]'s for this node will no longer be reachable. pub fn forget<T: Into<Node>>(node: T) { let node = node.into(); if !matches!(node, Node::Remote(_, _)) { panic!("Can't forget from self!"); } node_forget(node); } /// Sets the node cookie used to secure node connections. pub fn set_cookie<T: Into<String>>(cookie: T) { node_set_cookie(Some(cookie.into())); } /// Clears the node cookie. pub fn clear_cookie() { node_set_cookie(None); } /// Turns a non-distributed node into a distributed node. pub fn start<T: Into<String>>(name: T, options: NodeOptions) -> Pid { node_local_start(name.into(), options) } /// Turns a distributed node into a non-distributed node. /// /// For other nodes in the network, this is the same as the node going down. pub fn stop() { node_local_stop(); } /// Returns a list of all visible nodes in the system, excluding the local node. pub fn list() -> Vec<Node> { node_list() } /// Returns a list of all nodes in the system that match the given state. pub fn list_by_state(state: NodeState) -> Vec<Node> { node_list_filtered(state) } /// Monitors the given node. If we're not currently connected, an attempt is made to connect. pub fn monitor<T: Into<Node>>(node: T) -> Reference { let current = Process::current(); let node = node.into(); if !matches!(node, Node::Remote(_, _)) { panic!("Can't monitor self!"); } let reference = Reference::new(); PROCESS.with(|process| { process .monitors .borrow_mut() .insert(reference, ProcessMonitor::ForNode(node.clone())) }); node_monitor_create(node.clone(), reference, current); node_register(node, true); reference } /// Demonitors the monitor identified by the given reference. pub fn demonitor(monitor: Reference) { let Some(process_monitor) = PROCESS.with(|process| process.monitors.borrow_mut().remove(&monitor)) else { return; }; let ProcessMonitor::ForNode(node) = process_monitor else { panic!("Invalid node monitor reference!"); }; node_monitor_destroy(node, monitor); } } impl Debug for Node { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Local => write!(f, "Node<local>"), Self::Remote(name, address) => write!(f, "Node<{}, {}>", name, address), } } } impl From<(&str, SocketAddr)> for Node { fn from(value: (&str, SocketAddr)) -> Self { Self::Remote(value.0.into(), value.1) } } impl From<(String, SocketAddr)> for Node { fn from(value: (String, SocketAddr)) -> Self { Self::Remote(value.0, value.1) } } impl From<&str> for Node { fn from(value: &str) -> Self { if value == "local" { return Self::Local; } let split = value.split_once('@').expect("Missing '@' in node string!"); Self::Remote( split.0.into(), split.1.parse().expect("Malformed address in node string!"), ) } } impl From<String> for Node { fn from(value: String) -> Self { Node::from(value.as_str()) } } impl PartialEq<(&str, SocketAddr)> for Node { fn eq(&self, other: &(&str, SocketAddr)) -> bool { match self { Self::Local => false, Self::Remote(name, address) => name == other.0 && *address == other.1, } } } impl PartialEq<(String, SocketAddr)> for Node { fn eq(&self, other: &(String, SocketAddr)) -> bool { match self { Self::Local => false, Self::Remote(name, address) => *name == other.0 && *address == other.1, } } } impl PartialEq<&str> for Node { fn eq(&self, other: &&str) -> bool { match self { Self::Local => *other == "local", Self::Remote(name, address) => { let Some((other_name, other_address)) = other.split_once('@') else { return false; }; if name != other_name { return false; } let Ok(parse_address) = other_address.parse::<SocketAddr>() else { return false; }; *address == parse_address } } } } impl PartialEq<String> for Node { fn eq(&self, other: &String) -> bool { self == &other.as_str() } } impl PartialEq<Node> for String { fn eq(&self, other: &Node) -> bool { other == self } } impl PartialEq<Node> for &str { fn eq(&self, other: &Node) -> bool { other == self } } impl Serialize for Node { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let node: NodeWire = match self { Self::Local => match node_lookup_local() { Some((name, address)) => NodeWire { name, address: Some(address), }, None => NodeWire { name: String::from("nohost"), address: None, }, }, Self::Remote(name, address) => NodeWire { name: name.clone(), address: Some(*address), }, }; node.serialize(serializer) } } impl<'de> Deserialize<'de> for Node { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let node: NodeWire = NodeWire::deserialize(deserializer)?; match node_lookup_local() { Some((name, address)) => { if node.name == name && (node.address.is_none() || node.address.is_some_and(|node| node == address)) { Ok(Node::Local) } else { Ok(Node::Remote(node.name, node.address.unwrap())) } } None => Ok(Node::Local), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/link.rs
hydra/src/link.rs
use std::collections::BTreeMap; use std::collections::BTreeSet; use dashmap::DashMap; use once_cell::sync::Lazy; use crate::frame::Link; use crate::frame::LinkDown; use crate::ExitReason; use crate::Node; use crate::Pid; use crate::ProcessInfo; use crate::node_lookup_remote; use crate::node_process_link_create; use crate::node_process_link_destroy; use crate::node_process_link_destroy_all; use crate::node_register; use crate::node_send_frame; use crate::process_exists_lock; use crate::process_exit_signal_linked; /// A collection of local processes linked to another process. static LINKS: Lazy<DashMap<u64, BTreeSet<Pid>>> = Lazy::new(DashMap::new); /// Creates a link for the given local process from the given process. Returns `true` if the link was created. pub fn link_create(process: Pid, from: Pid, ignore_errors: bool) -> bool { if ignore_errors { LINKS.entry(process.id()).or_default().insert(from); return true; } process_exists_lock(process, |exists| { if exists { LINKS.entry(process.id()).or_default().insert(from); true } else { false } }) } /// Installs a link for the given process. pub fn link_install(process: Pid, from: Pid) { link_create(from, process, false) .then_some(()) .expect("From process must exist at this point!"); if process.is_local() { if !link_create(process, from, false) { process_exit_signal_linked(from, process, ExitReason::from("noproc")); } } else { match node_lookup_remote(process.node()) { Some((name, address)) => { let node = Node::from((name, address)); node_process_link_create(node.clone(), process, from); let node = node_register(node, true); let link = Link::new(true, process.id(), from.id()); node_send_frame(link.into(), node); } None => { process_exit_signal_linked(from, process, ExitReason::from("noconnection")); } } } } /// Destroys a link for the given local process. pub fn link_destroy(process: Pid, from: Pid) { if process.is_local() { LINKS.alter(&process.id(), |_, mut value| { value.remove(&from); value }); } else { let link = Link::new(false, process.id(), from.id()); node_send_frame(link.into(), process.node()); if let Some((name, address)) = node_lookup_remote(process.node()) { node_process_link_destroy(Node::from((name, address)), process, from); } } } /// Sends the proper exit signal about the given process going down for the given reason. pub fn link_process_down(from: Pid, exit_reason: ExitReason) { let Some(links) = LINKS.remove(&from.id()).map(|(_, links)| links) else { return; }; let mut remote_links: BTreeMap<u64, (LinkDown, Vec<Pid>)> = BTreeMap::new(); for pid in links { if pid.is_local() { LINKS.alter(&pid.id(), |_, mut value| { value.remove(&from); value }); process_exit_signal_linked(pid, from, exit_reason.clone()); } else { let remote = remote_links .entry(pid.node()) .or_insert((LinkDown::new(from.id(), exit_reason.clone()), Vec::new())); remote.0.links.push(pid.id()); remote.1.push(pid); } } for (node, (link_down, links)) in remote_links { if let Some((name, address)) = node_lookup_remote(node) { node_process_link_destroy_all(Node::from((name, address)), links, from); } node_send_frame(link_down.into(), node); } } /// Fills in link information for a process. pub fn link_fill_info(pid: Pid, info: &mut ProcessInfo) { let Some(links) = LINKS.get(&pid.id()) else { return; }; info.links = links.value().iter().copied().collect(); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/registry_options.rs
hydra/src/registry_options.rs
use crate::GenServerOptions; /// Options used to configure a Registry. #[derive(Debug, Default, Clone)] pub struct RegistryOptions { pub(crate) name: Option<String>, } impl RegistryOptions { /// Constructs a new instance of [RegistryOptions] with the default values. pub const fn new() -> Self { Self { name: None } } /// Specifies a name to register the Registry under. pub fn name<T: Into<String>>(mut self, name: T) -> Self { self.name = Some(name.into()); self } } impl From<RegistryOptions> for GenServerOptions { fn from(mut value: RegistryOptions) -> Self { let mut options = GenServerOptions::new(); if let Some(name) = value.name.take() { options = options.name(name); } options } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/from.rs
hydra/src/from.rs
use serde::Deserialize; use serde::Serialize; use crate::Pid; use crate::Reference; /// Information about a GenServer call request. #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct From { pid: Pid, tag: Reference, alias: bool, } impl From { /// Constructs a new instance of [From]. pub(crate) const fn new(pid: Pid, tag: Reference, alias: bool) -> Self { Self { pid, tag, alias } } /// Gets the process which sent this call. pub const fn pid(&self) -> Pid { self.pid } /// Gets the unique identifier for call. pub const fn tag(&self) -> Reference { self.tag } /// Gets whether or not the tag is an alias. pub const fn is_alias(&self) -> bool { self.alias } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/local.rs
hydra/src/local.rs
use serde::Deserialize; use serde::Serialize; use std::ops::Deref; use std::ops::DerefMut; /// Represents a local object in the current process userspace. /// /// A [Local] can be used to send any `T: Send + 'static` type to another local process. #[repr(transparent)] #[derive(Debug, Clone, Copy)] pub struct Local<T: Send + 'static>(T); impl<T> Local<T> where T: Send + 'static, { /// Constructs a new [Local] for the given object in the current process userspace. pub const fn new(local: T) -> Self { Self(local) } /// Retrieves the object in the current process userspace. pub fn into_inner(self) -> T { self.0 } } impl<T> Deref for Local<T> where T: Send + 'static, { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for Local<T> where T: Send + 'static, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T> Serialize for Local<T> where T: Send + 'static, { fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { panic!("Can't send `Local<T>` to a remote process!") } } impl<'de, T> Deserialize<'de> for Local<T> where T: Send + 'static, { fn deserialize<D>(_: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Err(serde::de::Error::custom( "Can't receive `Local<T>` from a remote process!", )) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/pid.rs
hydra/src/pid.rs
use std::fmt::Debug; use std::net::SocketAddr; use std::num::NonZeroU64; use serde::Deserialize; use serde::Serialize; use crate::INVALID_NODE_ID; use crate::LOCAL_NODE_ID; use crate::Node; use crate::node_lookup_local; use crate::node_lookup_remote; use crate::node_register; /// The representation of a [Pid] serialized for the wire. #[derive(Serialize, Deserialize)] enum PidWire { WithNode(NonZeroU64, String, SocketAddr), NodeUnavailable(NonZeroU64), } /// A unique identifier of a process in hydra. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Pid { Local(NonZeroU64), Remote(NonZeroU64, u64), } impl Pid { /// Constructs a new [Pid] from the given process id, assigning it to the local node. pub(crate) fn local(id: u64) -> Self { Self::Local(NonZeroU64::new(id).unwrap()) } /// Constructs a new [Pid] from the given process id, assigning it to the remote node. pub(crate) fn remote(id: u64, node: u64) -> Self { Self::Remote(NonZeroU64::new(id).unwrap(), node) } /// Returns `true` if this [Pid] is a local process. pub const fn is_local(&self) -> bool { matches!(self, Self::Local(_)) } /// Returns `true` if this [Pid] is a remote process. pub const fn is_remote(&self) -> bool { matches!(self, Self::Remote(_, _)) } /// Gets the id part of the [Pid]. pub(crate) const fn id(&self) -> u64 { match self { Self::Local(id) => id.get(), Self::Remote(id, _) => id.get(), } } /// Gets the node part of the [Pid]. pub(crate) const fn node(&self) -> u64 { match self { Self::Local(_) => LOCAL_NODE_ID, Self::Remote(_, node) => *node, } } } impl Debug for Pid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Local(id) => write!(f, "Pid<0, {}>", id), Self::Remote(id, node) => write!(f, "Pid<{}, {}>", node, id), } } } impl Serialize for Pid { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let pid: PidWire = match self { Self::Local(id) => match node_lookup_local() { Some((name, address)) => PidWire::WithNode(*id, name, address), None => PidWire::NodeUnavailable(*id), }, Self::Remote(id, node) => match node_lookup_remote(*node) { Some((name, address)) => PidWire::WithNode(*id, name, address), None => PidWire::NodeUnavailable(*id), }, }; pid.serialize(serializer) } } impl<'de> Deserialize<'de> for Pid { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let node: PidWire = PidWire::deserialize(deserializer)?; match node { PidWire::WithNode(id, node_name, node_address) => match node_lookup_local() { Some((name, address)) => { if name == node_name && address == node_address { Ok(Pid::Local(id)) } else { let node = node_register(Node::from((node_name, node_address)), false); Ok(Pid::Remote(id, node)) } } None => Ok(Pid::Remote(id, INVALID_NODE_ID)), }, PidWire::NodeUnavailable(id) => Ok(Self::Remote(id, INVALID_NODE_ID)), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/lib.rs
hydra/src/lib.rs
mod alias; mod application; mod application_config; mod argument_error; mod call_error; mod catch_unwind; mod child_spec; mod dest; mod exit_reason; mod frame; mod from; mod gen_server; mod gen_server_options; mod hash_ring; mod link; mod local; mod message; mod monitor; mod node; mod node_kernel; mod node_local; mod node_options; mod node_registration; mod node_registry; mod node_remote; mod node_state; mod pid; mod process; mod process_flags; mod process_info; mod process_item; mod process_kernel; mod process_monitor; mod process_receiver; mod process_registration; mod process_registry; mod receivable; mod reference; mod registry; mod registry_options; mod restart; mod semaphore; mod serialize; mod shutdown; mod supervisor; mod supervisor_options; mod system_message; mod task; mod timeout; #[cfg(feature = "console")] mod console; #[cfg(feature = "console")] mod runtime_info; pub use application::*; pub use application_config::*; pub use argument_error::*; pub use call_error::*; pub use child_spec::*; pub use dest::*; pub use exit_reason::*; pub use from::*; pub use gen_server::*; pub use gen_server_options::*; pub use hash_ring::*; pub use local::*; pub use message::*; pub use node::*; pub use node_options::*; pub use node_state::*; pub use pid::*; pub use process::*; pub use process_flags::*; pub use process_info::*; pub use process_receiver::*; pub use receivable::*; pub use reference::*; pub use registry::*; pub use registry_options::*; pub use restart::*; pub use semaphore::*; pub use shutdown::*; pub use supervisor::*; pub use supervisor_options::*; pub use system_message::*; pub use task::*; pub use timeout::*; #[cfg(feature = "macros")] pub use hydra_macros::main; #[cfg(feature = "macros")] pub use hydra_macros::test; #[cfg(feature = "console")] pub use console::*; #[cfg(feature = "console")] pub use runtime_info::*; pub(crate) use alias::*; pub(crate) use catch_unwind::*; pub(crate) use link::*; pub(crate) use monitor::*; pub(crate) use node_kernel::*; pub(crate) use node_local::*; pub(crate) use node_registration::*; pub(crate) use node_registry::*; pub(crate) use node_remote::*; pub(crate) use process_item::*; pub(crate) use process_kernel::*; pub(crate) use process_monitor::*; pub(crate) use process_registration::*; pub(crate) use process_registry::*; pub(crate) use serialize::*;
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/shutdown.rs
hydra/src/shutdown.rs
use std::time::Duration; use crate::ExitReason; use crate::Message; use crate::Pid; use crate::Process; use crate::Reference; use crate::SystemMessage; /// Defines how a child process should be terminated. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Shutdown { /// The child process is unconditionally and immediately terminated using `Process::exit(child, ExitReason::Kill)`. BrutalKill, /// The amount of time that the parent will wait for it's children to terminate after emitting a /// `Process::exit(child, ExitReason::from("shutdown"))` signal. If the child process is not trapping exits, the initial `shutdown` signal /// will terminate the child process immediately. If the child process is trapping exits, it has the given duration to terminate. Duration(Duration), /// The parent will wait indefinitely for the child to terminate. Infinity, } /// Defines how a superviser should handle shutdown when a significant process exits. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum AutoShutdown { /// This is the default, automatic shutdown is disabled. Never, /// If any significant child process exits, the supervisor will automatically shut down it's children, then itself. AnySignificant, /// When all significant child processes have exited, the supervisor will automatically shut down it's children, then itself. AllSignificant, } impl From<Duration> for Shutdown { fn from(value: Duration) -> Self { Self::Duration(value) } } /// Terminates the given `pid` by forcefully killing it and waiting for the `monitor` to fire. pub(crate) async fn shutdown_brutal_kill(pid: Pid, monitor: Reference) -> Result<(), ExitReason> { Process::exit(pid, ExitReason::Kill); let result = Process::receiver() .for_message::<()>() .select(|message| { match message { Message::System(SystemMessage::ProcessDown(_, tag, _)) => { // Make sure that the tag matches. *tag == monitor } _ => false, } }) .await; let Message::System(SystemMessage::ProcessDown(_, _, reason)) = result else { unreachable!() }; unlink_flush(pid, reason); Ok(()) } /// Terminates the given `pid` by gracefully waiting for `timeout` /// then forcefully kills it as necessary while waiting for `monitor` to fire. pub(crate) async fn shutdown_timeout( pid: Pid, monitor: Reference, timeout: Duration, ) -> Result<(), ExitReason> { Process::exit(pid, ExitReason::from("shutdown")); let receiver = Process::receiver() .select(|message| matches!(message, Message::System(SystemMessage::ProcessDown(_, tag, _)) if *tag == monitor)); let result = Process::timeout(timeout, receiver).await; match result { Ok(Message::System(SystemMessage::ProcessDown(_, _, reason))) => { unlink_flush(pid, reason); Ok(()) } Ok(_) => unreachable!(), Err(_) => shutdown_brutal_kill(pid, monitor).await, } } /// Terminates the given `pid` by gracefully waiting indefinitely for the `monitor` to fire. pub(crate) async fn shutdown_infinity(pid: Pid, monitor: Reference) -> Result<(), ExitReason> { Process::exit(pid, ExitReason::from("shutdown")); let result = Process::receiver() .select(|message| matches!(message, Message::System(SystemMessage::ProcessDown(_, tag, _)) if *tag == monitor)) .await; let Message::System(SystemMessage::ProcessDown(_, _, reason)) = result else { unreachable!() }; unlink_flush(pid, reason); Ok(()) } /// Unlinks the given process and ensures that any pending exit signal is flushed from the message queue. /// /// Returns the real [ExitReason] or the `default_reason` if no signal was found. fn unlink_flush(pid: Pid, default_reason: ExitReason) -> ExitReason { Process::unlink(pid); let mut reason = default_reason; Process::receiver().remove(|message| match message { Message::System(SystemMessage::Exit(epid, ereason)) => { if *epid == pid { reason = ereason.clone(); return true; } false } _ => false, }); reason }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/timeout.rs
hydra/src/timeout.rs
use serde::Deserialize; use serde::Serialize; /// Occurs when an operation has timed out. #[derive(Debug, Serialize, Deserialize)] pub struct Timeout;
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process.rs
hydra/src/process.rs
use std::cell::RefCell; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::future::Future; use std::panic::AssertUnwindSafe; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; use flume::Receiver; use flume::Sender; use crate::ArgumentError; use crate::AsyncCatchUnwind; use crate::Dest; use crate::Dests; use crate::ExitReason; use crate::Message; use crate::Pid; use crate::ProcessFlags; use crate::ProcessInfo; use crate::ProcessItem; use crate::ProcessMonitor; use crate::ProcessReceiver; use crate::ProcessRegistration; use crate::Receivable; use crate::Reference; use crate::Timeout; use crate::alias_create; use crate::alias_destroy; use crate::alias_destroy_all; use crate::link_create; use crate::link_destroy; use crate::link_fill_info; use crate::link_install; use crate::link_process_down; use crate::monitor_create; use crate::monitor_destroy; use crate::monitor_destroy_all; use crate::monitor_fill_info; use crate::monitor_install; use crate::monitor_process_down; use crate::node_process_send_exit; use crate::process_alive; use crate::process_destroy_timer; use crate::process_drop; use crate::process_exit; use crate::process_flags; use crate::process_info; use crate::process_insert; use crate::process_list; use crate::process_name_list; use crate::process_name_lookup; use crate::process_name_remove; use crate::process_read_timer; use crate::process_register; use crate::process_register_timer; use crate::process_send; use crate::process_set_exit_reason; use crate::process_set_flags; use crate::process_unregister; /// The send type for a process. pub(crate) type ProcessSend = Sender<ProcessItem>; /// The receive type for a process. pub(crate) type ProcessReceive = Receiver<ProcessItem>; /// A light weight task that can send and receive messages. pub struct Process { /// The unique id of this process. pub(crate) pid: Pid, /// The sender for this process. pub(crate) sender: ProcessSend, /// The receiver for this process. pub(crate) receiver: ProcessReceive, /// The messages already popped from the receiver for this process. pub(crate) items: RefCell<Vec<ProcessItem>>, /// A collection of process aliases. pub(crate) aliases: RefCell<BTreeSet<u64>>, /// A collection of process monitor references. pub(crate) monitors: RefCell<BTreeMap<Reference, ProcessMonitor>>, } tokio::task_local! { /// Current process information. pub(crate) static PROCESS: Process; } impl Process { /// Constructs a new [Process] from the given [Pid] and channels. pub(crate) fn new(pid: Pid, sender: ProcessSend, receiver: ProcessReceive) -> Self { Self { pid, sender, receiver, items: RefCell::new(Vec::new()), aliases: RefCell::new(BTreeSet::new()), monitors: RefCell::new(BTreeMap::new()), } } /// Creates a process alias. If reply is `true` the alias deactivates when the first message is received. /// /// Otherwise, you need to call `unalias(reference)` to deactivate the alias. pub fn alias(reply: bool) -> Reference { let reference = Reference::new(); let sender = PROCESS.with(|process| { process.aliases.borrow_mut().insert(reference.id()); process.sender.clone() }); alias_create(sender, reference, reply); reference } /// Explicitly deactivates a process alias. /// /// Returns `true` if the alias was currently-active for the current process, or `false` otherwise. pub fn unalias(alias: Reference) -> bool { PROCESS.with(|process| process.aliases.borrow_mut().remove(&alias.id())); alias_destroy(alias) } /// Returns the current [Pid]. #[must_use] pub fn current() -> Pid { PROCESS.with(|process| process.pid) } /// Returns the [Pid] registered under `name` or [None] if the name is not registered. #[must_use] pub fn whereis<S: AsRef<str>>(name: S) -> Option<Pid> { process_name_lookup(name.as_ref()) } /// Sends a message to `dests`. /// /// ## Example: /// This method allows sending to multiple targets with certain trade offs: /// ```ignore /// let pid1 = Process::spawn(async { /* */ }); /// let pid2 = Process::spawn(async { /* */ }); /// /// // faster when all processes are local. /// for pid in &[pid1, pid2] { /// Process::send(pid, "hello world!"); /// } /// /// // faster when processes are mostly remote. /// Process::send(&[pid1, pid2], "hello world!"); /// ``` pub fn send<D: Into<Dests>, M: Receivable>(dests: D, message: M) { process_send(dests.into(), message); } /// Sends a message to `dests` after the given `duration`. /// /// See [Process::send] for performance trade-offs. /// /// ## Example: /// Sends a message after 5 seconds to `pid`: /// ```ignore /// Process::send_after(pid, "hello world!", Duration::from_secs(5)); /// ``` pub fn send_after<D: Into<Dests>, M: Receivable>( dest: D, message: M, duration: Duration, ) -> Reference { let dest = dest.into(); let reference = Reference::new(); let handle = tokio::spawn(async move { Process::sleep(duration).await; Process::send(dest, message); process_destroy_timer(reference); }); process_register_timer(reference, duration, handle); reference } /// Cancels a timer created by `send_after`. pub fn cancel_timer(timer: Reference) { process_destroy_timer(timer); } /// Reads a timer created by `send_after`. /// /// It returns the time remaining until the timer expires. pub fn read_timer(timer: Reference) -> Option<Duration> { process_read_timer(timer) } /// Creates a receiver with advanced filtering options from the current processes mailbox. #[must_use] pub fn receiver() -> ProcessReceiver<()> { ProcessReceiver::new() } /// Creates a receiver for a single message that matches the given type from the current processes mailbox. /// /// This will panic if a message is received that doesn't match the given type. #[must_use] pub async fn receive<T: Receivable>() -> Message<T> { ProcessReceiver::new() .strict_type_checking() .receive() .await } /// Spawns the given `function` as a process and returns it's [Pid]. pub fn spawn<T>(function: T) -> Pid where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static, { match spawn_internal(function, false, false) { SpawnResult::Pid(pid) => pid, SpawnResult::PidMonitor(_, _) => unreachable!(), } } /// Spawns the given `function` as a process, creates a link between the calling process, and returns the new [Pid]. pub fn spawn_link<T>(function: T) -> Pid where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static, { match spawn_internal(function, true, false) { SpawnResult::Pid(pid) => pid, SpawnResult::PidMonitor(_, _) => unreachable!(), } } /// Spawns the given `function` as a process, creates a monitor for the calling process, and returns the new [Pid]. pub fn spawn_monitor<T>(function: T) -> (Pid, Reference) where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static, { match spawn_internal(function, false, true) { SpawnResult::Pid(_) => unreachable!(), SpawnResult::PidMonitor(pid, monitor) => (pid, monitor), } } /// Returns true if the given [Pid] is alive on the local node. #[must_use] pub fn alive(pid: Pid) -> bool { process_alive(pid) } /// Sleeps the current process for the given duration. pub async fn sleep(duration: Duration) { tokio::time::sleep(duration).await } /// Waits for the given future to complete until the given duration is up. pub async fn timeout<F>(duration: Duration, future: F) -> Result<<F as Future>::Output, Timeout> where F: Future, { pingora_timeout::timeout(duration, future) .await .map_err(|_| Timeout) } /// Registers the given [Pid] under `name` if the process is local, active, and the name is not already registered. pub fn register<S: Into<String>>(pid: Pid, name: S) -> Result<(), ArgumentError> { process_register(pid, name.into()) } /// Removes the registered `name`, associated with a [Pid]. pub fn unregister<S: AsRef<str>>(name: S) { process_unregister(name.as_ref()); } /// Returns a [Vec] of registered process names. #[must_use] pub fn registered() -> Vec<String> { process_name_list() } /// Returns a [Vec] of [Pid]'s on the local node. #[must_use] pub fn list() -> Vec<Pid> { process_list() } /// Creates a bi-directional link between the current process and the given process. pub fn link(pid: Pid) { let current = Self::current(); if pid == current { return; } link_install(pid, current); } /// Removes the link between the calling process and the given process. pub fn unlink(pid: Pid) { let current = Self::current(); if pid == current { return; } link_destroy(pid, current); } /// Starts monitoring the given process from the calling process. If the process is already dead a message is sent immediately. pub fn monitor<T: Into<Dest>>(process: T) -> Reference { let current = Self::current(); let process = process.into(); let reference = Reference::new(); monitor_install(process, reference, current); reference } /// Starts monitoring the given process from the calling process. If the process is already dead a message is sent immediately. /// /// Creates an alias for the calling process that's tied to the process monitor. /// /// The alias will be deactivated if: /// - The monitor sends a down message. /// - The user explicitly calls `unalias`. (The monitor will remain active) /// - `reply` is `true` and a message is sent over the alias. pub fn monitor_alias<T: Into<Dest>>(process: T, reply: bool) -> Reference { let current = Self::current(); let process = process.into(); let sender = PROCESS.with(|process| process.sender.clone()); let reference = Reference::new(); alias_create(sender, reference, reply); monitor_install(process, reference, current); reference } /// Demonitors the monitor identified by the given reference. /// /// If a monitor message was sent to the process already but was not received, it will be discarded automatically. pub fn demonitor(monitor: Reference) { let Some(process_monitor) = PROCESS.with(|process| process.monitors.borrow_mut().remove(&monitor)) else { return; }; let ProcessMonitor::ForProcess(pid) = process_monitor else { panic!("Invalid process monitor reference!"); }; let Some(pid) = pid else { return; }; monitor_destroy(pid, monitor); alias_destroy(monitor); } /// Returns the current process flags. #[must_use] pub fn flags() -> ProcessFlags { process_flags(Self::current()).unwrap() } /// Sets one or more process flags. pub fn set_flags(flags: ProcessFlags) { process_set_flags(Self::current(), flags) } /// Sends an exit signal with the given reason to [Pid]. pub fn exit<E: Into<ExitReason>>(pid: Pid, exit_reason: E) { let exit_reason = exit_reason.into(); if pid.is_local() { process_exit(pid, Self::current(), exit_reason); } else { node_process_send_exit(pid, Self::current(), exit_reason); } } /// Fetches debug information for a given local process. #[must_use] pub fn info(pid: Pid) -> Option<ProcessInfo> { if pid.is_remote() { panic!("Can't query information on a remote process!"); } let info = process_info(pid); info.map(|mut info| { link_fill_info(pid, &mut info); monitor_fill_info(pid, &mut info); info }) } } impl Drop for Process { fn drop(&mut self) { let process = process_drop(self.pid).unwrap(); if let Some(name) = process.name { process_name_remove(&name); } let exit_reason = process.exit_reason.unwrap_or_default(); link_process_down(self.pid, exit_reason.clone()); monitor_process_down(self.pid, exit_reason); monitor_destroy_all(self.monitors.borrow().iter()); alias_destroy_all(self.aliases.borrow().iter()); } } /// Internal spawn result. enum SpawnResult { Pid(Pid), PidMonitor(Pid, Reference), } /// The next process id to allocate if free. static ID: AtomicU64 = AtomicU64::new(1); /// Internal spawn utility. fn spawn_internal<T>(function: T, link: bool, monitor: bool) -> SpawnResult where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static, { let next_id = ID.fetch_add(1, Ordering::Relaxed); let (tx, rx) = flume::unbounded(); let pid = Pid::local(next_id); let process = Process::new(pid, tx.clone(), rx); let mut result = SpawnResult::Pid(pid); // If a link was requested, insert it before spawning the process. if link { let current = Process::current(); link_create(pid, current, true); link_create(current, pid, true); } // If a monitor was requested, insert it before spawning the process. if monitor { let monitor = Reference::new(); PROCESS.with(|process| { process .monitors .borrow_mut() .insert(monitor, ProcessMonitor::ForProcess(Some(pid))) }); monitor_create(pid, monitor, Process::current(), Some(pid.into())); result = SpawnResult::PidMonitor(pid, monitor); } // Spawn the process with the newly created process object in scope. let handle = tokio::spawn(PROCESS.scope(process, async move { if let Err(e) = AsyncCatchUnwind::new(AssertUnwindSafe(function)).await { process_set_exit_reason(Process::current(), e.into()); } })); // Register the process under it's new id. process_insert(next_id, ProcessRegistration::new(handle, tx)); result }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/argument_error.rs
hydra/src/argument_error.rs
/// Occurs when an argument to a function was incorrect or not valid at the given time. #[derive(Debug)] pub struct ArgumentError(pub String); impl<T> From<T> for ArgumentError where T: Into<String>, { fn from(value: T) -> Self { Self(value.into()) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/dest.rs
hydra/src/dest.rs
use std::borrow::Cow; use serde::Deserialize; use serde::Serialize; use crate::Node; use crate::Pid; use crate::Reference; /// A process destination. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub enum Dest { /// A process id. Pid(Pid), /// A registered process name. Named(Cow<'static, str>, Node), /// A reference to an alias. Alias(Reference), } /// One or more process destinations. #[derive(Debug)] pub enum Dests { /// A single process destination. Dest(Dest), /// Mutiple process destinations. Dests(Vec<Dest>), } impl Dest { /// Returns `true` if the [Dest] is for a local process. pub const fn is_local(&self) -> bool { match self { Self::Pid(pid) => pid.is_local(), Self::Named(_, node) => node.is_local(), Self::Alias(reference) => reference.is_local(), } } /// Returns `true` if the [Dest] is for a remote process. pub const fn is_remote(&self) -> bool { match self { Self::Pid(pid) => pid.is_remote(), Self::Named(_, node) => node.is_remote(), Self::Alias(reference) => reference.is_remote(), } } } impl From<Pid> for Dest { fn from(value: Pid) -> Self { Self::Pid(value) } } impl From<&'static str> for Dest { fn from(value: &'static str) -> Self { Self::Named(value.into(), Node::Local) } } impl From<String> for Dest { fn from(value: String) -> Self { Self::Named(value.into(), Node::Local) } } impl<T> From<(String, T)> for Dest where T: Into<Node>, { fn from(value: (String, T)) -> Self { Self::Named(value.0.into(), value.1.into()) } } impl<T> From<(&'static str, T)> for Dest where T: Into<Node>, { fn from(value: (&'static str, T)) -> Self { Self::Named(value.0.into(), value.1.into()) } } impl From<Reference> for Dest { fn from(value: Reference) -> Self { Self::Alias(value) } } impl PartialEq<Pid> for Dest { fn eq(&self, other: &Pid) -> bool { match self { Self::Pid(pid) => pid == other, _ => false, } } } impl PartialEq<Dest> for Pid { fn eq(&self, other: &Dest) -> bool { match other { Dest::Pid(pid) => self == pid, _ => false, } } } impl PartialEq<&str> for Dest { fn eq(&self, other: &&str) -> bool { match self { Self::Named(name, _) => name == other, _ => false, } } } impl PartialEq<Dest> for &str { fn eq(&self, other: &Dest) -> bool { match other { Dest::Named(name, _) => self == name, _ => false, } } } impl PartialEq<Reference> for Dest { fn eq(&self, other: &Reference) -> bool { match self { Self::Alias(reference) => reference == other, _ => false, } } } impl PartialEq<Dest> for Reference { fn eq(&self, other: &Dest) -> bool { match other { Dest::Alias(reference) => reference == other, _ => false, } } } impl From<Pid> for Dests { fn from(value: Pid) -> Self { Self::Dest(Dest::from(value)) } } impl From<Reference> for Dests { fn from(value: Reference) -> Self { Self::Dest(Dest::from(value)) } } impl From<&'static str> for Dests { fn from(value: &'static str) -> Self { Self::Dest(Dest::Named(value.into(), Node::Local)) } } impl<T> From<(String, T)> for Dests where T: Into<Node>, { fn from(value: (String, T)) -> Self { Self::Dest(Dest::Named(value.0.into(), value.1.into())) } } impl<T> From<(&'static str, T)> for Dests where T: Into<Node>, { fn from(value: (&'static str, T)) -> Self { Self::Dest(Dest::Named(value.0.into(), value.1.into())) } } impl From<String> for Dests { fn from(value: String) -> Self { Self::Dest(Dest::Named(value.into(), Node::Local)) } } impl From<&[Pid]> for Dests { fn from(value: &[Pid]) -> Self { if value.len() == 1 { Self::Dest(Dest::from(value[0])) } else { Self::Dests(value.iter().copied().map(Into::into).collect()) } } } impl From<Dest> for Dests { fn from(value: Dest) -> Self { Self::Dest(value) } } impl From<&[Dest]> for Dests { fn from(value: &[Dest]) -> Self { if value.len() == 1 { Self::Dest(value[0].to_owned()) } else { Self::Dests(Vec::from(value)) } } } impl From<Vec<Dest>> for Dests { fn from(value: Vec<Dest>) -> Self { Self::Dests(value) } } impl From<Vec<Pid>> for Dests { fn from(value: Vec<Pid>) -> Self { Self::Dests(value.into_iter().map(Into::into).collect()) } } impl From<&Vec<Pid>> for Dests { fn from(value: &Vec<Pid>) -> Self { Self::Dests(value.iter().copied().map(Into::into).collect()) } } impl FromIterator<Dest> for Dests { fn from_iter<T: IntoIterator<Item = Dest>>(iter: T) -> Self { Self::Dests(Vec::from_iter(iter)) } } impl FromIterator<Pid> for Dests { fn from_iter<T: IntoIterator<Item = Pid>>(iter: T) -> Self { Self::Dests(Vec::from_iter(iter.into_iter().map(Into::into))) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/hash_ring.rs
hydra/src/hash_ring.rs
use std::hash::BuildHasher; use std::hash::Hash; use std::hash::RandomState; use std::sync::Arc; use std::sync::Mutex; use arc_swap::ArcSwap; use dashmap::DashMap; /// Internal key, node pair. #[derive(Clone)] struct Node<T: Clone> { key: u64, node: T, } impl<T> Node<T> where T: Clone, { /// Constructs a new instance of [Node]. pub const fn new(key: u64, node: T) -> Self { Self { key, node } } } /// A concurrent, consistent hash ring. /// /// Provides the following features: /// - Lookup optimized ring storage. /// - Key overrides that allow you to pin a key to a specific node. pub struct HashRing<T: Clone, S = RandomState> { hash_builder: S, ring: ArcSwap<Vec<Node<T>>>, ring_lock: Mutex<()>, overrides: DashMap<u64, T>, } impl<T> HashRing<T> where T: Clone, { /// Constructs a new instance of [HashRing]. pub fn new() -> Self { Self { hash_builder: RandomState::new(), ring: ArcSwap::new(Arc::new(Vec::new())), ring_lock: Mutex::new(()), overrides: DashMap::new(), } } /// Adds a node to the existing set of nodes in the ring, this will replace an entry if one exists. pub fn add_node<K: Hash>(&self, key: K, node: T) -> Option<T> { let key = self.hash_key(key); let _ring_lock = self.ring_lock.lock().unwrap(); let mut new_ring: Vec<_> = self.ring.load().iter().cloned().collect(); match new_ring.binary_search_by(|node| node.key.cmp(&key)) { Ok(existing) => { let swapped = std::mem::replace(&mut new_ring[existing], Node::new(key, node)); self.ring.store(Arc::new(new_ring)); Some(swapped.node) } Err(index) => { new_ring.insert(index, Node::new(key, node)); self.ring.store(Arc::new(new_ring)); None } } } /// Removes a node from the existing set of nodes. pub fn remove_node<K: Hash>(&self, key: K) -> Option<T> { let key = self.hash_key(key); let _ring_lock = self.ring_lock.lock().unwrap(); let mut new_ring: Vec<_> = self.ring.load().iter().cloned().collect(); if let Ok(existing) = new_ring.binary_search_by(|node| node.key.cmp(&key)) { let existing = new_ring.remove(existing); self.ring.store(Arc::new(new_ring)); return Some(existing.node); } None } /// Adds a collection of nodes to the existing set of nodes in the ring, replacing any existing entries if they exist. pub fn add_nodes<K: Hash, I: IntoIterator<Item = (K, T)>>(&self, nodes: I) { let _ring_lock = self.ring_lock.lock().unwrap(); let mut new_ring: Vec<_> = self.ring.load().iter().cloned().collect(); for (key, node) in nodes.into_iter() { let key = self.hash_key(key); match new_ring.binary_search_by(|node| node.key.cmp(&key)) { Ok(existing) => { let _ = std::mem::replace(&mut new_ring[existing], Node::new(key, node)); } Err(index) => new_ring.insert(index, Node::new(key, node)), } } self.ring.store(Arc::new(new_ring)); } /// Replaces the nodes in the ring with a new set of nodes. pub fn set_nodes<K: Hash, I: IntoIterator<Item = (K, T)>>(&self, nodes: I) { let _ring_lock = self.ring_lock.lock().unwrap(); let nodes = nodes.into_iter(); let mut new_ring: Vec<Node<T>> = Vec::with_capacity(nodes.size_hint().0); for (key, node) in nodes { let key = self.hash_key(key); match new_ring.binary_search_by(|node| node.key.cmp(&key)) { Ok(existing) => { let _ = std::mem::replace(&mut new_ring[existing], Node::new(key, node)); } Err(index) => new_ring.insert(index, Node::new(key, node)), } } self.ring.store(Arc::new(new_ring)); } /// Returns the node responsible for `key`. If there are no nodes in the ring, it will return `None`. pub fn find_node<K: Hash>(&self, key: K) -> Option<T> { let mut result: Option<T> = None; self.map_node(key, |value| result = value.cloned()); result } /// Finds the node responsible for the given `key` and passes it to `map`. #[inline] pub fn map_node<K: Hash, F: FnMut(Option<&T>)>(&self, key: K, mut map: F) { let key = self.hash_key(key); if let Some(entry) = self.overrides.get(&key) { return map(Some(entry.value())); } let ring = self.ring.load(); if ring.is_empty() { return map(None); } let index = match ring.binary_search_by(|node| node.key.cmp(&key)) { Ok(index) => index, Err(index) => index, }; if index == ring.len() { return map(Some(&ring[0].node)); } map(Some(&ring[index].node)); } /// Adds an override to the ring. pub fn add_override<K: Hash>(&self, key: K, node: T) -> Option<T> { self.overrides.insert(self.hash_key(key), node) } /// Adds a collection of overrides to the ring. pub fn add_overrides<K: Hash, I: IntoIterator<Item = (K, T)>>(&self, overrides: I) { for (key, node) in overrides { self.overrides.insert(self.hash_key(key), node); } } /// Replaces the overrides in the ring with a new set of overrides. pub fn set_overrides<K: Hash, I: IntoIterator<Item = (K, T)>>(&self, overrides: I) { self.overrides.clear(); for (key, node) in overrides { self.overrides.insert(self.hash_key(key), node); } } /// Removes an existing override from the ring. pub fn remove_override<K: Hash>(&self, key: K) -> Option<T> { self.overrides .remove(&self.hash_key(key)) .map(|entry| entry.1) } /// Clears all of the nodes and overrides from the hash ring. pub fn clear(&self) { let _ring_lock = self.ring_lock.lock().unwrap(); self.ring.store(Arc::new(Vec::new())) } /// Hashes the given key using the selected hasher. #[inline(always)] fn hash_key<K: Hash>(&self, key: K) -> u64 { self.hash_builder.hash_one(key) } } impl<T> Default for HashRing<T> where T: Clone, { fn default() -> Self { Self::new() } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_state.rs
hydra/src/node_state.rs
use serde::Deserialize; use serde::Serialize; /// The different states a node can be in. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)] pub enum NodeState { /// This node is the local node. Current, /// This node information was given to us, but no attempt to connect has been made. Known, /// This node is currently connected. Connected, /// This node is pending a connection. Pending, }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/exit_reason.rs
hydra/src/exit_reason.rs
use bincode::Decode; use bincode::Encode; use serde::Deserialize; use serde::Serialize; /// Represents the reason a process exits. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)] pub enum ExitReason { /// Exited due to normal reasons, function ended, or manually stopped. #[default] Normal, /// Forceful kill reason. Kill, /// Ignored reason. Ignore, /// Custom exit reason. Custom(String), } impl ExitReason { /// Whether or not the reason is normal. pub const fn is_normal(&self) -> bool { matches!(self, ExitReason::Normal) } /// Whether or not the reason is kill. pub const fn is_kill(&self) -> bool { matches!(self, ExitReason::Kill) } /// Whether or not the reason is ignore. pub const fn is_ignore(&self) -> bool { matches!(self, ExitReason::Ignore) } /// Whether or not the reason is custom. pub const fn is_custom(&self) -> bool { matches!(self, ExitReason::Custom(_)) } } impl From<String> for ExitReason { fn from(value: String) -> Self { Self::Custom(value) } } impl From<&str> for ExitReason { fn from(value: &str) -> Self { Self::Custom(value.to_string()) } } impl PartialEq<&str> for ExitReason { fn eq(&self, other: &&str) -> bool { match self { Self::Custom(reason) => reason == other, _ => false, } } } impl PartialEq<ExitReason> for &str { fn eq(&self, other: &ExitReason) -> bool { match other { ExitReason::Custom(reason) => self == reason, _ => false, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_options.rs
hydra/src/node_options.rs
use std::net::IpAddr; use std::net::Ipv4Addr; use std::net::SocketAddr; use std::time::Duration; /// Options used to configure this node as a distributed node. #[derive(Clone, Copy)] pub struct NodeOptions { pub(crate) listen_address: SocketAddr, pub(crate) broadcast_address: SocketAddr, pub(crate) handshake_timeout: Duration, pub(crate) heartbeat_interval: Duration, pub(crate) heartbeat_timeout: Duration, } impl NodeOptions { /// Constructs a new instance of [NodeOptions] with default values. pub const fn new() -> Self { Self { listen_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1337), broadcast_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1337), handshake_timeout: Duration::from_secs(5), heartbeat_interval: Duration::from_secs(5), heartbeat_timeout: Duration::from_secs(45), } } /// Sets the address this node will listen for incoming connections on. pub fn listen_address<T: Into<SocketAddr>>(mut self, address: T) -> Self { self.listen_address = address.into(); self } /// Sets the address this node will advertise itself for remote connections. pub fn broadcast_address<T: Into<SocketAddr>>(mut self, address: T) -> Self { self.broadcast_address = address.into(); self } /// Sets the time it takes to timeout a remote node handshake. (Default 5s) pub fn handshake_timeout(mut self, duration: Duration) -> Self { self.handshake_timeout = duration; self } /// Sets the time in which a ping packet is sent to a remote node if no other messages have been sent recently. pub fn heartbeat_interval(mut self, duration: Duration) -> Self { self.heartbeat_interval = duration; self } /// Sets the time it takes to consider a remote node down when not receiving any data. pub fn heartbeat_timeout(mut self, duration: Duration) -> Self { self.handshake_timeout = duration; self } } impl Default for NodeOptions { fn default() -> Self { Self::new() } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/serialize.rs
hydra/src/serialize.rs
use std::io; use serde::Serialize; use serde::de::DeserializeOwned; /// Serializes a value. pub fn serialize_value<T: Serialize>(value: &T) -> Vec<u8> { rmp_serde::to_vec_named(value).unwrap() } /// Deserializes a value. pub fn deserialize_value<T: DeserializeOwned>(value: &[u8]) -> io::Result<T> { rmp_serde::from_slice(value).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/system_message.rs
hydra/src/system_message.rs
use crate::Dest; use crate::ExitReason; use crate::Node; use crate::Pid; use crate::Reference; /// A message sent from the hydra system. #[derive(Debug, Clone)] pub enum SystemMessage { /// A process has exited with the given reason. Exit(Pid, ExitReason), /// A monitored process went down. ProcessDown(Dest, Reference, ExitReason), /// A monitored node went down. NodeDown(Node, Reference), }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/application.rs
hydra/src/application.rs
use std::future::Future; use serde::Deserialize; use serde::Serialize; use tokio::runtime::Builder; use tokio::runtime::Runtime; use tokio::sync::oneshot; use crate::ApplicationConfig; use crate::ExitReason; use crate::Message; use crate::Pid; use crate::Process; use crate::ProcessFlags; use crate::SystemMessage; #[cfg(feature = "console")] use crate::ConsoleServer; /// Messages used internally by [Application]. #[derive(Debug, Clone, Copy, Serialize, Deserialize)] enum ApplicationMessage { ShutdownTimeout, } /// Main application logic and entry point for a hydra program. /// /// [Application] provides graceful shutdown by allowing you to link a process inside the call to `start`. /// The `run` call will only return once that process has terminated. It's recommended to link a supervisor. pub trait Application: Sized + Send + 'static { /// Override to change the application configuration defaults. fn config() -> ApplicationConfig { ApplicationConfig::default() } /// Called when an application is starting. You should link a process here and return it's [Pid]. /// /// The [Application] will wait for that process to exit before returning from `run`. fn start(&self) -> impl Future<Output = Result<Pid, ExitReason>> + Send; /// Runs the [Application] to completion. /// /// This method will return when the linked process created in `start` has exited. fn run(self) { use ApplicationMessage::*; let config = Self::config(); #[cfg(feature = "tracing")] if config.tracing_subscribe { use std::sync::Once; static TRACING_SUBSCRIBE_ONCE: Once = Once::new(); TRACING_SUBSCRIBE_ONCE.call_once(|| { tracing_subscriber::fmt::init(); }); } #[allow(unused_mut)] let mut prev_hook: Option<_> = None; #[cfg(feature = "tracing")] if config.tracing_panics { prev_hook = Some(std::panic::take_hook()); std::panic::set_hook(Box::new(panic_hook)); } let rt = Runtime::new().unwrap(); rt.block_on(async move { let (tx, rx) = oneshot::channel(); Process::spawn(async move { Process::set_flags(ProcessFlags::TRAP_EXIT); #[cfg(feature="console")] let mut cpid = ConsoleServer::new() .start_link() .await .expect("Failed to start console server!"); match self.start().await { Ok(pid) => { #[cfg(feature = "tracing")] tracing::info!(supervisor = ?pid, "Application supervisor has started"); let spid = if config.graceful_shutdown { Some(Process::spawn_link(signal_handler())) } else { None }; loop { let message = Process::receive::<ApplicationMessage>().await; match message { Message::User(ShutdownTimeout) => { #[cfg(feature = "tracing")] tracing::error!(timeout = ?config.graceful_shutdown_timeout, "Application failed to shutdown gracefully"); Process::exit(pid, ExitReason::Kill); } Message::System(SystemMessage::Exit(epid, ereason)) => { if epid == pid { if ereason.is_custom() && ereason != "shutdown" { #[cfg(feature = "tracing")] tracing::error!(reason = ?ereason, supervisor = ?pid, "Application supervisor has terminated"); } else { #[cfg(feature = "tracing")] tracing::info!(reason = ?ereason, supervisor = ?pid, "Application supervisor has exited"); } break; } else if spid.is_some_and(|spid| spid == epid) { #[cfg(feature = "tracing")] tracing::info!(reason = ?ereason, supervisor = ?pid, timeout = ?config.graceful_shutdown_timeout, "Application starting graceful shutdown"); Process::exit(pid, ExitReason::from("shutdown")); Process::send_after(Process::current(), ShutdownTimeout, config.graceful_shutdown_timeout); } #[cfg(feature = "console")] if cpid == epid && ereason != "shutdown" { cpid = ConsoleServer::new() .start_link() .await .expect("Failed to restart console server!"); } } _ => continue, } } } Err(reason) => { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, "Application supervisor failed to start"); #[cfg(not(feature = "tracing"))] let _ = reason; } } tx.send(()).unwrap(); }); let _ = rx.await; }); if let Some(prev_hook) = prev_hook { std::panic::set_hook(prev_hook); } } /// Runs the [Application] to completion for tests. /// /// This method will panic if the process doesn't cleanly exit with `normal` or `shutdown` reasons. fn test(self) { let rt = Builder::new_current_thread().enable_all().build().unwrap(); rt.block_on(async move { let (tx, rx) = oneshot::channel(); Process::spawn(async move { Process::set_flags(ProcessFlags::TRAP_EXIT); match self.start().await { Ok(pid) => loop { let message = Process::receive::<()>().await; match message { Message::System(SystemMessage::Exit(epid, ereason)) => { if epid == pid { tx.send(Some(ereason)).unwrap(); break; } } _ => continue, } }, Err(reason) => { tx.send(Some(reason)).unwrap(); } } }); if let Ok(Some(reason)) = rx.await && reason.is_custom() && reason != "shutdown" { panic!("Exited: {:?}", reason); } }); } } /// Handles SIGTERM and ctrl+c signals on unix-like platforms. #[cfg(unix)] async fn signal_handler() { use tokio::signal::unix; let mut sigterm = unix::signal(unix::SignalKind::terminate()).expect("Failed to register SIGTERM handler"); tokio::select! { _ = sigterm.recv() => { Process::exit(Process::current(), ExitReason::from("sigterm")); } _ = tokio::signal::ctrl_c() => { Process::exit(Process::current(), ExitReason::from("ctrl_c")); } } } /// Handles ctrl+c signals on non-unix-like platforms. #[cfg(not(unix))] async fn signal_handler() { let _ = tokio::signal::ctrl_c().await; Process::exit(Process::current(), ExitReason::from("ctrl_c")); } /// Handles forwarding panic messages through tracing when enabled. #[cfg(feature = "tracing")] fn panic_hook(panic_info: &std::panic::PanicHookInfo) { use std::backtrace::Backtrace; use std::backtrace::BacktraceStatus; use tracing::*; let payload = panic_info.payload(); #[allow(clippy::manual_map)] let payload = if let Some(s) = payload.downcast_ref::<&str>() { Some(&**s) } else if let Some(s) = payload.downcast_ref::<String>() { Some(s.as_str()) } else { None }; let location = panic_info.location().map(|location| location.to_string()); let backtrace = Backtrace::capture(); let backtrace = if backtrace.status() == BacktraceStatus::Disabled { String::from("run with RUST_BACKTRACE=1 environment variable to display a backtrace") } else { field::display(backtrace).to_string() }; event!( target: "hydra", Level::ERROR, payload = payload, location = location, backtrace = ?backtrace, "A process has panicked", ); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_monitor.rs
hydra/src/process_monitor.rs
use crate::Node; use crate::Pid; /// Represents an installed monitor's data for a process. pub enum ProcessMonitor { /// A monitor installed to monitor the given process. ForProcess(Option<Pid>), /// A monitor installed to monitor the given node. ForNode(Node), }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/registry.rs
hydra/src/registry.rs
use std::collections::BTreeMap; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use dashmap::DashMap; use once_cell::sync::Lazy; use serde::Deserialize; use serde::Serialize; use crate::CallError; use crate::ChildSpec; use crate::ChildType; use crate::Dest; use crate::ExitReason; use crate::From; use crate::GenServer; use crate::Message; use crate::Node; use crate::Pid; use crate::Process; use crate::ProcessFlags; use crate::Reference; use crate::RegistryOptions; use crate::Shutdown; use crate::SystemMessage; use crate::shutdown_infinity; use crate::shutdown_timeout; /// A local collection of active process registries. static REGISTRY: Lazy<DashMap<String, DashMap<RegistryKey, Pid>>> = Lazy::new(DashMap::new); /// A registry key. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum RegistryKey { /// A 32bit signed integer key. Integer32(i32), /// A 64bit signed integer key. Integer64(i64), /// A 128bit signed integer key. Integer128(i128), /// A 32bit unsigned integer key. UInteger32(u32), /// A 64bit unsigned integer key. UInteger64(u64), /// A 128bit unsigned integer key. UInteger128(u128), /// A string key. String(String), } /// A registry message. #[doc(hidden)] #[derive(Serialize, Deserialize)] pub enum RegistryMessage { Lookup(RegistryKey), LookupSuccess(Option<Pid>), LookupOrStart(RegistryKey), LookupOrStartSuccess(Pid), LookupOrStartError(RegistryError), Start(RegistryKey), StartSuccess(Pid), StartError(RegistryError), Stop(RegistryKey), StopSuccess, StopError(RegistryError), Count, CountSuccess(usize), List, ListSuccess(Vec<(RegistryKey, Pid)>), Remove(RegistryKey), RemoveSuccess(Option<Pid>), RemoveLookup(Pid), } /// Errors for [Registry] calls. #[derive(Debug, Serialize, Deserialize)] pub enum RegistryError { /// A call to the [Registry] server has failed. CallError(CallError), /// The process failed to start. StartError(ExitReason), /// The registry wasn't configured with a start routine. StartNotSupported, /// The process is already registered and running. AlreadyStarted(Pid), /// The process was not found for the given key. NotFound, } /// Provides a centralized 'registry' of processes using any value as a key. /// /// A registry is designed to only support a single type of [Process] or [GenServer], you should use multiple if necessary. #[derive(Clone)] pub struct Registry { name: String, #[allow(clippy::type_complexity)] start: Option< Arc< dyn Fn(RegistryKey) -> Box<dyn Future<Output = Result<Pid, ExitReason>> + Send + Sync> + Send + Sync, >, >, shutdown: Shutdown, lookup: BTreeMap<Pid, RegistryKey>, } impl Registry { /// Constructs a new local [Registry] with the given name. /// /// Names must be unique on a per-node basis. #[must_use] pub fn new<T: Into<String>>(name: T) -> Self { Self { name: name.into(), start: None, shutdown: Shutdown::BrutalKill, lookup: BTreeMap::new(), } } /// Assigns a start routine for the registry to be able to dynamically spawn processes. /// /// Must return a future that resolves to [Result<Pid, ExitReason>]. #[must_use] pub fn with_start<T, F>(mut self, start: T) -> Self where T: Fn(RegistryKey) -> F + Send + Sync + 'static, F: Future<Output = Result<Pid, ExitReason>> + Send + Sync + 'static, { self.start = Some(Arc::new(move |key| Box::new(start(key)))); self } /// Sets the method used to shutdown any registered processes once when the [Registry] is terminated. pub fn with_shutdown(mut self, shutdown: Shutdown) -> Self { self.shutdown = shutdown; self } /// Looks up a running process. /// /// If the registry is local, this will just query the table without hitting the registry process. pub async fn lookup<T: Into<Dest>, N: Into<RegistryKey>>( registry: T, key: N, timeout: Option<Duration>, ) -> Result<Option<Pid>, RegistryError> { use RegistryMessage::*; let registry = registry.into(); let key = key.into(); if let Dest::Named(registry, Node::Local) = &registry { return Ok(lookup_process(registry, &key)); } match Registry::call(registry, Lookup(key), timeout).await? { LookupSuccess(pid) => Ok(pid), _ => unreachable!(), } } /// Attempts to lookup a running process. /// /// If the process isn't currently running, it is spawned and passed the key. pub async fn lookup_or_start<T: Into<Dest>, N: Into<RegistryKey>>( registry: T, key: N, timeout: Option<Duration>, ) -> Result<Pid, RegistryError> { use RegistryMessage::*; let registry = registry.into(); let key = key.into(); if let Dest::Named(registry, Node::Local) = &registry && let Some(result) = lookup_process(registry, &key) { return Ok(result); } match Registry::call(registry, LookupOrStart(key), timeout).await? { LookupOrStartSuccess(pid) => Ok(pid), LookupOrStartError(error) => Err(error), _ => unreachable!(), } } /// Attempts to start a process. /// /// If the process is already running, an error is returned. pub async fn start_process<T: Into<Dest>, N: Into<RegistryKey>>( registry: T, key: N, timeout: Option<Duration>, ) -> Result<Pid, RegistryError> { use RegistryMessage::*; let registry = registry.into(); let key = key.into(); if let Dest::Named(registry, Node::Local) = &registry && let Some(pid) = lookup_process(registry, &key) { return Err(RegistryError::AlreadyStarted(pid)); } match Registry::call(registry, Start(key), timeout).await? { StartSuccess(pid) => Ok(pid), StartError(error) => Err(error), _ => unreachable!(), } } /// Stops a process registered in the given `registry` with the given `key`. /// /// If the process is trapping exits, it will still run, but be unregistered from this registry. /// /// If the process is not registered an error is returned. pub async fn stop_process<T: Into<Dest>, N: Into<RegistryKey>>( registry: T, key: N, timeout: Option<Duration>, ) -> Result<(), RegistryError> { use RegistryMessage::*; let registry = registry.into(); let key = key.into(); if let Dest::Named(registry, Node::Local) = &registry && lookup_process(registry, &key).is_none() { return Err(RegistryError::NotFound); } match Registry::call(registry, Stop(key), timeout).await? { StopSuccess => Ok(()), StopError(error) => Err(error), _ => unreachable!(), } } /// Returns the number of registered processes for the given `registry`. pub async fn count<T: Into<Dest>>( registry: T, timeout: Option<Duration>, ) -> Result<usize, RegistryError> { use RegistryMessage::*; let registry = registry.into(); if let Dest::Named(registry, Node::Local) = &registry { return Ok(count_processes(registry)); } match Registry::call(registry, Count, timeout).await? { CountSuccess(count) => Ok(count), _ => unreachable!(), } } /// Returns a list of every process registered to the given `registry`. /// /// There is no ordering guarantee. pub async fn list<T: Into<Dest>>( registry: T, timeout: Option<Duration>, ) -> Result<Vec<(RegistryKey, Pid)>, RegistryError> { use RegistryMessage::*; let registry = registry.into(); if let Dest::Named(registry, Node::Local) = &registry { return Ok(list_processes(registry)); } match Registry::call(registry, List, timeout).await? { ListSuccess(list) => Ok(list), _ => unreachable!(), } } /// Removes a process registered in the given `registry` with the given `key`. /// /// The process will no longer be registered, but it will remain running if it was found. pub async fn remove<T: Into<Dest>, N: Into<RegistryKey>>( registry: T, key: N, timeout: Option<Duration>, ) -> Result<Option<Pid>, RegistryError> { use RegistryMessage::*; let registry = registry.into(); let key = key.into(); if let Dest::Named(registry, Node::Local) = &registry { let Some(process) = remove_process(registry, &key) else { return Ok(None); }; Registry::cast(registry.to_string(), RemoveLookup(process)); return Ok(Some(process)); } match Registry::call(registry, Remove(key), timeout).await? { RemoveSuccess(pid) => Ok(pid), _ => unreachable!(), } } /// Create a registry proces not linked to a supervision tree. pub async fn start(self, mut options: RegistryOptions) -> Result<Pid, ExitReason> { if options.name.is_none() { options = options.name(self.name.clone()); } GenServer::start(self, options.into()).await } /// Creates a registry process as part of a supervision tree. /// /// For example, this function ensures that the registry is linked to the calling process (its supervisor). pub async fn start_link(self, mut options: RegistryOptions) -> Result<Pid, ExitReason> { if options.name.is_none() { options = options.name(self.name.clone()); } GenServer::start_link(self, options.into()).await } /// Builds a child specification for this [Registry] process. pub fn child_spec(self, mut options: RegistryOptions) -> ChildSpec { if options.name.is_none() { options = options.name(self.name.clone()); } ChildSpec::new("Registry") .start(move || self.clone().start_link(options.clone())) .child_type(ChildType::Supervisor) } /// Looks up, or starts a process by the given key. async fn lookup_or_start_by_key(&mut self, key: RegistryKey) -> Result<Pid, RegistryError> { if let Some(result) = lookup_process(&self.name, &key) { return Ok(result); } self.start_by_key(key).await } /// Starts a process if one doesn't exist. async fn start_by_key(&mut self, key: RegistryKey) -> Result<Pid, RegistryError> { if let Some(process) = lookup_process(&self.name, &key) { return Err(RegistryError::AlreadyStarted(process)); } let start_child = Pin::from(self.start.as_ref().unwrap()(key.clone())).await; match start_child { Ok(pid) => { #[cfg(feature = "tracing")] tracing::info!(child_key = ?key, child_pid = ?pid, "Started registered process"); self.lookup.insert(pid, key.clone()); register_process(&self.name, key, pid); Ok(pid) } Err(reason) => { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_key = ?key, "Start registered process error"); Err(RegistryError::StartError(reason)) } } } /// Terminates all registered children of this registry. async fn terminate_children(&mut self) { match self.shutdown { Shutdown::BrutalKill => { // Do nothing, the drop will automatically kill each process. } _ => { let Some((_, registry)) = REGISTRY.remove(&self.name) else { return; }; let mut monitors: Vec<(Pid, Reference)> = Vec::with_capacity(registry.len()); for (process, key) in &self.lookup { if registry.contains_key(key) { monitors.push((*process, Process::monitor(*process))); Process::exit(*process, ExitReason::from("shutdown")); } } for (process, monitor) in monitors { if let Shutdown::Duration(timeout) = self.shutdown { let _ = shutdown_timeout(process, monitor, timeout).await; } else if let Shutdown::Infinity = self.shutdown { let _ = shutdown_infinity(process, monitor).await; } } self.lookup.clear(); } } } /// Stops a process by the given key. fn stop_by_key(&mut self, key: RegistryKey) -> Result<(), RegistryError> { let Some(process) = lookup_process(&self.name, &key) else { return Err(RegistryError::NotFound); }; Process::unlink(process); Process::exit(process, ExitReason::from("shutdown")); self.lookup.remove(&process); remove_process(&self.name, &key); Ok(()) } /// Looks up a process by the given key. fn lookup_by_key(&mut self, key: RegistryKey) -> Option<Pid> { lookup_process(&self.name, &key) } /// Removes a process by the given key. fn remove_by_key(&mut self, key: RegistryKey) -> Option<Pid> { let process = remove_process(&self.name, &key)?; Process::unlink(process); self.lookup.remove(&process); Some(process) } /// Removes the process from the registry. fn remove_process(&mut self, pid: Pid, reason: ExitReason) { let Some(key) = self.lookup.remove(&pid) else { return; }; #[cfg(feature = "tracing")] tracing::info!(reason = ?reason, child_key = ?key, child_pid = ?pid, "Removed registered process"); #[cfg(not(feature = "tracing"))] let _ = reason; REGISTRY.alter(&self.name, |_, value| { value.remove_if(&key, |_, value| *value == pid); value }); } } impl Drop for Registry { fn drop(&mut self) { REGISTRY.remove(&self.name); for process in self.lookup.keys() { Process::unlink(*process); Process::exit(*process, ExitReason::Kill); } } } impl GenServer for Registry { type Message = RegistryMessage; async fn init(&mut self) -> Result<(), ExitReason> { Process::set_flags(ProcessFlags::TRAP_EXIT); Ok(()) } async fn terminate(&mut self, _reason: ExitReason) { self.terminate_children().await; } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { use RegistryMessage::*; match message { RemoveLookup(process) => { Process::unlink(process); self.lookup.remove(&process); Ok(()) } _ => unreachable!(), } } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { use RegistryMessage::*; match message { Lookup(key) => { let result = self.lookup_by_key(key); Ok(Some(LookupSuccess(result))) } LookupOrStart(key) => match self.lookup_or_start_by_key(key).await { Ok(pid) => Ok(Some(LookupOrStartSuccess(pid))), Err(error) => Ok(Some(LookupOrStartError(error))), }, Start(key) => match self.start_by_key(key).await { Ok(pid) => Ok(Some(StartSuccess(pid))), Err(error) => Ok(Some(StartError(error))), }, Stop(key) => match self.stop_by_key(key) { Ok(()) => Ok(Some(StopSuccess)), Err(error) => Ok(Some(StopError(error))), }, Count => { let count = count_processes(&self.name); Ok(Some(CountSuccess(count))) } List => { let list = list_processes(&self.name); Ok(Some(ListSuccess(list))) } Remove(key) => { let removed = self.remove_by_key(key); Ok(Some(RemoveSuccess(removed))) } _ => unreachable!(), } } async fn handle_info(&mut self, info: Message<Self::Message>) -> Result<(), ExitReason> { match info { Message::System(SystemMessage::Exit(pid, reason)) => { self.remove_process(pid, reason); Ok(()) } _ => Ok(()), } } } impl std::convert::From<i32> for RegistryKey { fn from(value: i32) -> Self { Self::Integer32(value) } } impl std::convert::From<i64> for RegistryKey { fn from(value: i64) -> Self { Self::Integer64(value) } } impl std::convert::From<i128> for RegistryKey { fn from(value: i128) -> Self { Self::Integer128(value) } } impl std::convert::From<u32> for RegistryKey { fn from(value: u32) -> Self { Self::UInteger32(value) } } impl std::convert::From<u64> for RegistryKey { fn from(value: u64) -> Self { Self::UInteger64(value) } } impl std::convert::From<u128> for RegistryKey { fn from(value: u128) -> Self { Self::UInteger128(value) } } impl std::convert::From<String> for RegistryKey { fn from(value: String) -> Self { Self::String(value) } } impl std::convert::From<&str> for RegistryKey { fn from(value: &str) -> Self { Self::String(value.to_owned()) } } impl std::convert::From<CallError> for RegistryError { fn from(value: CallError) -> Self { Self::CallError(value) } } /// Looks up a process in the given registry assigned to the given key. fn lookup_process<T: AsRef<str>>(registry: T, key: &RegistryKey) -> Option<Pid> { REGISTRY .get(registry.as_ref()) .and_then(|registry| registry.get(key).map(|entry| *entry.value())) } /// Removes a process in the given registry assigned to the given key. fn remove_process<T: AsRef<str>>(registry: T, key: &RegistryKey) -> Option<Pid> { REGISTRY .get_mut(registry.as_ref()) .and_then(|registry| registry.remove(key).map(|entry| entry.1)) } /// Counts the number of processes in a registry. fn count_processes<T: AsRef<str>>(registry: T) -> usize { REGISTRY .get(registry.as_ref()) .map(|registry| registry.len()) .unwrap_or_default() } /// Lists all of the processes in a registry. fn list_processes<T: AsRef<str>>(registry: T) -> Vec<(RegistryKey, Pid)> { REGISTRY .get(registry.as_ref()) .map(|registry| { registry .iter() .map(|entry| (entry.key().clone(), *entry.value())) .collect() }) .unwrap_or_default() } /// Registers the given process in the local registry with the given key. fn register_process<T: Into<String>>(registry: T, key: RegistryKey, process: Pid) { REGISTRY .entry(registry.into()) .or_default() .insert(key, process); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/alias.rs
hydra/src/alias.rs
use dashmap::DashMap; use once_cell::sync::Lazy; use crate::ProcessItem; use crate::ProcessSend; use crate::Reference; /// A collection of active aliases. static ALIASES: Lazy<DashMap<u64, Alias>> = Lazy::new(DashMap::new); /// The state of an active alias. #[derive(Clone)] pub struct Alias { /// The target process sender. pub sender: ProcessSend, /// Whether or not this alias is a one-shot alias. pub reply: bool, } /// Creates an alias for the given process and reference. pub fn alias_create(sender: ProcessSend, reference: Reference, reply: bool) { ALIASES.insert(reference.id(), Alias { sender, reply }); } /// Destroys an alias for the given reference, returning `true` if the alias existed. pub fn alias_destroy(reference: Reference) -> bool { ALIASES.remove(&reference.id()).is_some() } /// Destroys all of the alias for every given reference. pub fn alias_destroy_all<'a, A: IntoIterator<Item = &'a u64>>(ids: A) { for id in ids { ALIASES.remove(id); } } /// Retrieves an alias for the given reference if it's active. pub fn alias_retrieve(reference: Reference) -> Option<Alias> { let mut active: Option<Alias> = None; let result = ALIASES.remove_if(&reference.id(), |_, alias| { if alias.reply { true } else { active = Some(alias.clone()); false } }); result .map(|(_, alias)| { let _ = alias .sender .send(ProcessItem::AliasDeactivated(reference.id())); alias }) .or(active) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_info.rs
hydra/src/process_info.rs
use serde::Deserialize; use serde::Serialize; use crate::Pid; /// Debug information for a specific process. #[derive(Debug, Serialize, Deserialize)] pub struct ProcessInfo { /// The name, if any, that the process was registered under. pub registered_name: Option<String>, /// The number of messages in this processes message queue. pub message_queue_len: usize, /// Whether or not the process is trapping exits. pub trap_exit: bool, /// Collection of linked processes. pub links: Vec<Pid>, /// Collection of processes monitoring this process. pub monitored_by: Vec<Pid>, } impl ProcessInfo { /// Construct a new empty [ProcessInfo]. pub const fn new() -> Self { Self { registered_name: None, message_queue_len: 0, trap_exit: false, links: Vec::new(), monitored_by: Vec::new(), } } } impl Default for ProcessInfo { fn default() -> Self { Self::new() } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/supervisor_options.rs
hydra/src/supervisor_options.rs
use std::time::Duration; use crate::GenServerOptions; /// Options used to configure a Supervisor. #[derive(Debug, Default, Clone)] pub struct SupervisorOptions { pub(crate) name: Option<String>, pub(crate) timeout: Option<Duration>, } impl SupervisorOptions { /// Constructs a new instance of [SupervisorOptions] with the default values. pub const fn new() -> Self { Self { name: None, timeout: None, } } /// Specifies a name to register the Supervisor under. pub fn name<T: Into<String>>(mut self, name: T) -> Self { self.name = Some(name.into()); self } /// Specifies a timeout for the Supervisor `init` function. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } } impl From<SupervisorOptions> for GenServerOptions { fn from(mut value: SupervisorOptions) -> Self { let mut options = GenServerOptions::new(); if let Some(name) = value.name.take() { options = options.name(name); } if let Some(timeout) = value.timeout.take() { options = options.timeout(timeout); } options } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/task.rs
hydra/src/task.rs
use std::future::Future; use std::pin::Pin; use std::task::Context; use std::task::Poll; use futures_util::FutureExt; use tokio::task::JoinHandle; /// A task is a lightweight thread of execution designed to run one particular action. /// /// Tasks can not receive messages from other processes, only send. /// /// Calls that are allowed: /// - Process::send /// - GenServer::cast /// /// Calls that would panic: /// - Process::link /// - Process::monitor /// - GenServer::call /// /// You can however return a value in a task and await it to receive the value. /// /// It's not recommended to `await` long running tasks in a `GenServer` since it will delay processing of other messages. /// Instead, you should send a `cast` with the result of your task and handle it in `handle_cast`. pub struct Task; /// The result of a spawned task, can be used to await the task result, or shutdown the task. #[repr(transparent)] pub struct TaskHandle<R> { handle: JoinHandle<R>, } /// An error occured while executing the task. #[derive(Debug)] pub struct TaskError(pub String); impl Task { /// Runs the provided asynchronous `task`. #[track_caller] pub fn spawn<F>(task: F) -> TaskHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { TaskHandle { handle: tokio::task::spawn(task), } } /// Runs the provided synchronous `task` on a thread where blocking is acceptable. #[track_caller] pub fn spawn_blocking<F, R>(task: F) -> TaskHandle<R> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { TaskHandle { handle: tokio::task::spawn_blocking(task), } } /// Shuts down the task, and then checks for a result. /// /// Returns the result if the task finishes while shutting down, [TaskError] if the task died before returning. pub async fn shutdown<R>(task: TaskHandle<R>) -> Result<R, TaskError> { task.handle.abort(); task.handle .await .map_err(|error| TaskError(error.to_string())) } /// Await many tasks at once and returns their results in order, or returns the first error that occurs. pub async fn await_many<R, const N: usize>( tasks: [TaskHandle<R>; N], ) -> Result<Vec<R>, TaskError> where R: 'static, { let mut results: Vec<R> = Vec::with_capacity(N); for task in tasks { results.push( task.handle .await .map_err(|error| TaskError(error.to_string()))?, ); } Ok(results) } } impl<R> Future for TaskHandle<R> where R: Send + 'static, { type Output = Result<R, TaskError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.handle .poll_unpin(cx) .map_err(|error| TaskError(error.to_string())) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/supervisor.rs
hydra/src/supervisor.rs
use std::collections::BTreeSet; use std::pin::Pin; use std::time::Duration; use std::time::Instant; use serde::Deserialize; use serde::Serialize; use crate::AutoShutdown; use crate::CallError; use crate::ChildSpec; use crate::ChildType; use crate::Dest; use crate::ExitReason; use crate::From; use crate::GenServer; use crate::Local; use crate::Message; use crate::Pid; use crate::Process; use crate::ProcessFlags; use crate::Restart; use crate::Shutdown; use crate::SupervisorOptions; use crate::SystemMessage; use crate::shutdown_brutal_kill; use crate::shutdown_infinity; use crate::shutdown_timeout; /// A supervision child. #[derive(Clone)] struct SupervisedChild { spec: ChildSpec, pid: Option<Pid>, restarting: bool, } /// A supervisor message. #[doc(hidden)] #[derive(Serialize, Deserialize)] pub enum SupervisorMessage { TryAgainRestartPid(Pid), TryAgainRestartId(String), CountChildren, CountChildrenSuccess(SupervisorCounts), StartChild(Local<ChildSpec>), StartChildSuccess(Option<Pid>), StartChildError(SupervisorError), TerminateChild(String), TerminateChildSuccess, TerminateChildError(SupervisorError), RestartChild(String), RestartChildSuccess(Option<Pid>), RestartChildError(SupervisorError), DeleteChild(String), DeleteChildSuccess, DeleteChildError(SupervisorError), WhichChildren, WhichChildrenSuccess(Vec<SupervisorChildInfo>), } /// Errors for [Supervisor] calls. #[derive(Debug, Serialize, Deserialize)] pub enum SupervisorError { /// A call to the [Supervisor] server has failed. CallError(CallError), /// The child already exists and is running. AlreadyStarted, /// The child already exists. AlreadyPresent, /// The child failed to start. StartError(ExitReason), /// The child was not found. NotFound, /// The child is already running. Running, /// The child is being restarted. Restarting, } /// Information about a child of a [Supervisor]. #[derive(Debug, Serialize, Deserialize)] pub struct SupervisorChildInfo { /// The id as defined in the child specification. id: String, /// The [Pid] of the corrosponding child process if it exists. child: Option<Pid>, /// The type of child as defined in the child specification. child_type: ChildType, /// Whether or not the process is about to be restarted. restarting: bool, } /// Contains the counts of all of the supervised children. #[derive(Debug, Serialize, Deserialize)] pub struct SupervisorCounts { /// The total count of children, dead or alive. pub specs: usize, /// The count of all actively running child processes managed by this supervisor. pub active: usize, /// The count of all children marked as `supervisor` dead or alive. pub supervisors: usize, /// The count of all children marked as `worker` dead or alive. pub workers: usize, } /// The supervision strategy to use for each child. #[derive(Debug, Clone, Copy)] pub enum SupervisionStrategy { /// If a child process terminates, only that process is restarted. OneForOne, /// If a child process terminates, all other child processes are terminated and then all child processes are restarted. OneForAll, /// If a child process terminates, the terminated child process and the rest of the children started after it, are terminated and restarted. RestForOne, } /// A supervisor is a process which supervises other processes, which we refer to as child processes. /// Supervisors are used to build a hierarchical process structure called a supervision tree. /// Supervision trees provide fault-tolerance and encapsulate how our applications start and shutdown. #[derive(Clone)] pub struct Supervisor { children: Vec<SupervisedChild>, identifiers: BTreeSet<String>, restarts: Vec<Instant>, strategy: SupervisionStrategy, auto_shutdown: AutoShutdown, max_restarts: usize, max_duration: Duration, } impl Supervisor { /// Constructs a new instance of [Supervisor] with no children. pub const fn new() -> Self { Self { children: Vec::new(), identifiers: BTreeSet::new(), restarts: Vec::new(), strategy: SupervisionStrategy::OneForOne, auto_shutdown: AutoShutdown::Never, max_restarts: 3, max_duration: Duration::from_secs(5), } } /// Constructs a new instance of [Supervisor] with the given children. pub fn with_children<T: IntoIterator<Item = ChildSpec>>(children: T) -> Self { let mut result = Self::new(); for child in children { result = result.add_child(child); } result } /// Adds a child to this [Supervisor]. pub fn add_child(mut self, child: ChildSpec) -> Self { if self.identifiers.contains(&child.id) { panic!("Child id was not unique!"); } self.identifiers.insert(child.id.clone()); self.children.push(SupervisedChild { spec: child, pid: None, restarting: false, }); self } /// Builds a child specification for this [Supervisor] process. pub fn child_spec(self, options: SupervisorOptions) -> ChildSpec { ChildSpec::new("Supervisor") .start(move || self.clone().start_link(options.clone())) .child_type(ChildType::Supervisor) } /// Sets the supervision strategy for the [Supervisor]. pub const fn strategy(mut self, strategy: SupervisionStrategy) -> Self { self.strategy = strategy; self } /// Sets the behavior to use when a significant process exits. pub const fn auto_shutdown(mut self, auto_shutdown: AutoShutdown) -> Self { self.auto_shutdown = auto_shutdown; self } /// Sets the maximum number of restarts allowed in a time frame. /// /// Defaults to 3. pub const fn max_restarts(mut self, max_restarts: usize) -> Self { self.max_restarts = max_restarts; self } /// Sets the time frame in which `max_restarts` applies. /// /// Defaults to 5s. pub const fn max_duration(mut self, max_duration: Duration) -> Self { self.max_duration = max_duration; self } /// Creates a supervisor process not apart of a supervision tree. /// /// This will not return until all of the child processes have been started. pub async fn start(self, options: SupervisorOptions) -> Result<Pid, ExitReason> { GenServer::start(self, options.into()).await } /// Creates a supervisor process as part of a supervision tree. /// /// For example, this function ensures that the supervisor is linked to the calling process (its supervisor). /// /// This will not return until all of the child processes have been started. pub async fn start_link(self, options: SupervisorOptions) -> Result<Pid, ExitReason> { GenServer::start_link(self, options.into()).await } /// Returns [SupervisorCounts] containing the counts for each of the different child specifications. pub async fn count_children<T: Into<Dest>>( supervisor: T, ) -> Result<SupervisorCounts, SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, CountChildren, None).await? { CountChildrenSuccess(counts) => Ok(counts), _ => unreachable!(), } } /// Adds the child specification to the [Supervisor] and starts that child. pub async fn start_child<T: Into<Dest>>( supervisor: T, child: ChildSpec, ) -> Result<Option<Pid>, SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, StartChild(Local::new(child)), None).await? { StartChildSuccess(pid) => Ok(pid), StartChildError(error) => Err(error), _ => unreachable!(), } } /// Terminates the given child identified by `child_id`. /// /// The process is terminated, if there's one. The child specification is kept unless the child is temporary. /// /// A non-temporary child process may later be restarted by the [Supervisor]. /// /// The child process can also be restarted explicitly by calling `restart_child`. Use `delete_child` to remove the child specification. pub async fn terminate_child<T: Into<Dest>, I: Into<String>>( supervisor: T, child_id: I, ) -> Result<(), SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, TerminateChild(child_id.into()), None).await? { TerminateChildSuccess => Ok(()), TerminateChildError(error) => Err(error), _ => unreachable!(), } } /// Restarts a child identified by `child_id`. /// /// The child specification must exist and the corresponding child process must not be running. /// /// Note that for temporary children, the child specification is automatically deleted when the child terminates, /// and thus it is not possible to restart such children. pub async fn restart_child<T: Into<Dest>, I: Into<String>>( supervisor: T, child_id: I, ) -> Result<Option<Pid>, SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, RestartChild(child_id.into()), None).await? { RestartChildSuccess(pid) => Ok(pid), RestartChildError(error) => Err(error), _ => unreachable!(), } } /// Deletes the child specification identified by `child_id`. /// /// The corrosponding child process must not be running, use `terminate_child` to terminate it if it's running. pub async fn delete_child<T: Into<Dest>, I: Into<String>>( supervisor: T, child_id: I, ) -> Result<(), SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, DeleteChild(child_id.into()), None).await? { DeleteChildSuccess => Ok(()), DeleteChildError(error) => Err(error), _ => unreachable!(), } } /// Returns a list with information about all children of the given [Supervisor]. pub async fn which_children<T: Into<Dest>>( supervisor: T, ) -> Result<Vec<SupervisorChildInfo>, SupervisorError> { use SupervisorMessage::*; match Supervisor::call(supervisor, WhichChildren, None).await? { WhichChildrenSuccess(info) => Ok(info), _ => unreachable!(), } } /// Starts all of the children. async fn start_children(&mut self) -> Result<(), ExitReason> { let mut remove: Vec<usize> = Vec::new(); for index in 0..self.children.len() { match self.start_child_by_index(index).await { Ok(pid) => { let child = &mut self.children[index]; child.pid = pid; child.restarting = false; if child.is_temporary() && pid.is_none() { remove.push(index); } } Err(reason) => { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?self.children[index].spec.id, "Start error"); #[cfg(not(feature = "tracing"))] let _ = reason; return Err(ExitReason::from("failed_to_start_child")); } } } for index in remove.into_iter().rev() { self.remove_child(index); } Ok(()) } /// Deletes a child by the id if it exists. async fn delete_child_by_id(&mut self, child_id: String) -> Result<(), SupervisorError> { let index = self .children .iter() .position(|child| child.spec.id == child_id); let Some(index) = index else { return Err(SupervisorError::NotFound); }; let child = &self.children[index]; if child.restarting { return Err(SupervisorError::Restarting); } else if child.pid.is_some() { return Err(SupervisorError::Running); } let child = self.children.remove(index); self.identifiers.remove(&child.spec.id); Ok(()) } /// Terminates a child by the id if it exists. async fn terminate_child_by_id(&mut self, child_id: String) -> Result<(), SupervisorError> { let index = self .children .iter() .position(|child| child.spec.id == child_id); if let Some(index) = index { self.terminate_child_by_index(index).await; Ok(()) } else { Err(SupervisorError::NotFound) } } /// Restarts a child by the id if it's not already started or pending. async fn restart_child_by_id( &mut self, child_id: String, ) -> Result<Option<Pid>, SupervisorError> { let index = self .children .iter() .position(|child| child.spec.id == child_id); let Some(index) = index else { return Err(SupervisorError::NotFound); }; let child = &mut self.children[index]; if child.restarting { return Err(SupervisorError::Restarting); } else if child.pid.is_some() { return Err(SupervisorError::Running); } match self.start_child_by_index(index).await { Ok(pid) => { let child = &mut self.children[index]; child.pid = pid; child.restarting = false; Ok(pid) } Err(reason) => Err(SupervisorError::StartError(reason)), } } /// Terminates all of the children. async fn terminate_children(&mut self) { let mut remove: Vec<usize> = Vec::new(); for (index, child) in self.children.iter_mut().enumerate().rev() { if child.is_temporary() { remove.push(index); } let Some(pid) = child.pid.take() else { continue; }; if let Err(reason) = shutdown(pid, child.shutdown()).await { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_pid = ?pid, "Shutdown error"); #[cfg(not(feature = "tracing"))] let _ = reason; } } for index in remove { self.remove_child(index); } } /// Terminates a single child. async fn terminate_child_by_index(&mut self, index: usize) { let child = &mut self.children[index]; let Some(pid) = child.pid.take() else { return; }; child.restarting = false; let _ = shutdown(pid, child.shutdown()).await; } /// Checks all of the children for correct specification and then starts them. async fn init_children(&mut self) -> Result<(), ExitReason> { if let Err(reason) = self.start_children().await { self.terminate_children().await; return Err(reason); } Ok(()) } /// Restarts a child that exited for the given `reason`. async fn restart_exited_child( &mut self, pid: Pid, reason: ExitReason, ) -> Result<(), ExitReason> { let Some(index) = self.find_child(pid) else { return Ok(()); }; let child = &mut self.children[index]; // Permanent children are always restarted. if child.is_permanent() { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?child.spec.id, child_pid = ?child.pid, "Child terminated"); if self.add_restart() { return Err(ExitReason::from("shutdown")); } self.restart(index).await; return Ok(()); } // If it's not permanent, check if it's a normal reason. if reason.is_normal() || reason == "shutdown" { let child = self.remove_child(index); if self.check_auto_shutdown(child) { return Err(ExitReason::from("shutdown")); } else { return Ok(()); } } // Not a normal reason, check if transient. if child.is_transient() { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?child.spec.id, child_pid = ?child.pid, "Child terminated"); if self.add_restart() { return Err(ExitReason::from("shutdown")); } self.restart(index).await; return Ok(()); } // Not transient, check if temporary and clean up. if child.is_temporary() { #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?child.spec.id, child_pid = ?child.pid, "Child terminated"); let child = self.remove_child(index); if self.check_auto_shutdown(child) { return Err(ExitReason::from("shutdown")); } } Ok(()) } /// Restarts one or more children starting with the given `index` based on the current strategy. async fn restart(&mut self, index: usize) { use SupervisorMessage::*; match self.strategy { SupervisionStrategy::OneForOne => { match self.start_child_by_index(index).await { Ok(pid) => { let child = &mut self.children[index]; child.pid = pid; child.restarting = false; } Err(reason) => { let id = self.children[index].id(); #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?id, child_pid = ?self.children[index].pid, "Start error"); #[cfg(not(feature = "tracing"))] let _ = reason; self.children[index].restarting = true; Supervisor::cast(Process::current(), TryAgainRestartId(id)); } }; } SupervisionStrategy::RestForOne => { if let Some((index, reason)) = self.restart_multiple_children(index, false).await { let id = self.children[index].id(); #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?id, child_pid = ?self.children[index].pid, "Start error"); #[cfg(not(feature = "tracing"))] let _ = reason; self.children[index].restarting = true; Supervisor::cast(Process::current(), TryAgainRestartId(id)); } } SupervisionStrategy::OneForAll => { if let Some((index, reason)) = self.restart_multiple_children(index, true).await { let id = self.children[index].id(); #[cfg(feature = "tracing")] tracing::error!(reason = ?reason, child_id = ?id, child_pid = ?self.children[index].pid, "Start error"); #[cfg(not(feature = "tracing"))] let _ = reason; self.children[index].restarting = true; Supervisor::cast(Process::current(), TryAgainRestartId(id)); } } } } /// Restarts multiple children, returning if one of them fails. async fn restart_multiple_children( &mut self, index: usize, all: bool, ) -> Option<(usize, ExitReason)> { let mut indices = Vec::new(); let range = if all { 0..self.children.len() } else { index..self.children.len() }; for tindex in range { indices.push(tindex); if index == tindex { continue; } self.terminate_child_by_index(tindex).await; } for sindex in indices { match self.start_child_by_index(sindex).await { Ok(pid) => { let child = &mut self.children[sindex]; child.pid = pid; child.restarting = false; } Err(reason) => { return Some((sindex, reason)); } } } None } /// Tries to restart the given child again, returns if an error occured. async fn try_again_restart(&mut self, index: usize) -> Result<(), ExitReason> { if self.add_restart() { return Err(ExitReason::from("shutdown")); } if !self.children[index].restarting { return Ok(()); } self.restart(index).await; Ok(()) } /// Starts the given child by it's index and returns what the result was. async fn start_child_by_index(&mut self, index: usize) -> Result<Option<Pid>, ExitReason> { let child = &mut self.children[index]; let start_child = Pin::from(child.spec.start.as_ref().unwrap()()).await; match start_child { Ok(pid) => { #[cfg(feature = "tracing")] tracing::info!(child_id = ?child.spec.id, child_pid = ?pid, "Started child"); Ok(Some(pid)) } Err(reason) => { if reason.is_ignore() { #[cfg(feature = "tracing")] tracing::info!(child_id = ?child.spec.id, child_pid = ?None::<Pid>, "Started child"); Ok(None) } else { Err(reason) } } } } /// Adds the new child spec to the children if it's unique and starts it. async fn start_new_child(&mut self, spec: ChildSpec) -> Result<Option<Pid>, SupervisorError> { if self.identifiers.contains(&spec.id) { let child = self .children .iter() .find(|child| child.spec.id == spec.id) .unwrap(); if child.pid.is_some() { return Err(SupervisorError::AlreadyStarted); } else { return Err(SupervisorError::AlreadyPresent); } } self.identifiers.insert(spec.id.clone()); self.children.push(SupervisedChild { spec, pid: None, restarting: false, }); match self.start_child_by_index(self.children.len() - 1).await { Ok(pid) => { let index = self.children.len() - 1; let child = &mut self.children[index]; child.pid = pid; child.restarting = false; if child.is_temporary() && pid.is_none() { self.children.remove(index); } Ok(pid) } Err(reason) => Err(SupervisorError::StartError(reason)), } } /// Checks whether or not we should automatically shutdown the supervisor. Returns `true` if so. fn check_auto_shutdown(&mut self, child: SupervisedChild) -> bool { if matches!(self.auto_shutdown, AutoShutdown::Never) { return false; } if !child.spec.significant { return false; } if matches!(self.auto_shutdown, AutoShutdown::AnySignificant) { return true; } self.children.iter().any(|child| { if child.pid.is_none() { return false; } child.spec.significant }) } /// Adds another restart to the backlog and returns `true` if we've exceeded our quota of restarts. fn add_restart(&mut self) -> bool { let now = Instant::now(); let threshold = now - self.max_duration; self.restarts.retain(|restart| *restart >= threshold); self.restarts.push(now); if self.restarts.len() > self.max_restarts { #[cfg(feature = "tracing")] tracing::error!(restarts = ?self.restarts.len(), threshold = ?self.max_duration, "Reached max restart intensity"); return true; } false } /// Gets information on all of the children. fn which_children_info(&mut self) -> Vec<SupervisorChildInfo> { let mut result = Vec::with_capacity(self.children.len()); for child in &self.children { result.push(SupervisorChildInfo { id: child.spec.id.clone(), child: child.pid, child_type: child.spec.child_type, restarting: child.restarting, }); } result } /// Counts all of the supervised children. fn count_all_children(&mut self) -> SupervisorCounts { let mut counts = SupervisorCounts { specs: 0, active: 0, supervisors: 0, workers: 0, }; for child in &self.children { counts.specs += 1; if child.pid.is_some() { counts.active += 1; } if matches!(child.spec.child_type, ChildType::Supervisor) { counts.supervisors += 1; } else { counts.workers += 1; } } counts } /// Removes a child from the supervisor. fn remove_child(&mut self, index: usize) -> SupervisedChild { let child = self.children.remove(index); self.identifiers.remove(&child.spec.id); child } /// Finds a child by the given `pid`. fn find_child(&mut self, pid: Pid) -> Option<usize> { self.children .iter() .position(|child| child.pid.is_some_and(|cpid| cpid == pid)) } /// Finds a child by the given `id`. fn find_child_id(&mut self, id: &str) -> Option<usize> { self.children.iter().position(|child| child.spec.id == id) } } impl SupervisedChild { /// Returns `true` if the child is a permanent process. pub const fn is_permanent(&self) -> bool { matches!(self.spec.restart, Restart::Permanent) } /// Returns `true` if the child is a transient process. pub const fn is_transient(&self) -> bool { matches!(self.spec.restart, Restart::Transient) } /// Returns `true` if the child is a temporary process. pub const fn is_temporary(&self) -> bool { matches!(self.spec.restart, Restart::Temporary) } /// Returns the unique id of the child. pub fn id(&self) -> String { self.spec.id.clone() } /// Returns how the child should be terminated. pub const fn shutdown(&self) -> Shutdown { match self.spec.shutdown { None => match self.spec.child_type { ChildType::Worker => Shutdown::Duration(Duration::from_secs(5)), ChildType::Supervisor => Shutdown::Infinity, }, Some(shutdown) => shutdown, } } } impl Default for Supervisor { fn default() -> Self { Self::new() } } impl GenServer for Supervisor { type Message = SupervisorMessage; async fn init(&mut self) -> Result<(), ExitReason> { Process::set_flags(ProcessFlags::TRAP_EXIT); self.init_children().await } async fn terminate(&mut self, _reason: ExitReason) { self.terminate_children().await; } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { use SupervisorMessage::*; match message { TryAgainRestartPid(pid) => { if let Some(index) = self.find_child(pid) { return self.try_again_restart(index).await; } } TryAgainRestartId(id) => { if let Some(index) = self.find_child_id(&id) { return self.try_again_restart(index).await; } } _ => unreachable!(), } Ok(()) } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { use SupervisorMessage::*; match message { CountChildren => { let counts = self.count_all_children(); Ok(Some(CountChildrenSuccess(counts))) } StartChild(spec) => match self.start_new_child(spec.into_inner()).await { Ok(pid) => Ok(Some(StartChildSuccess(pid))), Err(error) => Ok(Some(StartChildError(error))), }, TerminateChild(child_id) => match self.terminate_child_by_id(child_id).await { Ok(()) => Ok(Some(TerminateChildSuccess)), Err(error) => Ok(Some(TerminateChildError(error))), }, RestartChild(child_id) => match self.restart_child_by_id(child_id).await { Ok(pid) => Ok(Some(RestartChildSuccess(pid))), Err(error) => Ok(Some(RestartChildError(error))), }, DeleteChild(child_id) => match self.delete_child_by_id(child_id).await { Ok(()) => Ok(Some(DeleteChildSuccess)), Err(error) => Ok(Some(DeleteChildError(error))), }, WhichChildren => { let children = self.which_children_info(); Ok(Some(WhichChildrenSuccess(children))) } _ => unreachable!(), } } async fn handle_info(&mut self, info: Message<Self::Message>) -> Result<(), ExitReason> { match info { Message::System(SystemMessage::Exit(pid, reason)) => { self.restart_exited_child(pid, reason).await } _ => Ok(()), } } } impl std::convert::From<CallError> for SupervisorError { fn from(value: CallError) -> Self { Self::CallError(value) } } /// Terminates the given `pid` using the given `shutdown` method. async fn shutdown(pid: Pid, shutdown: Shutdown) -> Result<(), ExitReason> { let monitor = Process::monitor(pid); match shutdown { Shutdown::BrutalKill => shutdown_brutal_kill(pid, monitor).await, Shutdown::Duration(timeout) => shutdown_timeout(pid, monitor, timeout).await, Shutdown::Infinity => shutdown_infinity(pid, monitor).await, } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/monitor.rs
hydra/src/monitor.rs
use std::collections::BTreeMap; use dashmap::DashMap; use once_cell::sync::Lazy; use crate::frame::Monitor; use crate::frame::MonitorDown; use crate::Dest; use crate::ExitReason; use crate::Node; use crate::PROCESS; use crate::Pid; use crate::ProcessInfo; use crate::ProcessItem; use crate::ProcessMonitor; use crate::Reference; use crate::alias_destroy; use crate::node_lookup_remote; use crate::node_monitor_destroy; use crate::node_process_monitor_create; use crate::node_process_monitor_destroy; use crate::node_process_monitor_destroy_all; use crate::node_register; use crate::node_send_frame; use crate::process_exists_lock; use crate::process_name_lookup; use crate::process_sender; /// A collection of the local processes being monitored, and the references that require the message. #[allow(clippy::type_complexity)] static MONITORS: Lazy<DashMap<u64, BTreeMap<Reference, (Pid, Option<Dest>)>>> = Lazy::new(DashMap::new); /// Creates a monitor for the given local process and reference from the given process. pub fn monitor_create(process: Pid, reference: Reference, from: Pid, dest: Option<Dest>) { MONITORS .entry(process.id()) .or_default() .insert(reference, (from, dest)); } /// Destroys a monitor for the given local process and reference. pub fn monitor_destroy(process: Pid, reference: Reference) { if process.is_local() { MONITORS.alter(&process.id(), |_, mut value| { value.remove(&reference); value }); } else { let monitor = Monitor::new(false, Some(process.id()), None, None, reference.id()); node_send_frame(monitor.into(), reference.node()); if let Some((name, address)) = node_lookup_remote(reference.node()) { node_process_monitor_destroy(Node::from((name, address)), reference); } } } /// Destroys all monitors registered for the given reference, monitor combination. pub fn monitor_destroy_all<'a, M: IntoIterator<Item = (&'a Reference, &'a ProcessMonitor)>>( monitors: M, ) { for (reference, monitor) in monitors { match monitor { ProcessMonitor::ForProcess(pid) => { let Some(pid) = pid else { continue; }; if pid.is_local() { MONITORS.alter(&pid.id(), |_, mut value| { value.remove(reference); value }); } else { let monitor = Monitor::new(false, Some(pid.id()), None, None, reference.id()); node_send_frame(monitor.into(), reference.node()); } } ProcessMonitor::ForNode(node) => { node_monitor_destroy(node.clone(), *reference); } } if reference.is_local() { alias_destroy(*reference); } } } /// Installs a monitor for the given process. pub fn monitor_install(process: Dest, reference: Reference, from: Pid) { let dest = process.clone(); let send_process_down = |dest: Dest, exit_reason: ExitReason| { PROCESS.with(|process| { process .sender .send(ProcessItem::MonitorProcessDown( dest, reference, exit_reason, )) .unwrap() }); alias_destroy(reference); }; match process { Dest::Pid(pid) => { if pid == from { panic!("Can not monitor yourself!"); } PROCESS.with(|process| { process .monitors .borrow_mut() .insert(reference, ProcessMonitor::ForProcess(Some(pid))) }); if pid.is_local() { process_exists_lock(pid, |exists| { if exists { monitor_create(pid, reference, from, Some(process)); } else { send_process_down(dest, ExitReason::from("noproc")); } }); } else { match node_lookup_remote(pid.node()) { Some((name, address)) => { let node = Node::from((name, address)); node_process_monitor_create(node.clone(), reference, dest, from); let node = node_register(node, true); let monitor = Monitor::new( true, Some(pid.id()), None, Some(from.id()), reference.id(), ); node_send_frame(monitor.into(), node); } None => { send_process_down(dest, ExitReason::from("noconnection")); } } } } Dest::Named(name, node) => { if node.is_local() { let Some(pid) = process_name_lookup(name.as_ref()) else { PROCESS.with(|process| { process .monitors .borrow_mut() .insert(reference, ProcessMonitor::ForProcess(None)) }); return send_process_down(dest, ExitReason::from("noproc")); }; PROCESS.with(|process| { process .monitors .borrow_mut() .insert(reference, ProcessMonitor::ForProcess(Some(pid))) }); process_exists_lock(pid, |exists| { if exists { monitor_create(pid, reference, from, Some(dest)); } else { send_process_down(dest, ExitReason::from("noproc")); } }); } else { PROCESS.with(|process| { process .monitors .borrow_mut() .insert(reference, ProcessMonitor::ForProcess(None)) }); node_process_monitor_create(node.clone(), reference, dest, from); let node = node_register(node.clone(), true); let monitor = Monitor::new( true, None, Some(name.into_owned()), Some(from.id()), reference.id(), ); node_send_frame(monitor.into(), node); } } Dest::Alias(_) => panic!("Can not monitor an alias!"), } } /// Sends monitor messages about the given process going down for the given reason. pub fn monitor_process_down(from: Pid, exit_reason: ExitReason) { let Some(references) = MONITORS .remove(&from.id()) .map(|(_, references)| references) else { return; }; let mut remote_monitors: BTreeMap<u64, (MonitorDown, Vec<Reference>)> = BTreeMap::new(); for (reference, (pid, dest)) in references { if pid.is_local() { process_sender(pid).map(|sender| { sender.send(ProcessItem::MonitorProcessDown( dest.unwrap(), reference, exit_reason.clone(), )) }); } else { let remote = remote_monitors .entry(pid.node()) .or_insert((MonitorDown::new(exit_reason.clone()), Vec::new())); remote.0.monitors.push(reference.id()); remote.1.push(reference); } if reference.is_local() { alias_destroy(reference); } } for (node, (monitor_down, references)) in remote_monitors { if let Some((name, address)) = node_lookup_remote(node) { node_process_monitor_destroy_all(Node::from((name, address)), references); } node_send_frame(monitor_down.into(), node); } } /// Fills in monitor information for the process. pub fn monitor_fill_info(pid: Pid, info: &mut ProcessInfo) { let Some(monitors) = MONITORS.get(&pid.id()) else { return; }; info.monitored_by = monitors.value().values().map(|entry| entry.0).collect(); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/semaphore.rs
hydra/src/semaphore.rs
use std::sync::Arc; use tokio::sync::OwnedSemaphorePermit as OwnedSemaphoreBasePermit; use tokio::sync::Semaphore as SemaphoreBase; use tokio::sync::SemaphorePermit as SemaphoreBasePermit; /// Represents a permit to a [Semaphore]. pub struct SemaphorePermit<'a> { _permit: SemaphoreBasePermit<'a>, } /// Represents an owned permit to a [OwnedSemaphore]. pub struct OwnedSemaphorePermit { _permit: OwnedSemaphoreBasePermit, } /// Error when there are no permits available. #[derive(Debug)] pub struct NoPermits; /// A semaphore maintains a set of permits. Permits are used to synchronize access to a shared resource. /// A semaphore differs from a mutex in that it can allow more than one concurrent caller to access the shared resource at a time. #[repr(transparent)] pub struct Semaphore { inner: SemaphoreBase, } /// An owned semaphore is identical to a [Semaphore] except it can be owned by an actor and it's permits can still be shared externally. #[repr(transparent)] pub struct OwnedSemaphore { inner: Arc<SemaphoreBase>, } impl Semaphore { /// Creates a new instance of [Semaphore] with the given `permits` count. /// /// This is typically used to create a static semaphore: /// ``` /// use hydra::Semaphore; /// /// static RATE_LIMIT: Semaphore = Semaphore::new(100); /// ``` pub const fn new(permits: usize) -> Self { Self { inner: SemaphoreBase::const_new(permits), } } /// Acquires one permit asynchronously waiting for one to become available. #[must_use] pub async fn acquire(&self) -> SemaphorePermit<'_> { let permit = self.inner.acquire().await.unwrap(); SemaphorePermit { _permit: permit } } /// Acquires many permits asynchronously waiting for them to become available. #[must_use] pub async fn acquire_many(&self, count: u32) -> SemaphorePermit<'_> { let permit = self.inner.acquire_many(count).await.unwrap(); SemaphorePermit { _permit: permit } } /// Attempts to acquire a permit, returning an error if there are none available. pub fn try_acquire(&self) -> Result<SemaphorePermit<'_>, NoPermits> { let permit = self.inner.try_acquire().map_err(|_| NoPermits)?; Ok(SemaphorePermit { _permit: permit }) } } impl OwnedSemaphore { /// Creates a new instance of [OwnedSemaphore] with the given `permits` count that can be used with owned permits. /// /// This can be used to create a owned semaphore that lives in a state: /// ``` /// use hydra::OwnedSemaphore; /// /// struct MyServer { /// rate_limit: OwnedSemaphore, /// } /// /// impl MyServer { /// pub fn new() -> Self { /// Self { /// rate_limit: OwnedSemaphore::new(100), /// } /// } /// } /// ``` pub fn new(permits: usize) -> Self { Self { inner: Arc::new(SemaphoreBase::new(permits)), } } /// Acquires one permit asynchronously waiting for one to become available. #[must_use] pub async fn acquire(&self) -> SemaphorePermit<'_> { let permit = self.inner.acquire().await.unwrap(); SemaphorePermit { _permit: permit } } /// Acquires one permit asynchronously waiting for one to become available. #[must_use] pub async fn acquire_owned(&self) -> OwnedSemaphorePermit { let permit = self.inner.clone().acquire_owned().await.unwrap(); OwnedSemaphorePermit { _permit: permit } } /// Acquires many permits asynchronously waiting for them to become available. #[must_use] pub async fn acquire_many(&self, count: u32) -> SemaphorePermit<'_> { let permit = self.inner.acquire_many(count).await.unwrap(); SemaphorePermit { _permit: permit } } /// Acquires many permits asynchronously waiting for them to become available. #[must_use] pub async fn acquire_many_owned(&self, count: u32) -> OwnedSemaphorePermit { let permit = self.inner.clone().acquire_many_owned(count).await.unwrap(); OwnedSemaphorePermit { _permit: permit } } /// Attempts to acquire a permit, returning an error if there are none available. pub fn try_acquire(&self) -> Result<SemaphorePermit<'_>, NoPermits> { let permit = self.inner.try_acquire().map_err(|_| NoPermits)?; Ok(SemaphorePermit { _permit: permit }) } /// Attempts to acquire a permit, returning an error if there are none available. pub fn try_acquire_owned(&self) -> Result<OwnedSemaphorePermit, NoPermits> { let permit = self .inner .clone() .try_acquire_owned() .map_err(|_| NoPermits)?; Ok(OwnedSemaphorePermit { _permit: permit }) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/application_config.rs
hydra/src/application_config.rs
use std::time::Duration; /// Configuration values for an application. pub struct ApplicationConfig { #[cfg(feature = "tracing")] pub(crate) tracing_subscribe: bool, #[cfg(feature = "tracing")] pub(crate) tracing_panics: bool, pub(crate) graceful_shutdown: bool, pub(crate) graceful_shutdown_timeout: Duration, } impl ApplicationConfig { /// Constructs a new instance of [ApplicationConfig]. pub const fn new() -> Self { Self { #[cfg(feature = "tracing")] tracing_subscribe: false, #[cfg(feature = "tracing")] tracing_panics: false, graceful_shutdown: false, graceful_shutdown_timeout: Duration::from_secs(10), } } /// Configure whether or not tracing will subscribe when you call `run`. /// /// This will install a global tracing subscriber with recommended settings for you. #[cfg(feature = "tracing")] pub fn with_tracing_subscribe(mut self, value: bool) -> Self { self.tracing_subscribe = value; self } /// Configure whether or not tracing will be used to catch panics globally. /// /// This will install a global panic hook that will log panics using `tracing`. #[cfg(feature = "tracing")] pub fn with_tracing_panics(mut self, value: bool) -> Self { self.tracing_panics = value; self } /// Configure whether or not to listen for shutdown signals and allow the program to cleanup processes before closing. pub fn with_graceful_shutdown(mut self, value: bool) -> Self { self.graceful_shutdown = value; self } /// Configure the maximum amount of time to wait for the application to shutdown before exiting. pub fn with_graceful_shutdown_timeout(mut self, duration: Duration) -> Self { self.graceful_shutdown_timeout = duration; self } } impl Default for ApplicationConfig { fn default() -> Self { Self { #[cfg(feature = "tracing")] tracing_subscribe: true, #[cfg(feature = "tracing")] tracing_panics: true, graceful_shutdown: true, graceful_shutdown_timeout: Duration::from_secs(10), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/runtime_info.rs
hydra/src/runtime_info.rs
use serde::Deserialize; use serde::Serialize; use tokio::runtime::Handle; use crate::process_len; /// Runtime information for the current hydra instance. #[derive(Serialize, Deserialize)] pub struct RuntimeInfo { /// The crate version of the hydra runtime. pub system_version: String, /// The number of logical cpus on the current machine. pub logical_cpus: usize, /// The number of worker threads currently in use. pub worker_threads: usize, /// The number of processes currently running. pub processes: usize, /// The "physical" memory used by this process, in bytes. /// This corresponds to the following /// metric on each platform: /// - **Linux, Android, MacOS, iOS**: Resident Set Size. /// - **Windows**: Working Set. pub physical_memory: usize, /// The "virtual" memory used by this process, in bytes. /// This corresponds to the following /// metric on each platform: /// - **Linux, Android, MacOS, iOS**: Virtual Size. /// - **Windows**: Pagefile Usage. pub virtual_memory: usize, } impl RuntimeInfo { /// Constructs and loads [RuntimeInfo] data, must be called from within the runtime. pub(super) fn load() -> Self { let runtime = Handle::current(); let (physical_memory, virtual_memory) = memory_stats::memory_stats() .map(|stats| (stats.physical_mem, stats.virtual_mem)) .unwrap_or_default(); Self { system_version: String::from(env!("CARGO_PKG_VERSION")), logical_cpus: std::thread::available_parallelism() .map(|cpus| cpus.get()) .unwrap_or_default(), worker_threads: runtime.metrics().num_workers(), processes: process_len(), physical_memory, virtual_memory, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_registration.rs
hydra/src/process_registration.rs
use tokio::task::JoinHandle; use crate::ExitReason; use crate::ProcessFlags; use crate::ProcessSend; /// Process registration information. pub struct ProcessRegistration { /// A handle to the task that this process lives in. pub handle: JoinHandle<()>, /// The sender of this process. pub sender: ProcessSend, /// Registered name of this process or [None] when unregistered. pub name: Option<String>, /// Process flags. pub flags: ProcessFlags, /// Process exit reason. pub exit_reason: Option<ExitReason>, } impl ProcessRegistration { /// Constructs a new [ProcessRegistration] from a given task handle, and channel. pub const fn new(handle: JoinHandle<()>, sender: ProcessSend) -> Self { Self { handle, sender, name: None, flags: ProcessFlags::empty(), exit_reason: None, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/console.rs
hydra/src/console.rs
use serde::Deserialize; use serde::Serialize; use crate::CallError; use crate::Dest; use crate::ExitReason; use crate::From; use crate::GenServer; use crate::GenServerOptions; use crate::Node; use crate::NodeState; use crate::Pid; use crate::Process; use crate::ProcessInfo; use crate::RuntimeInfo; /// Unique registered name for the console server process. const CONSOLE_NAME: &str = "$hydra_console"; /// Message used by the console server. #[derive(Serialize, Deserialize)] pub enum ConsoleServerMessage { Connect, ConnectSuccess(Pid), ListNodes(NodeState), ListNodesSuccess(Vec<Node>), ListProcesses, ListProcessesSuccess(Vec<Pid>), ProcessesInfo(Vec<Pid>), ProcessesInfoSuccess(Vec<Option<ProcessInfo>>), ListRuntimeInfo, ListRuntimeInfoSuccess(RuntimeInfo), } /// Console acts as a relay to `hydra-console`. It collects and sends realtime information about the current hydra instance. pub struct ConsoleServer { /// Used to prevent anyone from just constructing the console server, it's handled by applications. #[allow(unused)] _ignore: bool, } impl ConsoleServer { /// Constructs a new instance of [ConsoleServer]. pub(super) const fn new() -> Self { Self { _ignore: true } } /// Starts a [ConsoleServer] process linked to the current process. pub(super) async fn start_link(self) -> Result<Pid, ExitReason> { GenServer::start_link(self, GenServerOptions::new().name(CONSOLE_NAME)).await } /// Connects to the [ConsoleServer] on the given node, returning it's [Pid] if successful. pub async fn connect<T: Into<Node>>(node: T) -> Result<Pid, CallError> { use ConsoleServerMessage::*; match ConsoleServer::call((CONSOLE_NAME, node), Connect, None).await? { ConnectSuccess(pid) => Ok(pid), _ => unreachable!(), } } /// Requests the connected node list based on the state. pub async fn list_nodes<T: Into<Dest>>( server: T, state: NodeState, ) -> Result<Vec<Node>, CallError> { use ConsoleServerMessage::*; match ConsoleServer::call(server.into(), ListNodes(state), None).await? { ListNodesSuccess(nodes) => Ok(nodes), _ => unreachable!(), } } /// Requests the list of running processes. pub async fn list_processes<T: Into<Dest>>(server: T) -> Result<Vec<Pid>, CallError> { use ConsoleServerMessage::*; match ConsoleServer::call(server.into(), ListProcesses, None).await? { ListProcessesSuccess(processes) => Ok(processes), _ => unreachable!(), } } /// Requests process info for the given processes. pub async fn processes_info<T: Into<Dest>>( server: T, processes: Vec<Pid>, ) -> Result<Vec<Option<ProcessInfo>>, CallError> { use ConsoleServerMessage::*; match ConsoleServer::call(server.into(), ProcessesInfo(processes), None).await? { ProcessesInfoSuccess(info) => Ok(info), _ => unreachable!(), } } /// Requests runtime info for the hydra instance. pub async fn runtime_info<T: Into<Dest>>(server: T) -> Result<RuntimeInfo, CallError> { use ConsoleServerMessage::*; match ConsoleServer::call(server.into(), ListRuntimeInfo, None).await? { ListRuntimeInfoSuccess(info) => Ok(info), _ => unreachable!(), } } } impl GenServer for ConsoleServer { type Message = ConsoleServerMessage; async fn init(&mut self) -> Result<(), ExitReason> { #[cfg(feature = "tracing")] tracing::info!(console = ?Process::current(), "Console server has started"); Ok(()) } async fn terminate(&mut self, reason: ExitReason) { #[cfg(feature = "tracing")] tracing::info!(console = ?Process::current(), reason = ?reason, "Console server has terminated"); #[cfg(not(feature = "tracing"))] let _ = reason; } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { use ConsoleServerMessage::*; match message { Connect => Ok(Some(ConnectSuccess(Process::current()))), ListNodes(state) => Ok(Some(ListNodesSuccess(Node::list_by_state(state)))), ListProcesses => Ok(Some(ListProcessesSuccess(Process::list()))), ProcessesInfo(pids) => { let process_info = pids.into_iter().map(Process::info).collect(); Ok(Some(ProcessesInfoSuccess(process_info))) } ListRuntimeInfo => Ok(Some(ListRuntimeInfoSuccess(RuntimeInfo::load()))), _ => unreachable!(), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/gen_server.rs
hydra/src/gen_server.rs
use std::future::Future; use std::time::Duration; use tokio::sync::oneshot; use serde::Deserialize; use serde::Serialize; use crate::CallError; use crate::Dest; use crate::Dests; use crate::ExitReason; use crate::From; use crate::GenServerOptions; use crate::Message; use crate::Pid; use crate::Process; use crate::Receivable; use crate::Reference; use crate::SystemMessage; /// Unique message type for a [GenServer] cast, call, and reply. #[derive(Debug, Serialize, Deserialize)] enum GenServerMessage<T: Send + 'static> { #[serde(rename = "$gen_cast")] Cast(T), #[serde(rename = "$gen_call")] Call(From, T), #[serde(rename = "$gen_reply")] CallReply(Reference, T), #[serde(rename = "$gen_stop")] Stop(ExitReason), } /// A trait for implementing the server of a client-server relation. /// /// A [GenServer] is a process like any other hydra process and it can be used to keep state, /// execute code asynchronously and so on. /// /// The advantage of using a generic server process (GenServer) implemented using this /// trait is that it will have a standard set of trait functions and include functionality /// for tracing and error reporting. /// /// It will also fit into a supervision tree. /// /// ## Example /// Let's start with a code example and then explore the available callbacks. Imagine we want to implement a service with a GenServer that works like a stack, allowing us to push and pop elements. We'll customize a generic GenServer with our own module by implementing three callbacks. /// /// ```ignore /// #[derive(Debug, Serialize, Deserialize)] /// enum StackMessage { /// Pop, /// PopResult(String), /// Push(String), /// } /// /// struct Stack { /// stack: Vec<String>, /// } /// /// impl Stack { /// pub fn with_entries(entries: Vec<&'static str>) -> Self { /// Self { /// stack: Vec::from_iter(entries.into_iter().map(Into::into)), /// } /// } /// } /// /// impl GenServer for Stack { /// type Message = StackMessage; /// /// async fn init(&mut self) -> Result<(), ExitReason> { /// Ok(()) /// } /// /// async fn handle_call(&mut self, message: Self::Message, _from: From) -> Result<Option<Self::Message>, ExitReason> { /// match message { /// StackMessage::Pop => Ok(Some(StackMessage::PopResult(self.stack.remove(0)))), /// _ => unreachable!(), /// } /// } /// /// async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { /// match message { /// StackMessage::Push(value) => self.stack.insert(0, value), /// _ => unreachable!(), /// } /// Ok(()) /// } /// } /// ``` /// /// We leave the process machinery of startup, message passing, and the message loop to the GenServer. /// We can now use the GenServer methods to interact with the service by creating a process and sending it messages: /// ```ignore /// // Start the server. /// let pid = Stack::with_entries(vec![String::from("hello"), String::from("world")]) /// .start_link(GenServerOptions::new()) /// .await /// .expect("Failed to start stack!"); /// /// // This is the client. /// Stack::call(pid, StackMessage::Pop, None) /// .await /// .expect("Stack call failed!"); /// // => StackMessage::PopResult("hello") /// /// Stack::cast(pid, StackMessage::Push(String::from("rust"))) /// /// Stack::call(pid, StackMessage::Pop, None) /// .await /// .expect("Stack call failed!"); /// // => StackMessage::PopResult("rust") /// ``` pub trait GenServer: Sized + Send + 'static { /// The message type that this server will use. type Message: Receivable; /// Invoked when the server is started. `start_link` or `start` will block until it returns. fn init(&mut self) -> impl Future<Output = Result<(), ExitReason>> + Send; /// Starts a [GenServer] process without links. fn start( self, options: GenServerOptions, ) -> impl Future<Output = Result<Pid, ExitReason>> + Send { async { start_gen_server(self, options, false).await } } /// Starts a [GenServer] process linked to the current process. fn start_link( self, options: GenServerOptions, ) -> impl Future<Output = Result<Pid, ExitReason>> + Send { async { start_gen_server(self, options, true).await } } /// Synchronously stops the server with the given `reason`. /// /// The `terminate` callback of the given `server` will be invoked before exiting. This function returns an error if the process /// exits with a reason other than the given `reason`. /// /// The default timeout is infinity. fn stop<T: Into<Dest>>( server: T, reason: ExitReason, timeout: Option<Duration>, ) -> impl Future<Output = Result<(), ExitReason>> { async move { let server = server.into(); let monitor = Process::monitor(server.clone()); Process::send( server, GenServerMessage::<Self::Message>::Stop(reason.clone()), ); let receiver = Process::receiver() .for_message::<GenServerMessage<Self::Message>>() .select(|message| matches!(message, Message::System(SystemMessage::ProcessDown(_, tag, _)) if *tag == monitor)); let result = match timeout { Some(duration) => Process::timeout(duration, receiver).await, None => Ok(receiver.await), }; match result { Ok(Message::System(SystemMessage::ProcessDown(_, _, exit_reason))) => { if reason == exit_reason { Ok(()) } else { Err(exit_reason) } } Err(_) => { Process::demonitor(monitor); Err(ExitReason::from("timeout")) } _ => unreachable!(), } } } /// Casts a request to the `servers` without waiting for a response. /// /// It is unknown whether the destination server successfully handled the request. /// /// See [Process::send] for performance trade-offs. fn cast<T: Into<Dests>>(servers: T, message: Self::Message) { Process::send(servers, GenServerMessage::Cast(message)); } /// Casts a request to the `servers` after the given `duration` without waiting for a response. /// /// It is unknown whether the destination server successfully handled the request. /// /// See [Process::send] for performance trade-offs. fn cast_after<T: Into<Dests>>( servers: T, message: Self::Message, duration: Duration, ) -> Reference { Process::send_after(servers, GenServerMessage::Cast(message), duration) } /// Makes a synchronous call to the `server` and waits for it's reply. /// /// The client sends the given `message` to the server and waits until a reply /// arrives or a timeout occurs. `handle_call` will be called on the server to handle the request. /// /// The default timeout is 5000ms. fn call<T: Into<Dest>>( server: T, message: Self::Message, timeout: Option<Duration>, ) -> impl Future<Output = Result<Self::Message, CallError>> + Send { let server = server.into(); async move { let monitor = if server.is_local() { Process::monitor(server.clone()) } else { Process::monitor_alias(server.clone(), true) }; let from = From::new(Process::current(), monitor, server.is_remote()); Process::send(server, GenServerMessage::Call(from, message)); let receiver = Process::receiver() .for_message::<GenServerMessage<Self::Message>>() .select(|message| { match message { Message::User(GenServerMessage::CallReply(tag, _)) => { // Make sure the tag matches the monitor. *tag == monitor } Message::System(SystemMessage::ProcessDown(_, tag, _)) => { // Make sure the tag matches the monitor. *tag == monitor } _ => false, } }); let result = Process::timeout(timeout.unwrap_or(Duration::from_millis(5000)), receiver).await; match result { Ok(Message::User(GenServerMessage::CallReply(_, message))) => { Process::demonitor(monitor); Ok(message) } Ok(Message::System(SystemMessage::ProcessDown(_, _, reason))) => { Err(CallError::ServerDown(reason)) } Err(timeout) => { Process::demonitor(monitor); // Drop a stale reply that may already be in the process message inbox. Process::receiver() .for_message::<GenServerMessage<Self::Message>>() .remove(|message| matches!(message, Message::User(GenServerMessage::CallReply(tag, _)) if *tag == monitor)); Err(CallError::Timeout(timeout)) } _ => unreachable!(), } } } /// Replies to a client. /// /// This function can be used to explicitly send a reply to a client that called `call` when the /// reply cannot be specified in the return value of `handle_call`. /// /// `client` must be the `from` argument accepted by `handle_call` callbacks. /// /// Note that `reply` can be called from any process, not just the [GenServer] that originally received the call /// (as long as the GenServer communicated the `from` argument somehow). fn reply(from: From, message: Self::Message) { if from.is_alias() { Process::send(from.tag(), GenServerMessage::CallReply(from.tag(), message)); } else { Process::send(from.pid(), GenServerMessage::CallReply(from.tag(), message)); } } /// Invoked when the server is about to exit. It should do any cleanup required. /// /// `terminate` is useful for cleanup that requires access to the [GenServer]'s state. However, it is not /// guaranteed that `terminate` is called when a [GenServer] exits. Therefore, important cleanup should be done /// using process links and/or monitors. A monitoring process will receive the same `reason` that would be passed to `terminate`. /// /// `terminate` is called if: /// - The [GenServer] traps exits (using [Process::flags]) and the parent process sends an exit signal. /// - A callback (except `init`) returns stop with a given reason. /// - The `stop` method is called on a [GenServer]. fn terminate(&mut self, reason: ExitReason) -> impl Future<Output = ()> + Send { async move { let _ = reason; } } /// Invoked to handle asynchronous `cast` messages. fn handle_cast( &mut self, message: Self::Message, ) -> impl Future<Output = Result<(), ExitReason>> + Send { async move { let _ = message; unimplemented!(); } } /// Invoked to handle all other messages. fn handle_info( &mut self, info: Message<Self::Message>, ) -> impl Future<Output = Result<(), ExitReason>> + Send { async move { let _ = info; Ok(()) } } /// Invoked to handle synchronous `call` messages. `call` will block until a reply is received /// (unless the call times out or nodes are disconnected). /// /// `from` is a struct containing the callers [Pid] and a [Reference] that uniquely identifies the call. fn handle_call( &mut self, message: Self::Message, from: From, ) -> impl Future<Output = Result<Option<Self::Message>, ExitReason>> + Send { async move { let _ = message; let _ = from; unimplemented!(); } } } /// Internal [GenServer] start routine. async fn start_gen_server<T: GenServer>( gen_server: T, options: GenServerOptions, link: bool, ) -> Result<Pid, ExitReason> { let (tx, rx) = oneshot::channel::<Result<(), ExitReason>>(); let parent: Option<Pid> = link.then(Process::current); let server = async move { let mut gen_server = gen_server; let mut options = options; let parent = parent.unwrap_or(Process::current()); let registered = if let Some(name) = options.name.take() { Process::register(Process::current(), name).is_ok() } else { true }; if !registered { tx.send(Err(ExitReason::from("already_started"))) .expect("Failed to notify parent process!"); return; } let timeout = if let Some(duration) = options.timeout.take() { Process::timeout(duration, gen_server.init()).await } else { Ok(gen_server.init().await) }; match timeout { Ok(Ok(())) => { tx.send(Ok(())).expect("Failed to notify parent process!"); } Ok(Err(reason)) => { tx.send(Err(reason.clone())) .expect("Failed to notify parent process!"); return Process::exit(Process::current(), reason); } Err(_) => { tx.send(Err(ExitReason::from("timeout"))) .expect("Failed to notify parent process!"); return Process::exit(Process::current(), ExitReason::from("timeout")); } } loop { let message: Message<GenServerMessage<T::Message>> = Process::receive().await; match message { Message::User(GenServerMessage::Cast(message)) => { if let Err(reason) = gen_server.handle_cast(message).await { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } Message::User(GenServerMessage::Call(from, message)) => { match gen_server.handle_call(message, from).await { Ok(Some(message)) => { T::reply(from, message); } Ok(None) => { // Server must reply using `GenServer::reply(from, message)`. } Err(reason) => { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } } Message::User(GenServerMessage::CallReply(_, message)) => { if let Err(reason) = gen_server.handle_info(Message::User(message)).await { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } Message::User(GenServerMessage::Stop(reason)) => { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } Message::System(system) => match system { SystemMessage::Exit(epid, reason) if epid == parent => { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } _ => { if let Err(reason) = gen_server.handle_info(Message::System(system)).await { gen_server.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } }, } } }; let pid = if link { Process::spawn_link(server) } else { Process::spawn(server) }; rx.await .map_err(|_| ExitReason::from("unknown"))? .map(|_| pid) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_kernel.rs
hydra/src/process_kernel.rs
use std::collections::BTreeMap; use crate::frame::Frame; use crate::frame::Send; use crate::frame::SendTarget; use crate::Dest; use crate::Dests; use crate::Message; use crate::ProcessItem; use crate::Receivable; use crate::alias_retrieve; use crate::node_process_send_with_alias; use crate::node_process_send_with_name; use crate::node_process_send_with_pid; use crate::node_register; use crate::node_send_frame; use crate::process_name_lookup; use crate::process_sender; use crate::serialize_value; /// Sends a message to one or more destinations. pub fn process_send<M: Receivable>(dests: Dests, message: M) { match dests { Dests::Dest(dest) => { process_send_optimal(dest, message); } Dests::Dests(dests) => { let mut first_local_process: Option<Dest> = None; let mut serialized: Option<Vec<u8>> = None; // Delay serialization until it's absolutely necessary to have it. let mut get_serialized = || { if let Some(serialized) = &serialized { serialized.clone() } else { let message = serialize_value(&message); serialized = Some(message.clone()); message } }; let mut remote_sends: BTreeMap<u64, Send> = BTreeMap::new(); for dest in dests { if dest.is_local() && first_local_process.is_none() { first_local_process = Some(dest); continue; } if dest.is_local() { process_send_unoptimal(dest, get_serialized()); } else { let (node, send_target) = match dest { Dest::Pid(pid) => (pid.node(), SendTarget::from(pid)), Dest::Named(name, node) => { (node_register(node, false), SendTarget::from(name)) } Dest::Alias(reference) => (reference.node(), SendTarget::from(reference)), }; remote_sends .entry(node) .or_insert(Send::with_message(get_serialized())) .targets .push(send_target); } } // Fast path optimization to move the message itself into the mailbox of one local process destination. if let Some(dest) = first_local_process.take() { process_send_optimal(dest, message); } // Optimally send one packet per target node. for (node, send) in remote_sends { node_send_frame(Frame::from(send), node); } } } } /// Sends a single message to the target destination, avoiding T: Clone. /// /// TODO: This is a suboptimal path, that can be replaced once specialization lands by specializing on T: Clone. fn process_send_unoptimal(dest: Dest, message: Vec<u8>) { match dest { Dest::Pid(pid) => { process_sender(pid).map(|sender| sender.send(ProcessItem::UserRemoteMessage(message))); } Dest::Named(name, _) => { process_name_lookup(name.as_ref()) .and_then(process_sender) .map(|sender| sender.send(ProcessItem::UserRemoteMessage(message))); } Dest::Alias(reference) => { alias_retrieve(reference) .map(|alias| alias.sender.send(ProcessItem::UserRemoteMessage(message))); } } } // Optimally sends a single message to the target destination. fn process_send_optimal<M: Receivable>(dest: Dest, message: M) { match dest { Dest::Pid(pid) => { if pid.is_local() { process_sender(pid).map(|sender| sender.send(Message::User(message).into())); } else { node_process_send_with_pid(pid, message); } } Dest::Named(name, node) => { if node.is_local() { process_name_lookup(name.as_ref()) .and_then(process_sender) .map(|sender| sender.send(Message::User(message).into())); } else { node_process_send_with_name(name.into_owned(), node, message); } } Dest::Alias(reference) => { if reference.is_local() { alias_retrieve(reference) .map(|alias| alias.sender.send(Message::User(message).into())); } else { node_process_send_with_alias(reference, message); } } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/message.rs
hydra/src/message.rs
use crate::SystemMessage; /// A messages sent to a process. #[derive(Debug)] pub enum Message<T> { /// A message that was sent from another process. User(T), /// A message that was sent from the system. System(SystemMessage), }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_local.rs
hydra/src/node_local.rs
use std::sync::Arc; use serde::Deserialize; use serde::Serialize; use tokio::net::TcpListener; use crate::Local; use crate::Message; use crate::NodeOptions; use crate::NodeRemoteConnectorMessage; use crate::Pid; use crate::Process; use crate::ProcessFlags; use crate::SystemMessage; use crate::node_local_panic; use crate::node_remote_accepter; #[derive(Serialize, Deserialize)] pub enum NodeLocalSupervisorMessage { /// Occurs when a connector process requests the supervisor. RequestLocalSupervisor(Pid), } pub struct NodeLocalSupervisor { pub name: String, pub options: NodeOptions, #[allow(dead_code)] pub process: Pid, } impl Drop for NodeLocalSupervisor { fn drop(&mut self) { node_local_panic(); } } async fn node_local_listener(supervisor: Arc<NodeLocalSupervisor>) { let listener = TcpListener::bind(supervisor.options.listen_address) .await .expect("Failed to bind socket for local node listener!"); loop { let Ok((socket, _)) = listener.accept().await else { continue; }; Process::spawn(node_remote_accepter(socket, supervisor.clone())); } } pub async fn node_local_supervisor(name: String, options: NodeOptions) { Process::set_flags(ProcessFlags::TRAP_EXIT); let supervisor = Arc::new(NodeLocalSupervisor { name, options, process: Process::current(), }); let listener = Process::spawn_link(node_local_listener(supervisor.clone())); loop { let message = Process::receive::<NodeLocalSupervisorMessage>().await; match message { Message::User(NodeLocalSupervisorMessage::RequestLocalSupervisor(process)) => { let supervisor = Local::new(supervisor.clone()); Process::send( process, NodeRemoteConnectorMessage::LocalNodeSupervisor(supervisor), ); } Message::System(SystemMessage::Exit(pid, exit_reason)) => { if pid == listener { panic!("Lost the local node listener: {:?}!", exit_reason); } } _ => unreachable!(), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/call_error.rs
hydra/src/call_error.rs
use serde::Deserialize; use serde::Serialize; use crate::ExitReason; use crate::Timeout; /// Occurs when a server call fails. #[derive(Debug, Serialize, Deserialize)] pub enum CallError { Timeout(Timeout), ServerDown(ExitReason), }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_registry.rs
hydra/src/node_registry.rs
use std::collections::BTreeMap; use std::collections::BTreeSet; use std::net::SocketAddr; use std::sync::Mutex; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use dashmap::DashMap; use dashmap::mapref::entry::Entry; use once_cell::sync::Lazy; use crate::frame::Frame; use crate::Dest; use crate::ExitReason; use crate::Local; use crate::Node; use crate::NodeOptions; use crate::NodeRegistration; use crate::NodeRemoteSenderMessage; use crate::NodeState; use crate::Pid; use crate::Process; use crate::ProcessItem; use crate::Reference; use crate::alias_destroy; use crate::link_destroy; use crate::monitor_destroy; use crate::node_local_supervisor; use crate::node_remote_connector; use crate::process_exit_signal_linked; use crate::process_sender; /// Represents the node id always used for the local node. pub const LOCAL_NODE_ID: u64 = 0; /// Represents a node id that will never be allocated. pub const INVALID_NODE_ID: u64 = u64::MAX; /// The type of node monitor that was installed. #[derive(Debug)] enum NodeMonitor { /// The monitor is explicitly for the node itself. Node(u64), /// The monitor is installed on behalf of a remote process monitor. ProcessMonitor(u64, Dest), /// The monitor is installed on behalf of a remote process monitor for cleanup. ProcessMonitorCleanup(u64), } // When a pid is serialized over the wire, we need to lookup it's node@ip:port combination. // If it's already in the registry, we need to get it's node id, else // we need to get it's thing. static NODE_REGISTRATIONS: Lazy<DashMap<u64, NodeRegistration>> = Lazy::new(DashMap::new); /// A collection of node:id into the node registrations. static NODE_MAP: Lazy<DashMap<Node, u64>> = Lazy::new(DashMap::new); /// A collection of node monitors installed. static NODE_MONITORS: Lazy<DashMap<Node, BTreeMap<Reference, NodeMonitor>>> = Lazy::new(DashMap::new); /// A collection of node links installed. static NODE_LINKS: Lazy<DashMap<Node, BTreeSet<(Pid, u64)>>> = Lazy::new(DashMap::new); /// A collection of node:vec<msg> pending messages for a node. static NODE_PENDING_MESSAGES: Lazy<DashMap<Node, Vec<Frame>>> = Lazy::new(DashMap::new); /// A secret value that secures the connection between nodes. static NODE_COOKIE: Mutex<Option<String>> = Mutex::new(None); /// The next id for this node. static NODE_ID: AtomicU64 = AtomicU64::new(1); /// Returns `true` if the local node is alive. pub fn node_alive() -> bool { NODE_MAP.contains_key(&Node::Local) } /// Starts the local node. pub fn node_local_start(name: String, options: NodeOptions) -> Pid { let Entry::Vacant(entry) = NODE_MAP.entry(Node::Local) else { panic!("Local node already started!"); }; let supervisor = Process::spawn(node_local_supervisor(name.clone(), options)); NODE_REGISTRATIONS.insert( LOCAL_NODE_ID, NodeRegistration::new( Some(supervisor), NodeState::Current, name, options.broadcast_address, ), ); entry.insert(LOCAL_NODE_ID); supervisor } /// Stops the local node, forgetting all nodes. pub fn node_local_stop() { let Some((_, _)) = NODE_MAP.remove(&Node::Local) else { panic!("Local node not started!"); }; NODE_MAP.clear(); if let Some(entry) = NODE_REGISTRATIONS.get(&LOCAL_NODE_ID) && let Some(supervisor) = entry.supervisor { Process::exit(supervisor, ExitReason::Kill); } NODE_REGISTRATIONS.clear(); NODE_PENDING_MESSAGES.clear(); } /// Cleans up distribution information when the local node goes down unexpectedly. pub fn node_local_panic() { NODE_MAP.clear(); NODE_REGISTRATIONS.clear(); NODE_PENDING_MESSAGES.clear(); } /// Returns the process responsible for the local node. pub fn node_local_process() -> Option<Pid> { NODE_REGISTRATIONS .get(&LOCAL_NODE_ID) .and_then(|process| process.supervisor) } /// Sets available worker processes for a node, then, drains any pending messages to them. pub fn node_register_workers(node: Node, sender: Pid, receiver: Pid) { let Some(entry) = NODE_MAP.get(&node) else { return; }; NODE_REGISTRATIONS.alter(&entry, |_, mut value| { value.sender = Some(sender); value.receiver = Some(receiver); let frames = NODE_PENDING_MESSAGES .remove(&node) .map(|pending| pending.1) .unwrap_or_default(); // We need to pop the pending messages and send them to the sender // This way, the order for sent messages is maintained and all future messages go direct to the sender. Process::send( sender, NodeRemoteSenderMessage::SendFrames(Local::new(frames)), ); value }); } /// Gets the send process for a given node. pub fn node_send_frame(frame: Frame, id: u64) { let Some(registration) = NODE_REGISTRATIONS.get(&id) else { return; }; if let Some(sender) = registration.sender { Process::send( sender, NodeRemoteSenderMessage::SendFrame(Local::new(frame)), ); } else if !matches!(registration.state, NodeState::Known) { NODE_PENDING_MESSAGES .entry(Node::from(( registration.name.clone(), registration.broadcast_address, ))) .or_default() .push(frame); } } /// Accepts a remote node's connection if one doesn't exist, returns `true` if accepted. pub fn node_accept(node: Node, supervisor: Pid) -> bool { let Node::Remote(name, address) = node else { panic!("Can't accept a local node!"); }; let entry = NODE_MAP.entry(Node::from((name.clone(), address))); match entry { Entry::Vacant(entry) => { let next_id = NODE_ID.fetch_add(1, Ordering::Relaxed); NODE_REGISTRATIONS.insert( next_id, NodeRegistration::new(Some(supervisor), NodeState::Connected, name, address), ); entry.insert(next_id); true } Entry::Occupied(entry) => { let mut accepted = false; NODE_REGISTRATIONS.alter(entry.get(), |_, mut value| { if matches!(value.state, NodeState::Pending) && let Some(current_supervisor) = value.supervisor.take() && supervisor != current_supervisor { Process::exit(current_supervisor, ExitReason::Kill); } if value.supervisor.is_none() { accepted = true; value.supervisor = Some(supervisor); value.state = NodeState::Connected; } value }); accepted } } } /// Registers a remote node's information, or returns an existing one. pub fn node_register(node: Node, connect: bool) -> u64 { let Node::Remote(name, address) = node else { panic!("Can't register a local node!"); }; let node = Node::from((name.clone(), address)); let entry = match NODE_MAP.entry(node.clone()) { Entry::Vacant(entry) => entry, Entry::Occupied(entry) => { let id = *entry.get(); if connect { NODE_REGISTRATIONS.alter(&id, |_, mut value| { if value.supervisor.is_none() { value.supervisor = Some(Process::spawn(node_remote_connector(node))); value.state = NodeState::Pending; } value }); } return id; } }; let next_id = NODE_ID.fetch_add(1, Ordering::Relaxed); if connect { let supervisor = Process::spawn(node_remote_connector(node)); NODE_REGISTRATIONS.insert( next_id, NodeRegistration::new(Some(supervisor), NodeState::Pending, name, address), ); } else { NODE_REGISTRATIONS.insert( next_id, NodeRegistration::new(None, NodeState::Known, name, address), ); } entry.insert(next_id); next_id } /// Triggered when a remote node supervisor goes down unexpectedly. pub fn node_remote_supervisor_down(node: Node, process: Pid) { let Some(id) = NODE_MAP.get(&node) else { return; }; NODE_REGISTRATIONS.alter(&id, |_, mut value| { if value .supervisor .is_some_and(|supervisor| supervisor != process) { return value; } value.supervisor = None; value.sender = None; value.receiver = None; value.state = NodeState::Known; if let Some((_, links)) = NODE_LINKS.remove(&node) { for (from, process_id) in links { let process = Pid::local(process_id); link_destroy(process, from); process_exit_signal_linked(process, from, ExitReason::from("noconnection")); } } if let Some((_, monitors)) = NODE_MONITORS.remove(&node) { for (reference, monitor) in monitors { match monitor { NodeMonitor::Node(id) => { process_sender(Pid::local(id)).map(|sender| { sender.send(ProcessItem::MonitorNodeDown(node.clone(), reference)) }); } NodeMonitor::ProcessMonitor(id, dest) => { process_sender(Pid::local(id)).map(|sender| { sender.send(ProcessItem::MonitorProcessDown( dest, reference, ExitReason::from("noconnection"), )) }); } NodeMonitor::ProcessMonitorCleanup(id) => { monitor_destroy(Pid::local(id), reference); } } if reference.is_local() { alias_destroy(reference); } } } NODE_PENDING_MESSAGES.remove(&node); value }); } /// Returns the node list excluding the local node. pub fn node_list() -> Vec<Node> { NODE_MAP .iter() .filter_map(|entry| { if matches!(entry.key(), Node::Local) { None } else { Some(entry.key().clone()) } }) .collect() } /// Returns the node list filtered to the given node state. pub fn node_list_filtered(state: NodeState) -> Vec<Node> { NODE_REGISTRATIONS .iter() .filter_map(|entry| { if entry.state == state { Some(Node::from((entry.name.clone(), entry.broadcast_address))) } else { None } }) .collect() } /// Disconnects a connected node, leaving it as a known node. pub fn node_disconnect(node: Node) { let Some(id) = NODE_MAP.get(&node) else { return; }; NODE_REGISTRATIONS.alter(&id, |_, mut value| { NODE_PENDING_MESSAGES.remove(&node); if let Some(supervisor) = value.supervisor.take() { Process::exit(supervisor, ExitReason::Kill); } value.state = NodeState::Known; value }); } /// Disconnects and forgets a node completely. pub fn node_forget(node: Node) { let Some((_, id)) = NODE_MAP.remove(&node) else { return; }; let Some((_, registration)) = NODE_REGISTRATIONS.remove(&id) else { return; }; NODE_PENDING_MESSAGES.remove(&node); if let Some(supervisor) = registration.supervisor { Process::exit(supervisor, ExitReason::Kill); } } /// Looks up the node information for the local node. pub fn node_lookup_local() -> Option<(String, SocketAddr)> { NODE_REGISTRATIONS .get(&LOCAL_NODE_ID) .map(|registration| (registration.name.clone(), registration.broadcast_address)) } /// Looks up the node information for a remote node id. pub fn node_lookup_remote(id: u64) -> Option<(String, SocketAddr)> { NODE_REGISTRATIONS .get(&id) .map(|registration| (registration.name.clone(), registration.broadcast_address)) } /// Creates a monitor for the given node and reference from the given process. pub fn node_monitor_create(node: Node, reference: Reference, from: Pid) { NODE_MONITORS .entry(node) .or_default() .insert(reference, NodeMonitor::Node(from.id())); } /// Creates a monitor for the given node and reference from the given process for dest. pub fn node_process_monitor_create(node: Node, reference: Reference, dest: Dest, from: Pid) { NODE_MONITORS .entry(node) .or_default() .insert(reference, NodeMonitor::ProcessMonitor(from.id(), dest)); } /// Creates a monitor cleanup for the given node and reference from the given process. pub fn node_process_monitor_cleanup(node: Node, reference: Reference, process: Pid) { NODE_MONITORS .entry(node) .or_default() .insert(reference, NodeMonitor::ProcessMonitorCleanup(process.id())); } /// Destroys a node process monitor for the given node and reference. pub fn node_process_monitor_destroy(node: Node, reference: Reference) { NODE_MONITORS.alter(&node, |_, mut value| { value.remove(&reference); value }); } /// Destroys all process monitors for the given node by their references. pub fn node_process_monitor_destroy_all(node: Node, references: Vec<Reference>) { NODE_MONITORS.alter(&node, |_, mut value| { for reference in references { value.remove(&reference); } value }); } /// Destroys a node process link for the given node by the link process. pub fn node_process_link_destroy(node: Node, link: Pid, from: Pid) { NODE_LINKS.alter(&node, |_, mut value| { value.remove(&(link, from.id())); value }); } /// Destroys all process links for the given node by their link processes. pub fn node_process_link_destroy_all(node: Node, links: Vec<Pid>, from: Pid) { NODE_LINKS.alter(&node, |_, mut value| { for link in links { value.remove(&(link, from.id())); } value }); } /// Creates a monitor for the given node and process from the given linked process. pub fn node_process_link_create(node: Node, process: Pid, from: Pid) { NODE_LINKS .entry(node) .or_default() .insert((process, from.id())); } /// Removes a monitor for the given node and reference. pub fn node_monitor_destroy(node: Node, reference: Reference) { NODE_MONITORS.alter(&node, |_, mut value| { value.remove(&reference); value }); } /// Removes a link for the given node and process. pub fn node_link_destroy(node: Node, process: Pid, from: Pid) { NODE_LINKS.alter(&node, |_, mut value| { value.remove(&(process, from.id())); value }); } /// Fires when a remote process has notified the local node that it went down for a monitor. pub fn node_process_monitor_down(node: Node, reference: Reference, exit_reason: ExitReason) { let mut monitor: Option<NodeMonitor> = None; NODE_MONITORS.alter(&node, |_, mut value| { monitor = value.remove(&reference); value }); alias_destroy(reference); if let Some(NodeMonitor::ProcessMonitor(id, dest)) = monitor { process_sender(Pid::local(id)).map(|sender| { sender.send(ProcessItem::MonitorProcessDown( dest, reference, exit_reason, )) }); } } /// Fires when a remote process has notified the local node that it went down for a link. pub fn node_process_link_down(node: Node, process: Pid, from: Pid, exit_reason: ExitReason) { let mut found = false; NODE_LINKS.alter(&node, |_, mut value| { found = value.remove(&(from, process.id())); value }); if found { process_exit_signal_linked(process, from, exit_reason); } } /// Gets the cookie secret value. pub fn node_get_cookie() -> Option<String> { NODE_COOKIE.lock().unwrap().clone() } /// Sets or clears the cookie secret value. pub fn node_set_cookie(cookie: Option<String>) { *NODE_COOKIE.lock().unwrap() = cookie; }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/receivable.rs
hydra/src/receivable.rs
use serde::Serialize; use serde::de::DeserializeOwned; // TODO: Once specialization lands, we can make a specialization for Receivable that handles types that are `Deserialize` vs not so that // We can send any T to a local process and panic at runtime if we try to send a non `Deserialize` type. /// An object that can be sent or received to/from a process. pub trait Receivable: Serialize + DeserializeOwned + Send + 'static {} impl<T> Receivable for T where T: Serialize + DeserializeOwned + Send + 'static {}
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_registry.rs
hydra/src/process_registry.rs
use std::time::Duration; use std::time::Instant; use dashmap::DashMap; use dashmap::mapref::entry::Entry; use once_cell::sync::Lazy; use tokio::task::JoinHandle; use crate::ArgumentError; use crate::ExitReason; use crate::Pid; use crate::ProcessFlags; use crate::ProcessInfo; use crate::ProcessItem; use crate::ProcessRegistration; use crate::ProcessSend; use crate::Reference; use crate::SystemMessage; /// A collection of process id -> process registration. static PROCESS_REGISTRY: Lazy<DashMap<u64, ProcessRegistration>> = Lazy::new(DashMap::new); /// A collection of registered named processes. static PROCESS_NAMES: Lazy<DashMap<String, u64>> = Lazy::new(DashMap::new); /// A collection of process timers. static PROCESS_TIMERS: Lazy<DashMap<u64, (Instant, JoinHandle<()>)>> = Lazy::new(DashMap::new); /// Checks for the given `pid` and calls the given `callback` with the result if it exists or not. /// /// The process will exist for the duration of `callback`. pub fn process_exists_lock<C: FnOnce(bool) -> R, R>(pid: Pid, callback: C) -> R { if PROCESS_REGISTRY.get(&pid.id()).is_some() { callback(true) } else { callback(false) } } /// Drops a process from the registry. pub fn process_drop(pid: Pid) -> Option<ProcessRegistration> { PROCESS_REGISTRY .remove(&pid.id()) .map(|(_, process)| process) } /// Gets the sender for this process. pub fn process_sender(pid: Pid) -> Option<ProcessSend> { PROCESS_REGISTRY .get(&pid.id()) .map(|process| process.sender.clone()) } /// Looks up a process by the given name. pub fn process_name_lookup(name: &str) -> Option<Pid> { PROCESS_NAMES .get(name) .map(|process_id| Pid::local(*process_id)) } /// Inserts a new process registration. pub fn process_insert(id: u64, registration: ProcessRegistration) { PROCESS_REGISTRY.insert(id, registration); } /// Removes a registered name. pub fn process_name_remove(name: &str) { PROCESS_NAMES.remove(name); } /// Checks if the process is alive. pub fn process_alive(pid: Pid) -> bool { if pid.is_remote() { panic!("Expected a local pid!"); } PROCESS_REGISTRY .get(&pid.id()) .map(|process| process.exit_reason.is_none()) .unwrap_or_default() } /// Registers a process under the given name. pub fn process_register(pid: Pid, name: String) -> Result<(), ArgumentError> { if pid.is_remote() { return Err(ArgumentError::from("Expected local pid for register!")); } let entry = PROCESS_NAMES.entry(name.clone()); let entry = match entry { Entry::Occupied(entry) => { if *entry.get() == pid.id() { return Ok(()); } else { return Err(ArgumentError::from(format!( "Name {:?} registered to another process!", name ))); } } Entry::Vacant(entry) => entry, }; let mut updated = false; let mut found = false; PROCESS_REGISTRY.alter(&pid.id(), |_, mut process| { found = true; if process.name.is_none() { process.name = Some(name); updated = true; } process }); if !found { return Err(ArgumentError::from("Process does not exist!")); } if !updated { return Err(ArgumentError::from(format!( "Process {:?} was already registered!", pid ))); } entry.insert(pid.id()); Ok(()) } /// Unregisters a process with the given name. pub fn process_unregister(name: &str) { let Some((_, pid)) = PROCESS_NAMES.remove(name) else { panic!("Name {:?} was not registered!", name); }; PROCESS_REGISTRY.alter(&pid, |_, mut process| { process.name = None; process }); } /// Processes an exit signal for the given [Pid] with the `exit_reason`. pub fn process_exit(pid: Pid, from: Pid, exit_reason: ExitReason) { PROCESS_REGISTRY.alter(&pid.id(), |_, mut process| { let trapping_exits = process.flags.contains(ProcessFlags::TRAP_EXIT); match exit_reason { ExitReason::Normal | ExitReason::Ignore => { if pid == from { process.exit_reason = Some(exit_reason); process.handle.abort(); } else if trapping_exits { process .sender .send(ProcessItem::SystemMessage(SystemMessage::Exit( from, exit_reason, ))) .unwrap(); } } ExitReason::Kill => { process.exit_reason = Some(exit_reason); process.handle.abort(); } ExitReason::Custom(_) => { if pid == from || !trapping_exits { process.exit_reason = Some(exit_reason); process.handle.abort(); } else { process .sender .send(ProcessItem::SystemMessage(SystemMessage::Exit( from, exit_reason, ))) .unwrap(); } } } process }); } /// Forwards an exit signal to the linked [Pid] from the given [Pid] with the `exit_reason`. pub fn process_exit_signal_linked(pid: Pid, from: Pid, exit_reason: ExitReason) { PROCESS_REGISTRY.alter(&pid.id(), |_, mut process| { if process.flags.contains(ProcessFlags::TRAP_EXIT) { process .sender .send(ProcessItem::SystemMessage(SystemMessage::Exit( from, exit_reason.clone(), ))) .unwrap(); } else if !exit_reason.is_normal() { process.exit_reason = Some(exit_reason); process.handle.abort(); } process }); } /// Returns the process flags for the given process. pub fn process_flags(pid: Pid) -> Option<ProcessFlags> { PROCESS_REGISTRY.get(&pid.id()).map(|process| process.flags) } /// Sets the process flags. pub fn process_set_flags(pid: Pid, flags: ProcessFlags) { PROCESS_REGISTRY.alter(&pid.id(), |_, mut process| { process.flags = flags; process }); } /// Sets the process exit reason. pub fn process_set_exit_reason(pid: Pid, exit_reason: ExitReason) { PROCESS_REGISTRY.alter(&pid.id(), |_, mut process| { process.exit_reason = Some(exit_reason); process }); } /// Returns a list of processes. pub fn process_list() -> Vec<Pid> { PROCESS_REGISTRY .iter() .map(|process| Pid::local(*process.key())) .collect() } /// Returns a list of registered process names. pub fn process_name_list() -> Vec<String> { PROCESS_NAMES .iter() .map(|value| value.key().to_owned()) .collect() } /// Registers a timer. pub fn process_register_timer(timer: Reference, duration: Duration, handle: JoinHandle<()>) { PROCESS_TIMERS.insert(timer.id(), (Instant::now() + duration, handle)); } /// Reads a timer. pub fn process_read_timer(timer: Reference) -> Option<Duration> { let time = PROCESS_TIMERS.get(&timer.id())?; let now = Instant::now(); let timer = time.value().0; if timer <= now { Some(Duration::from_secs(0)) } else { Some(timer - now) } } /// Unregisters and kills a timer. pub fn process_destroy_timer(timer: Reference) { if let Some((_, (_, handle))) = PROCESS_TIMERS.remove(&timer.id()) { handle.abort(); } } /// Gets process registry info. pub fn process_info(pid: Pid) -> Option<ProcessInfo> { let process = PROCESS_REGISTRY.get(&pid.id())?; let mut info = ProcessInfo::new(); info.registered_name.clone_from(&process.name); info.message_queue_len = process.sender.len(); info.trap_exit = process.flags.contains(ProcessFlags::TRAP_EXIT); Some(info) } /// The number of processes currently running. #[cfg(feature = "console")] pub fn process_len() -> usize { PROCESS_REGISTRY.len() }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/node_registration.rs
hydra/src/node_registration.rs
use std::net::SocketAddr; use crate::NodeState; use crate::Pid; /// Node registration information. pub struct NodeRegistration { /// The process responsible for this node. pub supervisor: Option<Pid>, /// The process responsible for sending outbound messages for this node. pub sender: Option<Pid>, /// The process responsible for receiving messages for this node. pub receiver: Option<Pid>, /// The state of this node. pub state: NodeState, /// The name of this node. pub name: String, /// The broadcast address of this node. pub broadcast_address: SocketAddr, } impl NodeRegistration { /// Constructs a new [NodeRegistration] from a given process, name, and broadcast address. pub fn new( supervisor: Option<Pid>, state: NodeState, name: String, broadcast_address: SocketAddr, ) -> Self { Self { supervisor, sender: None, receiver: None, state, name, broadcast_address, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/child_spec.rs
hydra/src/child_spec.rs
use std::future::Future; use std::sync::Arc; use serde::Deserialize; use serde::Serialize; use crate::ExitReason; use crate::Pid; use crate::Restart; use crate::Shutdown; /// The type of child process. #[derive(Debug, Serialize, Deserialize, Clone, Copy)] pub enum ChildType { /// The child is a worker process. Worker, /// The child is a supervisor process. Supervisor, } /// The child specification describes how the supervisor starts, shuts down, and restarts child processes. #[derive(Clone)] pub struct ChildSpec { pub(crate) id: String, #[allow(clippy::type_complexity)] pub(crate) start: Option< Arc< dyn Fn() -> Box<dyn Future<Output = Result<Pid, ExitReason>> + Send + Sync> + Send + Sync, >, >, pub(crate) restart: Restart, pub(crate) shutdown: Option<Shutdown>, pub(crate) child_type: ChildType, pub(crate) significant: bool, } impl ChildSpec { /// Constructs a new instance of [ChildSpec] with the given id. pub fn new<T: Into<String>>(id: T) -> Self { Self { id: id.into(), start: None, restart: Restart::Permanent, shutdown: None, child_type: ChildType::Worker, significant: false, } } /// Sets a new id for this [ChildSpec]. pub fn id<T: Into<String>>(mut self, id: T) -> Self { self.id = id.into(); self } /// The method invoked to start the child process. /// /// Must return a future that resolves to [Result<Pid, ExitReason>]. pub fn start<T, F>(mut self, start: T) -> Self where T: Fn() -> F + Send + Sync + 'static, F: Future<Output = Result<Pid, ExitReason>> + Send + Sync + 'static, { self.start = Some(Arc::new(move || Box::new(start()))); self } /// Defines when a terminated child process should be restarted. /// /// Defaults to [Restart::Permanent]. pub const fn restart(mut self, restart: Restart) -> Self { self.restart = restart; self } /// Defines how a process should be terminated, specifically how long to wait before forcefully killing it. /// /// Defaults to 5s if the type is `worker` or infinity if the type is `supervisor`. pub fn shutdown<T: Into<Shutdown>>(mut self, shutdown: T) -> Self { self.shutdown = Some(shutdown.into()); self } /// Specifies the type of child process. pub const fn child_type(mut self, child_type: ChildType) -> Self { self.child_type = child_type; self } /// A boolean indicating if the child process should be considered significant with regard to automatic shutdown. /// /// Only `transient` and `temporary` child processes can be marked as significant. /// /// Defaults to `false`. pub const fn significant(mut self, significant: bool) -> Self { if significant && !matches!(self.restart, Restart::Temporary) && !matches!(self.restart, Restart::Transient) { panic!("Only temporary/transient children can be marked significant!"); } self.significant = significant; self } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_flags.rs
hydra/src/process_flags.rs
use bitflags::bitflags; bitflags! { /// A collection of configurable flags for a process. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct ProcessFlags : u32 { /// Whether or not the process is trapping exits. const TRAP_EXIT = 1 << 0; } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/gen_server_options.rs
hydra/src/gen_server_options.rs
use std::time::Duration; /// Options used to configure a GenServer. #[derive(Debug, Default, Clone)] pub struct GenServerOptions { pub(crate) name: Option<String>, pub(crate) timeout: Option<Duration>, } impl GenServerOptions { /// Constructs a new instance of [GenServerOptions] with the default values. pub const fn new() -> Self { Self { name: None, timeout: None, } } /// Specifies a name to register the GenServer under. pub fn name<T: Into<String>>(mut self, name: T) -> Self { self.name = Some(name.into()); self } /// Specifies a timeout for the GenServer `init` function. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/process_receiver.rs
hydra/src/process_receiver.rs
use std::marker::PhantomData; use crate::Message; use crate::PROCESS; use crate::ProcessItem; use crate::ProcessMonitor; use crate::Receivable; use crate::SystemMessage; use crate::deserialize_value; /// Used to receive messages from processes. pub struct ProcessReceiver<T: Receivable> { ignore_type: bool, _message: PhantomData<T>, } impl<T> ProcessReceiver<T> where T: Receivable, { /// Constructs a new instance of [ProcessReceiver]. pub(crate) fn new() -> ProcessReceiver<T> { Self { ignore_type: true, _message: PhantomData, } } /// Enables strict type checking which will panic if the message type doesn't match. pub fn strict_type_checking(mut self) -> Self { self.ignore_type = false; self } /// Sets the message type this receiver will handle. pub fn for_message<N: Receivable>(self) -> ProcessReceiver<N> { ProcessReceiver::<N> { ignore_type: self.ignore_type, _message: PhantomData, } } /// Selects a single message. pub async fn select<F: (Fn(&Message<&T>) -> bool) + Send>(self, filter: F) -> Message<T> { let result = PROCESS.with(|process| { let mut items = process.items.borrow_mut(); let mut found: Option<usize> = None; for (index, item) in items.iter_mut().enumerate() { match process_item::<T>(item) { Ok(Some(message)) => { if filter(&message) { found = Some(index); break; } } Ok(None) => { continue; } Err(_) => { if self.ignore_type { continue; } else { panic!("Unsupported message type!") } } } } if let Some(found) = found { return Some(convert_item::<T>(items.remove(found))); } None }); if let Some(message) = result { return message; } let receiver = PROCESS.with(|process| process.receiver.clone()); loop { let mut item = receiver.recv_async().await.unwrap(); match process_item::<T>(&mut item) { Ok(Some(message)) => { if filter(&message) { return convert_item::<T>(item); } PROCESS.with(|process| process.items.borrow_mut().push(item)); } Ok(None) => { continue; } Err(_) => { if self.ignore_type { PROCESS.with(|process| process.items.borrow_mut().push(item)); continue; } else { panic!("Unsupported message type!") } } } } } /// Removes any message that is already in the message queue matching the filter. pub fn remove<F: (FnMut(&Message<&T>) -> bool) + Send>(self, mut filter: F) { PROCESS.with(|process| { let mut items = process.items.borrow_mut(); items.retain_mut(|item| match process_item::<T>(item) { Ok(Some(message)) => !filter(&message), Ok(None) => true, Err(_) => { if self.ignore_type { true } else { panic!("Unsupported message type!") } } }); }); let receiver = PROCESS.with(|process| process.receiver.clone()); for mut item in receiver.drain() { match process_item::<T>(&mut item) { Ok(Some(message)) => { if !filter(&message) { PROCESS.with(|process| process.items.borrow_mut().push(item)); } } Ok(None) => continue, Err(_) => { if self.ignore_type { PROCESS.with(|process| process.items.borrow_mut().push(item)); continue; } else { panic!("Unsupported message type!") } } } } } /// Receives a single message. pub async fn receive(self) -> Message<T> { self.select(|_| true).await } } /// Converts a processed item into a message. #[inline(always)] fn convert_item<T: Receivable>(item: ProcessItem) -> Message<T> { match item { // If we got here, the deserialization has already taken place. ProcessItem::UserRemoteMessage(_) => unreachable!(), ProcessItem::UserLocalMessage(deserialized) => { deserialized.downcast().map(|x| Message::User(*x)).unwrap() } ProcessItem::SystemMessage(system) => Message::System(system), // Handled during item processing. ProcessItem::MonitorProcessDown(_, _, _) => unreachable!(), ProcessItem::MonitorNodeDown(_, _) => unreachable!(), ProcessItem::MonitorProcessUpdate(_, _) => unreachable!(), ProcessItem::AliasDeactivated(_) => unreachable!(), } } /// Processes a process item, which could be a command, or a message, or anything. #[inline(always)] fn process_item<T: Receivable>(item: &mut ProcessItem) -> Result<Option<Message<&T>>, ()> { // Special case for serialized messages, we'll convert them to deserialized one time to prevent // deserializing the value more than once, then convert to a reference. if let ProcessItem::UserRemoteMessage(serialized) = item { let result: Result<T, _> = deserialize_value(serialized); if let Ok(result) = result { *item = ProcessItem::UserLocalMessage(Box::new(result)); } else { return Err(()); } } match item { // Explicitly handled first, so that we can process the other values later. ProcessItem::UserRemoteMessage(_) => unreachable!(), ProcessItem::UserLocalMessage(deserialized) => deserialized .downcast_ref() .map(Message::User) .ok_or(()) .map(Some), ProcessItem::SystemMessage(system) => Ok(Some(Message::System(system.clone()))), ProcessItem::MonitorProcessDown(dest, reference, exit_reason) => { if PROCESS.with(|process| process.monitors.borrow_mut().remove(reference).is_none()) { // If the process has already called demonitor, discard the message. // This prevents the need for a flush option. return Ok(None); } let system = SystemMessage::ProcessDown(dest.clone(), *reference, exit_reason.clone()); // Make sure processing only happens one time. *item = ProcessItem::SystemMessage(system.clone()); Ok(Some(Message::System(system))) } ProcessItem::MonitorNodeDown(node, reference) => { if PROCESS.with(|process| process.monitors.borrow_mut().remove(reference).is_none()) { // If the process has already called demonitor, discard the message. // This prevents the need for a flush option. return Ok(None); } let system = SystemMessage::NodeDown(node.clone(), *reference); // Make sure processing only happens one time. *item = ProcessItem::SystemMessage(system.clone()); Ok(Some(Message::System(system))) } ProcessItem::MonitorProcessUpdate(reference, pid) => { // Update the existing monitor reference so that if we go down before it fires, // We can gracefully clean up the remote monitor, this is only for named monitors. PROCESS.with(|process| { if let Some(monitor) = process.monitors.borrow_mut().get_mut(reference) { *monitor = ProcessMonitor::ForProcess(Some(*pid)); } }); Ok(None) } ProcessItem::AliasDeactivated(id) => { PROCESS.with(|process| process.aliases.borrow_mut().remove(id)); Ok(None) } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/link.rs
hydra/src/frame/link.rs
use bincode::Decode; use bincode::Encode; /// The frame used to install or destroy a process link. #[derive(Debug, Encode, Decode)] pub struct Link { pub install: bool, pub process_id: u64, pub from_id: u64, } impl Link { /// Constructs a new instance of [Link] frame. pub const fn new(install: bool, process_id: u64, from_id: u64) -> Self { Self { install, process_id, from_id, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/send.rs
hydra/src/frame/send.rs
use std::borrow::Cow; use std::num::NonZeroU64; use bincode::Decode; use bincode::Encode; use crate::Pid; use crate::Reference; /// The target process information for a send frame. #[derive(Debug, Encode, Decode)] pub enum SendTarget { Pid(NonZeroU64), Named(String), Alias(NonZeroU64), } /// The frame used to send a message to remote processes. #[derive(Debug, Encode, Decode)] pub struct Send { pub targets: Vec<SendTarget>, pub message: Vec<u8>, } impl Send { /// Constructs a new [Send] frame with the given message. pub fn with_message(message: Vec<u8>) -> Self { Self { targets: Vec::new(), message, } } /// Constructs a new [Send] frame with the given process id. pub fn with_pid(id: NonZeroU64, message: Vec<u8>) -> Self { Self { targets: vec![SendTarget::Pid(id)], message, } } /// Constructs a new [Send] frame with the given process name. pub fn with_name(name: String, message: Vec<u8>) -> Self { Self { targets: vec![SendTarget::Named(name)], message, } } /// Constructs a new [Send] frame with the given alias. pub fn with_alias(alias: NonZeroU64, message: Vec<u8>) -> Self { Self { targets: vec![SendTarget::Alias(alias)], message, } } } impl From<Pid> for SendTarget { fn from(value: Pid) -> Self { SendTarget::Pid(NonZeroU64::new(value.id()).unwrap()) } } impl From<String> for SendTarget { fn from(value: String) -> Self { Self::Named(value) } } impl<'a> From<Cow<'a, str>> for SendTarget { fn from(value: Cow<'a, str>) -> Self { Self::Named(String::from(value)) } } impl From<Reference> for SendTarget { fn from(value: Reference) -> Self { Self::Alias(NonZeroU64::new(value.id()).unwrap()) } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/monitor_update.rs
hydra/src/frame/monitor_update.rs
use bincode::Decode; use bincode::Encode; /// The frame used to update an installed process monitor. #[derive(Debug, Encode, Decode)] pub struct MonitorUpdate { pub process_id: u64, pub from_id: u64, pub reference_id: u64, } impl MonitorUpdate { /// Constructs a new instance of [MonitorUpdate] frame. pub const fn new(process_id: u64, from_id: u64, reference_id: u64) -> Self { Self { process_id, from_id, reference_id, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/ping.rs
hydra/src/frame/ping.rs
use bincode::Decode; use bincode::Encode; /// The frame used to keep the connection alive. #[derive(Debug, Encode, Decode)] pub struct Ping;
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/link_down.rs
hydra/src/frame/link_down.rs
use bincode::Decode; use bincode::Encode; use crate::ExitReason; /// The frame used to notify processes about down links. #[derive(Debug, Encode, Decode)] pub struct LinkDown { pub links: Vec<u64>, pub from_id: u64, pub exit_reason: ExitReason, } impl LinkDown { /// Constructs a new isntance of [LinkDown] frame. pub const fn new(from_id: u64, exit_reason: ExitReason) -> Self { Self { links: Vec::new(), from_id, exit_reason, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/hello.rs
hydra/src/frame/hello.rs
use std::net::SocketAddr; use sha2::Sha256; use hmac::Hmac; use hmac::Mac; use bincode::Decode; use bincode::Encode; use crate::node_get_cookie; /// Hmac using sha256. type HmacSha256 = Hmac<Sha256>; /// The frame used to handshake with other nodes. #[derive(Debug, Encode, Decode)] pub struct Hello { pub name: String, pub broadcast_address: SocketAddr, pub challenge: Vec<u8>, } impl Hello { /// Constructs a new instance of the [Hello] frame. pub fn new(name: String, broadcast_address: SocketAddr) -> Self { let mut challenge = { let cookie = node_get_cookie(); let cookie = cookie .as_ref() .map(|cookie| cookie.as_bytes()) .unwrap_or(&[0]); HmacSha256::new_from_slice(cookie).unwrap() }; challenge.update(name.as_bytes()); challenge.update(broadcast_address.to_string().as_bytes()); Self { name, broadcast_address, challenge: challenge.finalize().into_bytes().to_vec(), } } /// Validates this [Hello] frame against our cookie. pub fn validate(&mut self) -> bool { let mut challenge = { let cookie = node_get_cookie(); let cookie = cookie .as_ref() .map(|cookie| cookie.as_bytes()) .unwrap_or(&[0]); HmacSha256::new_from_slice(cookie).unwrap() }; challenge.update(self.name.as_bytes()); challenge.update(self.broadcast_address.to_string().as_bytes()); let wanted = challenge.finalize().into_bytes(); let challenge = std::mem::take(&mut self.challenge); wanted.as_slice() == challenge } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/mod.rs
hydra/src/frame/mod.rs
use std::io::Error; use std::io::ErrorKind; use bincode::Decode; use bincode::Encode; use bincode::config; use bincode::config::Configuration; use bincode::config::Fixint; use bincode::config::LittleEndian; use bincode::error::DecodeError; use bytes::Buf; use bytes::BufMut; use bytes::BytesMut; use tokio_util::codec::Decoder; use tokio_util::codec::Encoder; mod exit; mod hello; mod link; mod link_down; mod monitor; mod monitor_down; mod monitor_update; mod ping; mod pong; mod send; pub use exit::*; pub use hello::*; pub use link::*; pub use link_down::*; pub use monitor::*; pub use monitor_down::*; pub use monitor_update::*; pub use ping::*; pub use pong::*; pub use send::*; /// Bincode configuration for the frame codec. const FRAME_CONFIG: Configuration<LittleEndian, Fixint> = config::standard() .with_fixed_int_encoding() .with_little_endian(); /// The size of the marker. const MARKER_LENGTH: usize = std::mem::size_of::<u32>(); /// A frame value for the codec. #[derive(Debug, Encode, Decode)] pub enum Frame { Hello(Hello), Ping, Pong, Send(Send), Monitor(Monitor), MonitorDown(MonitorDown), MonitorUpdate(MonitorUpdate), Link(Link), LinkDown(LinkDown), Exit(Exit), } impl From<Hello> for Frame { fn from(value: Hello) -> Self { Self::Hello(value) } } impl From<Ping> for Frame { fn from(_: Ping) -> Self { Self::Ping } } impl From<Pong> for Frame { fn from(_: Pong) -> Self { Self::Pong } } impl From<Send> for Frame { fn from(value: Send) -> Self { Self::Send(value) } } impl From<Monitor> for Frame { fn from(value: Monitor) -> Self { Self::Monitor(value) } } impl From<MonitorDown> for Frame { fn from(value: MonitorDown) -> Self { Self::MonitorDown(value) } } impl From<MonitorUpdate> for Frame { fn from(value: MonitorUpdate) -> Self { Self::MonitorUpdate(value) } } impl From<Link> for Frame { fn from(value: Link) -> Self { Self::Link(value) } } impl From<LinkDown> for Frame { fn from(value: LinkDown) -> Self { Self::LinkDown(value) } } impl From<Exit> for Frame { fn from(value: Exit) -> Self { Self::Exit(value) } } /// The frame codec. #[derive(Default)] pub struct Codec; impl Codec { /// Constructs a new instance of [Codec] with default settings. pub const fn new() -> Self { Self } } impl Encoder<Frame> for Codec { type Error = Error; fn encode(&mut self, item: Frame, dst: &mut BytesMut) -> Result<(), Self::Error> { let marker = dst.len(); dst.put_u32_le(0); let size = bincode::encode_into_std_write(item, &mut dst.writer(), FRAME_CONFIG) .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?; dst[marker..marker + MARKER_LENGTH].copy_from_slice(&(size as u32).to_le_bytes()); Ok(()) } } impl Decoder for Codec { type Item = Frame; type Error = Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.len() < 4 { return Ok(None); } let mut length_marker = [0u8; MARKER_LENGTH]; length_marker.copy_from_slice(&src[0..MARKER_LENGTH]); let length = u32::from_le_bytes(length_marker) as usize; if src.len() < MARKER_LENGTH + length { src.reserve(MARKER_LENGTH + length - src.len()); return Ok(None); } let result = bincode::decode_from_slice(&src[4..], FRAME_CONFIG); match result { Ok((frame, _)) => { src.advance(MARKER_LENGTH + length); Ok(Some(frame)) } Err(DecodeError::UnexpectedEnd { additional }) => { src.reserve(additional); Ok(None) } Err(e) => Err(Error::new(ErrorKind::InvalidData, e)), } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/monitor.rs
hydra/src/frame/monitor.rs
use bincode::Decode; use bincode::Encode; /// The frame used to install or destroy a process monitor. #[derive(Debug, Encode, Decode)] pub struct Monitor { pub install: bool, pub process_id: Option<u64>, pub process_name: Option<String>, pub from_id: Option<u64>, pub reference_id: u64, } impl Monitor { /// Constructs a new instance of [Monitor] frame. pub const fn new( install: bool, process_id: Option<u64>, process_name: Option<String>, from_id: Option<u64>, reference_id: u64, ) -> Self { Self { install, process_id, process_name, from_id, reference_id, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/exit.rs
hydra/src/frame/exit.rs
use bincode::Decode; use bincode::Encode; use crate::ExitReason; /// The frame used to send an exit signal to a process. #[derive(Debug, Encode, Decode)] pub struct Exit { pub process_id: u64, pub from_id: u64, pub exit_reason: ExitReason, } impl Exit { /// Constructs a new instance of [Exit] frame. pub const fn new(process_id: u64, from_id: u64, exit_reason: ExitReason) -> Self { Self { process_id, from_id, exit_reason, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/monitor_down.rs
hydra/src/frame/monitor_down.rs
use bincode::Decode; use bincode::Encode; use crate::ExitReason; /// The frame used to notify processes about down monitors. #[derive(Debug, Encode, Decode)] pub struct MonitorDown { pub monitors: Vec<u64>, pub exit_reason: ExitReason, } impl MonitorDown { /// Constructs a new instance of [MonitorDown] frame. pub const fn new(exit_reason: ExitReason) -> Self { Self { monitors: Vec::new(), exit_reason, } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/src/frame/pong.rs
hydra/src/frame/pong.rs
use bincode::Decode; use bincode::Encode; /// The frame used to keep the connection alive. #[derive(Debug, Encode, Decode)] pub struct Pong;
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/tests/link.rs
hydra/tests/link.rs
use std::time::Duration; use hydra::Message; use hydra::Process; use hydra::ProcessFlags; use hydra::SystemMessage; #[hydra::test] async fn link_works() { let pid = Process::spawn(async { Process::spawn_link(async { panic!("we died!"); }); let _ = Process::receive::<()>().await; }); Process::sleep(Duration::from_millis(10)).await; assert!(!Process::alive(pid)); } #[hydra::test] async fn link_trap_exit_works() { Process::set_flags(ProcessFlags::TRAP_EXIT); let pid = Process::spawn_link(async { panic!("we died!"); }); let message: Message<()> = Process::receive().await; if let Message::System(SystemMessage::Exit(from, exit_reason)) = message { assert!(from == pid); assert!(exit_reason == "we died!"); } else { panic!("Expected exit signal!"); } } #[hydra::test] async fn unlink_works() { let pid = Process::spawn_link(async { Process::sleep(Duration::from_millis(10)).await; panic!("we died!"); }); Process::unlink(pid); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/tests/hash_ring.rs
hydra/tests/hash_ring.rs
use hydra::HashRing; #[test] fn hash_ring_works() { let ring: HashRing<u64> = HashRing::new(); ring.add_node(0, 0xDEADBEEF); ring.add_node(1, 0xDEADC0DE); let node1 = ring.find_node(0); let node2 = ring.find_node(1); let node3 = ring.find_node(1337); assert_eq!(node1.unwrap(), 0xDEADBEEF); assert_eq!(node2.unwrap(), 0xDEADC0DE); assert!([0xDEADBEEF, 0xDEADC0DE].contains(&node3.unwrap())); } #[test] fn hash_ring_set_nodes() { let ring: HashRing<u64> = HashRing::new(); ring.add_node(0, 0xDEADBEEF); ring.add_node(1, 0xDEADC0DE); ring.set_nodes([(0, 0xDEADC0DE), (1, 0xDEADBEEF)]); let node1 = ring.find_node(0); let node2 = ring.find_node(1); assert_eq!(node1.unwrap(), 0xDEADC0DE); assert_eq!(node2.unwrap(), 0xDEADBEEF); } #[test] fn hash_ring_clear() { let ring: HashRing<u64> = HashRing::new(); ring.add_node(0, 0xDEADBEEF); ring.add_node(1, 0xDEADC0DE); assert!(ring.find_node(0).is_some()); ring.clear(); assert!(ring.find_node(0).is_none()); } #[test] fn hash_ring_overrides() { let ring: HashRing<u64> = HashRing::new(); ring.add_node(0, 0xDEADBEEF); ring.add_node(1, 0xDEADC0DE); let node1 = ring.find_node(0); assert_eq!(node1.unwrap(), 0xDEADBEEF); ring.add_override(3, 0xC0DEBEEF); let node3 = ring.find_node(3); assert_eq!(node3.unwrap(), 0xC0DEBEEF); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/tests/monitor.rs
hydra/tests/monitor.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; use hydra::ExitReason; use hydra::Message; use hydra::Process; use hydra::SystemMessage; #[hydra::test] async fn monitor_works() { let pid = Process::spawn(async { Process::sleep(Duration::from_millis(50)).await; panic!("we're going down!"); }); let reference = Process::monitor(pid); let message: Message<()> = Process::receive().await; if let Message::System(SystemMessage::ProcessDown(object, mref, exit_reason)) = message { assert!(object == pid); assert!(reference == mref); assert!(matches!(exit_reason, ExitReason::Custom(_))); } else { panic!("Expected process down message!"); } } #[hydra::test] async fn monitor_named_works() { let pid = Process::spawn(async { Process::sleep(Duration::from_millis(50)).await; panic!("we're going down!"); }); Process::register(pid, "monitor_me").expect("Failed to register process!"); let reference = Process::monitor("monitor_me"); let message: Message<()> = Process::receive().await; if let Message::System(SystemMessage::ProcessDown(object, mref, exit_reason)) = message { assert!(object == "monitor_me"); assert!(reference == mref); assert!(matches!(exit_reason, ExitReason::Custom(_))); } else { panic!("Expected process down message!"); } } #[hydra::test] async fn monitor_noproc_works() { let pid = Process::spawn(async { // End immediately. }); Process::sleep(Duration::from_millis(10)).await; let reference1 = Process::monitor("no_exists"); let reference2 = Process::monitor(pid); let message1: Message<()> = Process::receive().await; let message2: Message<()> = Process::receive().await; if let Message::System(SystemMessage::ProcessDown(object, mref, exit_reason)) = message1 { assert!(object == "no_exists"); assert!(reference1 == mref); assert!(matches!(exit_reason, ExitReason::Custom(_))); } else { panic!("Expected process down message!"); } if let Message::System(SystemMessage::ProcessDown(object, mref, exit_reason)) = message2 { assert!(object == pid); assert!(reference2 == mref); assert!(matches!(exit_reason, ExitReason::Custom(_))); } else { panic!("Expected process down message!"); } } #[hydra::test] async fn demonitor_works() { let is_down: Arc<AtomicBool> = Arc::new(AtomicBool::new(false)); let is_down_ref = is_down.clone(); let (_, monitor) = Process::spawn_monitor(async move { Process::sleep(Duration::from_millis(50)).await; is_down_ref.store(true, Ordering::Relaxed); panic!("we're going down!"); }); Process::demonitor(monitor); Process::sleep(Duration::from_millis(75)).await; assert!(is_down.load(Ordering::Relaxed)); Process::send(Process::current(), ()); let message: Message<()> = Process::receive().await; assert!(matches!(message, Message::User(()))); } #[hydra::test] async fn spawn_monitor_works() { let (pid, reference) = Process::spawn_monitor(async { panic!("we're going down!"); }); let message: Message<()> = Process::receive().await; if let Message::System(SystemMessage::ProcessDown(object, mref, exit_reason)) = message { assert!(object == pid); assert!(reference == mref); assert!(matches!(exit_reason, ExitReason::Custom(_))); } else { panic!("Expected process down message!"); } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/examples/benchmark.rs
hydra/examples/benchmark.rs
use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; use hydra::Message; use hydra::Pid; use hydra::Process; static COUNTER: AtomicU64 = AtomicU64::new(0); #[hydra::main] async fn main() { let workers = std::thread::available_parallelism() .map(|cores| cores.get()) .unwrap_or(4); for _ in 0..workers { let pid1 = Process::spawn(async { loop { let Message::User(pid2) = Process::receive::<Pid>().await else { panic!() }; COUNTER.fetch_add(1, Ordering::Relaxed); Process::send(pid2, ()); } }); Process::spawn(async move { let pid2 = Process::current(); loop { Process::send(pid1, pid2); let _ = Process::receive::<()>().await; } }); } let start = Instant::now(); loop { Process::sleep(Duration::from_secs(1)).await; let elapsed = start.elapsed(); let count = COUNTER.load(Ordering::Relaxed); let ops = count / elapsed.as_secs().max(1); tracing::info!("Msg/s: {}", ops); } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/examples/application.rs
hydra/examples/application.rs
use hydra::Application; use hydra::ExitReason; use hydra::From; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use serde::Deserialize; use serde::Serialize; #[derive(Debug, Serialize, Deserialize)] enum StackMessage { Pop, PopResult(String), Push(String), } struct Stack { stack: Vec<String>, } impl Stack { pub fn with_entries(entries: Vec<&'static str>) -> Self { Self { stack: Vec::from_iter(entries.into_iter().map(Into::into)), } } } impl GenServer for Stack { type Message = StackMessage; async fn init(&mut self) -> Result<(), ExitReason> { Ok(()) } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { match message { StackMessage::Pop => Ok(Some(StackMessage::PopResult(self.stack.remove(0)))), _ => unreachable!(), } } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { match message { StackMessage::Push(value) => self.stack.insert(0, value), _ => unreachable!(), } Ok(()) } } struct StackApplication; impl Application for StackApplication { // Here, we must link a process for the application to monitor, usually, a Supervisor, but it can be any process. async fn start(&self) -> Result<Pid, ExitReason> { let pid = Stack::with_entries(vec!["hello", "world"]) .start_link(GenServerOptions::new()) .await .expect("Failed to start stack!"); let result = Stack::call(pid, StackMessage::Pop, None) .await .expect("Stack call failed!"); tracing::info!("{:?}", result); Stack::cast(pid, StackMessage::Push(String::from("rust"))); let result = Stack::call(pid, StackMessage::Pop, None) .await .expect("Stack call failed!"); tracing::info!("{:?}", result); // Otherwise, the application will run forever waiting for Stack to terminate. Stack::stop(pid, ExitReason::Normal, None).await?; Ok(pid) } } fn main() { // This method will return once the linked Process in StackApplication::start has terminated. Application::run(StackApplication) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/examples/registry.rs
hydra/examples/registry.rs
use std::time::Duration; use serde::Deserialize; use serde::Serialize; use hydra::Application; use hydra::ChildSpec; use hydra::ExitReason; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use hydra::Process; use hydra::ProcessFlags; use hydra::Registry; use hydra::RegistryKey; use hydra::RegistryOptions; use hydra::Shutdown; use hydra::SupervisionStrategy; use hydra::Supervisor; use hydra::SupervisorOptions; async fn test_registry() { Registry::start_process("space-registry", "my awesome space id", None) .await .expect("Failed to start process"); Registry::start_process("space-registry", "my lame space id", None) .await .expect("Failed to start process"); let pid = Registry::lookup("space-registry", "my awesome space id", None) .await .expect("Failed to lookup process"); tracing::info!("Looked up space process: {:?}", pid); let count = Registry::count("space-registry", None) .await .expect("Failed to count processes"); tracing::info!("Count of registered processes: {:?}", count); let list = Registry::list("space-registry", None) .await .expect("Failed to list processes"); tracing::info!("List of registered processes: {:?}", list); } #[derive(Debug, Serialize, Deserialize)] enum MyMessage { // No messages used. } struct MyApplication; impl Application for MyApplication { async fn start(&self) -> Result<Pid, ExitReason> { // Spawn a registry that will take care of registering 'MySpace'. let children = [ Registry::new("space-registry") .with_start(|key| { let RegistryKey::String(id) = key else { panic!() }; MySpace::new(id).start_link(GenServerOptions::new()) }) .with_shutdown(Shutdown::Infinity) .child_spec(RegistryOptions::new()) .id("space-registry"), ChildSpec::new("test-registry") .start(move || async { Ok(Process::spawn(test_registry())) }), ]; // Restart only the terminated child. Supervisor::with_children(children) .strategy(SupervisionStrategy::OneForOne) .start_link(SupervisorOptions::new()) .await } } #[derive(Clone)] struct MySpace { id: String, } impl MySpace { /// Constructs a new [MySpace]. pub fn new(id: String) -> Self { Self { id } } } impl GenServer for MySpace { type Message = MyMessage; async fn init(&mut self) -> Result<(), ExitReason> { Process::set_flags(ProcessFlags::TRAP_EXIT); tracing::info!("Init MySpace for {:?}", self.id); Ok(()) } async fn terminate(&mut self, _reason: ExitReason) { tracing::info!("Shutting down MySpace! {:?}", self.id); Process::sleep(Duration::from_secs(5)).await; } } fn main() { // This method will only return once the supervisor linked in `start` has terminated. Application::run(MyApplication) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/examples/stack.rs
hydra/examples/stack.rs
use hydra::ExitReason; use hydra::From; use hydra::GenServer; use hydra::GenServerOptions; use serde::Deserialize; use serde::Serialize; #[derive(Debug, Serialize, Deserialize)] enum StackMessage { Pop, PopResult(String), Push(String), } struct Stack { stack: Vec<String>, } impl Stack { pub fn with_entries(entries: Vec<&'static str>) -> Self { Self { stack: Vec::from_iter(entries.into_iter().map(Into::into)), } } } impl GenServer for Stack { type Message = StackMessage; async fn init(&mut self) -> Result<(), ExitReason> { Ok(()) } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { match message { StackMessage::Pop => Ok(Some(StackMessage::PopResult(self.stack.remove(0)))), _ => unreachable!(), } } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { match message { StackMessage::Push(value) => self.stack.insert(0, value), _ => unreachable!(), } Ok(()) } } #[hydra::main] async fn main() { let pid = Stack::with_entries(vec!["hello", "world"]) .start_link(GenServerOptions::new()) .await .expect("Failed to start stack!"); let result = Stack::call(pid, StackMessage::Pop, None) .await .expect("Stack call failed!"); tracing::info!("{:?}", result); Stack::cast(pid, StackMessage::Push(String::from("rust"))); let result = Stack::call(pid, StackMessage::Pop, None) .await .expect("Stack call failed!"); tracing::info!("{:?}", result); }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra/examples/supervisor.rs
hydra/examples/supervisor.rs
use std::time::Duration; use serde::Deserialize; use serde::Serialize; use hydra::Application; use hydra::CallError; use hydra::ChildSpec; use hydra::Dest; use hydra::ExitReason; use hydra::From; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use hydra::Process; use hydra::SupervisionStrategy; use hydra::Supervisor; use hydra::SupervisorOptions; #[derive(Debug, Serialize, Deserialize)] enum MyMessage { Hello(String), HelloResponse(String), Crash, } struct MyApplication; impl Application for MyApplication { async fn start(&self) -> Result<Pid, ExitReason> { // Spawn two instances of `MyServer` with their own unique ids. let children = [ MyServer::new().child_spec().id("server1"), MyServer::new().child_spec().id("server2"), ]; // Restart only the terminated child. Supervisor::with_children(children) .strategy(SupervisionStrategy::OneForOne) .start_link(SupervisorOptions::new()) .await } } #[derive(Clone)] struct MyServer; impl MyServer { /// Constructs a new [MyServer]. pub fn new() -> Self { Self } /// A wrapper around the GenServer call "Hello". pub async fn hello<T: Into<Dest>>(server: T, string: &str) -> Result<String, CallError> { use MyMessage::*; match MyServer::call(server, Hello(string.to_owned()), None).await? { HelloResponse(response) => Ok(response), _ => unreachable!(), } } /// Builds the child specification for [MyServer]. pub fn child_spec(self) -> ChildSpec { ChildSpec::new("MyServer") .start(move || MyServer::start_link(MyServer, GenServerOptions::new())) } } impl GenServer for MyServer { type Message = MyMessage; async fn init(&mut self) -> Result<(), ExitReason> { let server = Process::current(); Process::spawn(async move { // Ask for a formatted string. let hello_world = MyServer::hello(server, "hello") .await .expect("Failed to call server!"); tracing::info!("Got: {:?}", hello_world); // Wait before crashing. Process::sleep(Duration::from_secs(1)).await; // Crash the process so the supervisor restarts it. MyServer::cast(server, MyMessage::Crash); }); Ok(()) } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { use MyMessage::*; match message { Hello(string) => Ok(Some(HelloResponse(format!("{} world!", string)))), _ => unreachable!(), } } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { use MyMessage::*; match message { Crash => { panic!("Whoops! We crashed!"); } _ => unreachable!(), } } } fn main() { // This method will only return once the supervisor linked in `start` has terminated. Application::run(MyApplication) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/src/lib.rs
hydra-websockets/src/lib.rs
mod websocket_command; mod websocket_handler; mod websocket_server; mod websocket_server_config; pub use websocket_command::*; pub use websocket_handler::*; pub use websocket_server::*; pub use websocket_server_config::*; use tokio_tungstenite::tungstenite; // Re-export for WebSocketHandler::accept. pub use tungstenite::Message as WebsocketMessage; pub use tungstenite::handshake::server::Request as WebsocketRequest; pub use tungstenite::handshake::server::Response as WebsocketResponse; pub use tungstenite::protocol::frame::coding::CloseCode;
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/src/websocket_handler.rs
hydra-websockets/src/websocket_handler.rs
use std::future::Future; use std::net::SocketAddr; use futures_util::SinkExt; use futures_util::StreamExt; use futures_util::stream; use tokio::io::AsyncRead; use tokio::io::AsyncWrite; use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::tungstenite::Error; use tokio_tungstenite::tungstenite::protocol::CloseFrame; use hydra::ExitReason; use hydra::Message; use hydra::Process; use hydra::Receivable; use crate::WebsocketCommand; use crate::WebsocketCommands; use crate::WebsocketMessage; use crate::WebsocketRequest; use crate::WebsocketResponse; /// A process that handles websocket messages. pub trait WebsocketHandler where Self: Sized, { /// The message type that this handler will use. type Message: Receivable; /// A callback used to accept or deny a request for a websocket upgrade. /// /// You can extract information from the request and put it in your handler state. fn accept( address: SocketAddr, request: &WebsocketRequest, response: WebsocketResponse, ) -> Result<(WebsocketResponse, Self), ExitReason>; /// An optional callback that happens before the first message is sent/received from the websocket. /// /// This is the first callback that happens in the process responsible for the websocket. fn websocket_init( &mut self, ) -> impl Future<Output = Result<Option<WebsocketCommands>, ExitReason>> + Send { async move { Ok(None) } } /// Invoked to handle messages received from the websocket. fn websocket_handle( &mut self, message: WebsocketMessage, ) -> impl Future<Output = Result<Option<WebsocketCommands>, ExitReason>> + Send; /// Invoked to handle messages from processes and system messages. fn websocket_info( &mut self, info: Message<Self::Message>, ) -> impl Future<Output = Result<Option<WebsocketCommands>, ExitReason>> + Send { async move { let _ = info; Ok(None) } } /// Invoked when the handler is about to exit. It should do any cleanup required. /// /// `terminate` is useful for cleanup that requires access to the [WebsocketHandler]'s state. However, it is not /// guaranteed that `terminate` is called when a [WebsocketHandler] exits. Therefore, important cleanup should be done /// using process links and/or monitors. A monitoring process will receive the same `reason` that would be passed to `terminate`. /// /// `terminate` is called if: /// - The websocket connection closes for whatever reason. /// - A callback (except `accept`) returns stop with a given reason. fn terminate(&mut self, reason: ExitReason) -> impl Future<Output = ()> + Send { async move { let _ = reason; } } } /// Internal routine to process commands from a [WebsocketHandler] callback. async fn websocket_process_commands<T, S>( commands: WebsocketCommands, handler: &mut T, stream: &mut WebSocketStream<S>, ) where T: WebsocketHandler + Send + 'static, S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { let mut close_command: Option<WebsocketCommand> = None; let sends = commands.buffer.into_iter().filter_map(|command| { if close_command.is_some() { return None; } match command { WebsocketCommand::Send(message) => Some(Ok(message)), WebsocketCommand::Close(_, _) => { close_command = Some(command); None } } }); let mut sends = stream::iter(sends); if let Err(error) = stream.send_all(&mut sends).await { handler.terminate(error_to_reason(&error)).await; Process::exit(Process::current(), error_to_reason(&error)) } if let Some(WebsocketCommand::Close(code, reason)) = close_command { if let Err(error) = stream .close(Some(CloseFrame { code, reason: reason.into(), })) .await { handler.terminate(error_to_reason(&error)).await; Process::exit(Process::current(), error_to_reason(&error)); } else { Process::exit(Process::current(), ExitReason::Normal); } } } /// Internal [WebsocketHandler] start routine. pub(crate) async fn start_websocket_handler<T, S>(mut handler: T, mut stream: WebSocketStream<S>) where T: WebsocketHandler + Send + 'static, S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { match handler.websocket_init().await { Ok(commands) => { if let Some(commands) = commands { websocket_process_commands(commands, &mut handler, &mut stream).await; } } Err(reason) => { return Process::exit(Process::current(), reason); } } loop { tokio::select! { message = Process::receive::<T::Message>() => { match handler.websocket_info(message).await { Ok(commands) => { if let Some(commands) = commands { websocket_process_commands(commands, &mut handler, &mut stream).await; } } Err(reason) => { handler.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } } ws_message = stream.next() => { let Some(ws_message) = ws_message else { panic!("Websocket closed without close frame!"); }; match ws_message { Ok(message) => { let mut should_close = false; match &message { WebsocketMessage::Ping(data) => { if let Err(error) = stream.send(WebsocketMessage::Pong(data.clone())).await { handler.terminate(error_to_reason(&error)).await; return Process::exit(Process::current(), error_to_reason(&error)); } } WebsocketMessage::Close(_) => { should_close = true; } _ => { // No special handling. } } match handler.websocket_handle(message).await { Ok(commands) => { if let Some(commands) = commands { websocket_process_commands(commands, &mut handler, &mut stream).await; } } Err(reason) => { handler.terminate(reason.clone()).await; return Process::exit(Process::current(), reason); } } if should_close { handler.terminate(ExitReason::from("connection_closed")).await; return Process::exit(Process::current(), ExitReason::from("connection_closed")); } } Err(error) => { handler.terminate(error_to_reason(&error)).await; return Process::exit(Process::current(), error_to_reason(&error)); } } } } } } /// Converts a websocket error to an exit reason. fn error_to_reason(error: &Error) -> ExitReason { match error { Error::AlreadyClosed | Error::ConnectionClosed => ExitReason::from("connection_closed"), Error::Io(_) => ExitReason::from("io_error"), Error::Tls(_) => ExitReason::from("tls_error"), Error::Utf8(_) => ExitReason::from("utf8_error"), Error::AttackAttempt => ExitReason::from("attack_attempt"), _ => ExitReason::from("unknown"), } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/src/websocket_server.rs
hydra-websockets/src/websocket_server.rs
use std::io::ErrorKind; use std::marker::PhantomData; use std::net::SocketAddr; #[cfg(feature = "native-tls")] use std::sync::Arc; use tokio::io::AsyncRead; use tokio::io::AsyncWrite; use tokio::net::TcpListener; use tokio_tungstenite::accept_hdr_async_with_config; use tokio_tungstenite::tungstenite; use tungstenite::handshake::server::ErrorResponse; use tungstenite::protocol::WebSocketConfig; #[cfg(feature = "native-tls")] use tokio_native_tls::TlsAcceptor; use hydra::ChildSpec; use hydra::ExitReason; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use hydra::Process; use hydra::ProcessFlags; use crate::WebsocketRequest; use crate::WebsocketResponse; use crate::WebsocketHandler; use crate::WebsocketServerConfig; use crate::start_websocket_handler; /// A [Process] that listens for websocket connections and spawns [WebsocketHandler]'s to read/write to them. pub struct WebsocketServer<T: WebsocketHandler + Send + 'static> { config: WebsocketServerConfig, server: Option<Pid>, _handler: PhantomData<T>, } impl<T> WebsocketServer<T> where T: WebsocketHandler + Send + 'static, { /// Constructs a new instance of [WebsocketServer] with the given `config`. pub fn new(config: WebsocketServerConfig) -> Self { WebsocketServer { config, server: None, _handler: PhantomData, } } } impl<T> WebsocketServer<T> where T: WebsocketHandler + Send + Sync + 'static, { pub fn child_spec(self) -> ChildSpec { ChildSpec::new("WebsocketServer").start(move || { WebsocketServer::start_link( WebsocketServer { config: self.config.clone(), server: None, _handler: PhantomData::<T>, }, GenServerOptions::new(), ) }) } } impl<T> GenServer for WebsocketServer<T> where T: WebsocketHandler + Send + 'static, { type Message = (); async fn init(&mut self) -> Result<(), ExitReason> { Process::set_flags(ProcessFlags::TRAP_EXIT); let server = match TcpListener::bind(self.config.address).await { Ok(server) => server, Err(error) => { let reason = match error.kind() { ErrorKind::AddrInUse => "address_in_use", ErrorKind::AddrNotAvailable => "address_not_available", ErrorKind::WouldBlock => "would_block", _ => "unknown", }; return Err(ExitReason::from(reason)); } }; self.server = Some(Process::spawn_link(server_process::<T>( server, self.config.clone(), ))); Ok(()) } async fn terminate(&mut self, _reason: ExitReason) { if let Some(server) = self.server.take() { Process::exit(server, ExitReason::Kill); } } } /// Internal [WebsocketServer] accept routine. async fn server_accept<T, S>(stream: S, address: SocketAddr, config: WebsocketServerConfig) where T: WebsocketHandler + Send + 'static, S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { let mut handler: Option<T> = None; let callback = |request: &WebsocketRequest, response: WebsocketResponse| match T::accept( address, request, response, ) { Ok((response, rhandler)) => { handler = Some(rhandler); Ok(response) } Err(reason) => Err(ErrorResponse::new(Some(format!("{:?}", reason)))), }; let ws_config = WebSocketConfig::default() .max_message_size(config.max_message_size) .max_frame_size(config.max_frame_size); let accept = match config.handshake_timeout { Some(timeout) => { Process::timeout( timeout, accept_hdr_async_with_config(stream, callback, Some(ws_config)), ) .await } None => Ok(accept_hdr_async_with_config(stream, callback, Some(ws_config)).await), }; let stream = match accept { Ok(Ok(stream)) => stream, Ok(Err(error)) => { #[cfg(feature = "tracing")] tracing::error!(error = ?error, address = ?address, "Failed to accept websocket"); #[cfg(not(feature = "tracing"))] { let _ = error; let _ = address; } return; } Err(_) => { #[cfg(feature = "tracing")] tracing::error!(timeout = ?config.handshake_timeout, address = ?address, "Websocket accept timeout"); return; } }; let handler = handler .take() .expect("Must have a handler after accepting!"); #[cfg(feature = "tracing")] tracing::trace!(address = ?address, "Accepted websocket connection"); Process::spawn(start_websocket_handler(handler, stream)); } /// Internal [WebsocketHandler] tls routine. #[cfg(feature = "native-tls")] async fn server_accept_tls<T, S>( tls: Arc<TlsAcceptor>, stream: S, address: SocketAddr, mut config: WebsocketServerConfig, ) where T: WebsocketHandler + Send + 'static, S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { let started = std::time::Instant::now(); let accept = match config.handshake_timeout { Some(timeout) => Process::timeout(timeout, tls.accept(stream)).await, None => Ok(tls.accept(stream).await), }; if let Some(timeout) = config.handshake_timeout.as_mut() { *timeout -= started.elapsed().min(*timeout) } match accept { Ok(Ok(stream)) => server_accept::<T, _>(stream, address, config).await, Ok(Err(error)) => { #[cfg(feature = "tracing")] tracing::error!(error = ?error, address = ?address, "Failed to accept tls connection"); #[cfg(not(feature = "tracing"))] let _ = error; } Err(_) => { #[cfg(feature = "tracing")] tracing::error!(timeout = ?config.handshake_timeout, address = ?address, "Websocket accept tls timeout"); } }; } /// Internal [WebsocketServer] process routine. async fn server_process<T>(server: TcpListener, config: WebsocketServerConfig) where T: WebsocketHandler + Send + 'static, { #[cfg(feature = "native-tls")] let tls = { use std::sync::Arc; use tokio_native_tls::TlsAcceptor; use tokio_native_tls::native_tls::Identity; use tokio_native_tls::native_tls::TlsAcceptor as NTlsAcceptor; let identity = if let (Some(der), Some(password)) = (&config.tls_pkcs12_der, &config.tls_pkcs12_password) { Identity::from_pkcs12(der, password.as_str()) .expect("Failed to parse pkcs12 certificate!") } else if let (Some(pem), Some(key)) = (&config.tls_pkcs8_pem, &config.tls_pkcs8_key) { Identity::from_pkcs8(pem, key).expect("Failed to parse pkcs8 certificate!") } else { panic!("Feature 'native-tls' enabled without providing a tls certificate!"); }; let tls = NTlsAcceptor::new(identity).expect("Failed to load identity!"); Arc::new(TlsAcceptor::from(tls)) }; #[cfg(feature = "tracing")] tracing::info!(address = ?config.address, "Websocket server accepting connections"); loop { match server.accept().await { Ok((stream, address)) => { #[cfg(feature = "tracing")] tracing::trace!(address = ?address, "Accepted socket connection"); #[cfg(feature = "native-tls")] Process::spawn(server_accept_tls::<T, _>( tls.clone(), stream, address, config.clone(), )); #[cfg(not(feature = "native-tls"))] Process::spawn(server_accept::<T, _>(stream, address, config.clone())); } Err(error) => { #[cfg(feature = "tracing")] tracing::error!(error = ?error, "Failed to accept connection"); #[cfg(not(feature = "tracing"))] let _ = error; } } } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/src/websocket_command.rs
hydra-websockets/src/websocket_command.rs
use smallvec::SmallVec; use crate::CloseCode; use crate::WebsocketMessage; /// Internal websocket command representation. pub(crate) enum WebsocketCommand { Send(WebsocketMessage), Close(CloseCode, String), } /// A command buffer returned from a websocket callback. pub struct WebsocketCommands { pub(crate) buffer: SmallVec<[WebsocketCommand; 6]>, } impl WebsocketCommands { /// Constructs a new websocket command buffer. pub fn new() -> Self { Self { buffer: SmallVec::new(), } } /// Constructs a new websocket command buffer to send `message`. pub fn with_send<T: Into<WebsocketMessage>>(message: T) -> Self { let mut result = Self::new(); result.send(message); result } /// Constructs a new websocket command buffer to close the websocket gracefully. pub fn with_close<T: Into<String>>(code: CloseCode, reason: T) -> Self { let mut result = Self::new(); result.close(code, reason); result } /// Sends the message to the websocket client. pub fn send<T: Into<WebsocketMessage>>(&mut self, message: T) { self.buffer.push(WebsocketCommand::Send(message.into())); } /// Gracefully close the websocket with the given `code` and `reason`. pub fn close<T: Into<String>>(&mut self, code: CloseCode, reason: T) { self.buffer .push(WebsocketCommand::Close(code, reason.into())); } } impl Default for WebsocketCommands { fn default() -> Self { Self::new() } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/src/websocket_server_config.rs
hydra-websockets/src/websocket_server_config.rs
use std::net::SocketAddr; use std::time::Duration; /// A set of configuration options for the websocket server. #[derive(Debug, Clone)] pub struct WebsocketServerConfig { pub(crate) address: SocketAddr, pub(crate) handshake_timeout: Option<Duration>, pub(crate) max_message_size: Option<usize>, pub(crate) max_frame_size: Option<usize>, #[cfg(feature = "native-tls")] pub(crate) tls_pkcs12_der: Option<Vec<u8>>, #[cfg(feature = "native-tls")] pub(crate) tls_pkcs12_password: Option<String>, #[cfg(feature = "native-tls")] pub(crate) tls_pkcs8_pem: Option<Vec<u8>>, #[cfg(feature = "native-tls")] pub(crate) tls_pkcs8_key: Option<Vec<u8>>, } impl WebsocketServerConfig { /// Constructs a new [WebsocketServerConfig] with the given address to listen on. pub fn new(address: SocketAddr) -> Self { use tokio_tungstenite::tungstenite; use tungstenite::protocol::*; let defaults = WebSocketConfig::default(); Self { address, handshake_timeout: None, max_message_size: defaults.max_message_size, max_frame_size: defaults.max_frame_size, #[cfg(feature = "native-tls")] tls_pkcs12_der: None, #[cfg(feature = "native-tls")] tls_pkcs12_password: None, #[cfg(feature = "native-tls")] tls_pkcs8_pem: None, #[cfg(feature = "native-tls")] tls_pkcs8_key: None, } } /// Sets the timeout for websocket handshakes. /// /// When tls is enabled, this time includes the tls handshake as well. pub const fn handshake_timeout(mut self, timeout: Duration) -> Self { self.handshake_timeout = Some(timeout); self } /// Sets the maximum size of an incoming message. `None` means no size limit. The default value is 64 MiB /// which should be reasonably big for all normal use-cases but small enough to prevent /// memory eating by a malicious user. pub const fn max_message_size(mut self, size: Option<usize>) -> Self { self.max_message_size = size; self } /// Sets the maximum size of a single incoming message frame. `None` means no size limit. The limit is for /// frame payload NOT including the frame header. The default value is 16 MiB which should /// be reasonably big for all normal use-cases but small enough to prevent memory eating /// by a malicious user. pub const fn max_frame_size(mut self, size: Option<usize>) -> Self { self.max_frame_size = size; self } /// Loads a DER-formatted PKCS #12 archive, using the specified `password` to decrypt the key. /// /// The archive should contain a leaf certificate and its private key, /// as well any intermediate certificates that should be sent to clients to allow them to build a chain to a trusted root. /// The chain certificates should be in order from the leaf certificate towards the root. /// /// PKCS #12 archives typically have the file extension .p12 or .pfx, and can be created with the OpenSSL pkcs12 tool: /// ```ignore /// openssl pkcs12 -export -out identity.pfx -inkey key.pem -in cert.pem -certfile chain_certs.pem /// ``` #[cfg(feature = "native-tls")] pub fn tls_pkcs12<D: Into<Vec<u8>>, S: Into<String>>(mut self, der: D, password: S) -> Self { self.tls_pkcs12_der = Some(der.into()); self.tls_pkcs12_password = Some(password.into()); self } /// Loads a chain of PEM encoded X509 certificates, with the leaf certificate first. /// `key` is a PEM encoded PKCS #8 formatted private key for the leaf certificate. /// /// The certificate chain should contain any intermediate cerficates that should be sent to clients to allow them to build a chain to a trusted root. /// /// A certificate chain here means a series of PEM encoded certificates concatenated together. #[cfg(feature = "native-tls")] pub fn tls_pkcs8<P: Into<Vec<u8>>, K: Into<Vec<u8>>>(mut self, pem: P, key: K) -> Self { self.tls_pkcs8_pem = Some(pem.into()); self.tls_pkcs8_key = Some(key.into()); self } }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-websockets/examples/server.rs
hydra-websockets/examples/server.rs
use std::net::SocketAddr; use hydra::Application; use hydra::ExitReason; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use hydra::Process; use hydra_websockets::WebsocketCommands; use hydra_websockets::WebsocketHandler; use hydra_websockets::WebsocketMessage; use hydra_websockets::WebsocketRequest; use hydra_websockets::WebsocketResponse; use hydra_websockets::WebsocketServer; use hydra_websockets::WebsocketServerConfig; struct MyWebsocketHandler; impl WebsocketHandler for MyWebsocketHandler { type Message = (); fn accept( _address: SocketAddr, _request: &WebsocketRequest, response: WebsocketResponse, ) -> Result<(WebsocketResponse, Self), ExitReason> { // You can extract any header information from `request` and pass it to the handler. Ok((response, MyWebsocketHandler)) } async fn websocket_handle( &mut self, message: WebsocketMessage, ) -> Result<Option<WebsocketCommands>, ExitReason> { match message { WebsocketMessage::Text(text) => { tracing::info!(handler = ?Process::current(), message = ?text.as_str(), "Got message"); // Echo the command back to the client. Ok(Some(WebsocketCommands::with_send(text.as_str()))) } _ => { // Hydra websockets automatically responds to ping requests. Ok(None) } } } } struct MyWebsocketApplication; impl Application for MyWebsocketApplication { async fn start(&self) -> Result<Pid, ExitReason> { let address: SocketAddr = "127.0.0.1:1337".parse().unwrap(); let config = WebsocketServerConfig::new(address); WebsocketServer::<MyWebsocketHandler>::new(config) .start_link(GenServerOptions::new()) .await } } fn main() { Application::run(MyWebsocketApplication) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-test/src/main.rs
hydra-test/src/main.rs
use std::time::Duration; use serde::Deserialize; use serde::Serialize; use hydra::Application; use hydra::CallError; use hydra::ChildSpec; use hydra::Dest; use hydra::ExitReason; use hydra::From; use hydra::GenServer; use hydra::GenServerOptions; use hydra::Pid; use hydra::Process; use hydra::SupervisionStrategy; use hydra::Supervisor; use hydra::SupervisorOptions; #[derive(Debug, Serialize, Deserialize)] enum MyMessage { Hello(String), HelloResponse(String), Crash, } struct MyApplication; impl Application for MyApplication { async fn start(&self) -> Result<Pid, ExitReason> { // Spawn two instances of `MyServer` with their own unique ids. let children = [ MyServer::new().child_spec().id("server1"), MyServer::new().child_spec().id("server2"), ]; // Restart only the terminated child. Supervisor::with_children(children) .strategy(SupervisionStrategy::OneForOne) .start_link(SupervisorOptions::new()) .await } } #[derive(Clone)] struct MyServer; impl MyServer { /// Constructs a new [MyServer]. pub fn new() -> Self { Self } /// A wrapper around the GenServer call "Hello". pub async fn hello<T: Into<Dest>>(server: T, string: &str) -> Result<String, CallError> { use MyMessage::*; match MyServer::call(server, Hello(string.to_owned()), None).await? { HelloResponse(response) => Ok(response), _ => unreachable!(), } } /// Builds the child specification for [MyServer]. pub fn child_spec(self) -> ChildSpec { ChildSpec::new("MyServer") .start(move || MyServer::start_link(MyServer, GenServerOptions::new())) } } impl GenServer for MyServer { type Message = MyMessage; async fn init(&mut self) -> Result<(), ExitReason> { let server = Process::current(); Process::spawn(async move { // Ask for a formatted string. let hello_world = MyServer::hello(server, "hello") .await .expect("Failed to call server!"); tracing::info!("Got: {:?}", hello_world); // Wait before crashing. Process::sleep(Duration::from_secs(1)).await; // Crash the process so the supervisor restarts it. MyServer::cast(server, MyMessage::Crash); }); Ok(()) } async fn handle_call( &mut self, message: Self::Message, _from: From, ) -> Result<Option<Self::Message>, ExitReason> { use MyMessage::*; match message { Hello(string) => Ok(Some(HelloResponse(format!("{} world!", string)))), _ => unreachable!(), } } async fn handle_cast(&mut self, message: Self::Message) -> Result<(), ExitReason> { use MyMessage::*; match message { Crash => { panic!("Whoops! We crashed!"); } _ => unreachable!(), } } } fn main() { // This method will only return once the supervisor linked in `start` has terminated. Application::run(MyApplication) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-macros/src/lib.rs
hydra-macros/src/lib.rs
use proc_macro::TokenStream; mod entry; /// Marks an async function to be executed as a hydra application. /// /// Note: This macro is designed to be simplistic, if you wish to customize your application, you should /// implement the trait yourself and call `run` instead. /// /// If the feature `tracing` is enabled, this will automatically setup a subscriber and panic hook. #[proc_macro_attribute] pub fn main(arg: TokenStream, item: TokenStream) -> TokenStream { entry::main(arg, item) } /// Marks an async function to be executed as a hydra application suitable for the test environment. #[proc_macro_attribute] pub fn test(arg: TokenStream, item: TokenStream) -> TokenStream { entry::test(arg, item) }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
dtzxporter/hydra
https://github.com/dtzxporter/hydra/blob/37c630fc77316049a186907d87dfc47109777433/hydra-macros/src/entry.rs
hydra-macros/src/entry.rs
use proc_macro::TokenStream; use quote::format_ident; use quote::quote; use syn::ItemFn; use syn::parse_macro_input; pub(crate) fn main(_: TokenStream, item: TokenStream) -> TokenStream { let input_fn = parse_macro_input!(item as ItemFn); let input_name = &input_fn.sig.ident; let input_block = &input_fn.block; let input_struct = format_ident!("{}_MainStruct", input_name); let output = quote! { #[allow(non_camel_case_types)] struct #input_struct; impl ::hydra::Application for #input_struct { async fn start(&self) -> Result<::hydra::Pid, ::hydra::ExitReason> { Ok(::hydra::Process::spawn_link(async move { #input_block })) } } fn #input_name() { use ::hydra::Application; let main = #input_struct; main.run(); } }; output.into() } pub(crate) fn test(_: TokenStream, item: TokenStream) -> TokenStream { let input_fn = parse_macro_input!(item as ItemFn); let input_name = &input_fn.sig.ident; let input_block = &input_fn.block; let input_struct = format_ident!("{}_TestStruct", input_name); let output = quote! { #[allow(non_camel_case_types)] struct #input_struct; impl ::hydra::Application for #input_struct { async fn start(&self) -> Result<::hydra::Pid, ::hydra::ExitReason> { Ok(::hydra::Process::spawn_link(async move { #input_block })) } } #[test] fn #input_name() { use ::hydra::Application; let test = #input_struct; test.test(); } }; output.into() }
rust
MIT
37c630fc77316049a186907d87dfc47109777433
2026-01-04T20:19:03.102117Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/rust_gpu_material.rs
src/rust_gpu_material.rs
//! Trait use crate::prelude::EntryPoint; /// A [`Material`] type with statically-known `rust-gpu` vertex and fragment entry points. pub trait RustGpuMaterial { type Vertex: EntryPoint; type Fragment: EntryPoint; }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/prelude.rs
src/prelude.rs
pub use crate::{builder_output::*, entry_point::*, plugin::*, rust_gpu::*, rust_gpu_material::*, *}; #[cfg(feature = "hot-rebuild")] pub use crate::entry_point_export::*;
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/bevy_pbr_rust.rs
src/bevy_pbr_rust.rs
//! `bevy-pbr-rust`-backed `RustGpuMaterial` implementation for `StandardMaterial`. use bevy::{prelude::StandardMaterial, render::render_resource::ShaderDefVal}; use crate::{ prelude::{EntryPoint, EntryPointName, EntryPointParameters, RustGpuMaterial}, EntryPointConstants, }; /// `bevy_rust_gpu::mesh::entry_points::vertex` pub enum MeshVertex {} impl EntryPoint for MeshVertex { const NAME: EntryPointName = "mesh::entry_points::vertex"; fn parameters() -> EntryPointParameters { &[ (&[("VERTEX_TANGENTS", "some")], "none"), (&[("VERTEX_COLORS", "some")], "none"), (&[("SKINNED", "some")], "none"), ] } } /// `bevy_rust_gpu::mesh::entry_points::fragment` pub enum MeshFragment {} impl EntryPoint for MeshFragment { const NAME: EntryPointName = "mesh::entry_points::fragment"; } /// `bevy_rust_gpu::pbr::entry_points::fragment` pub enum PbrFragment {} impl EntryPoint for PbrFragment { const NAME: EntryPointName = "pbr::entry_points::fragment"; fn parameters() -> EntryPointParameters { &[ (&[("NO_TEXTURE_ARRAYS_SUPPORT", "texture")], "array"), (&[("VERTEX_UVS", "some")], "none"), (&[("VERTEX_TANGENTS", "some")], "none"), (&[("VERTEX_COLORS", "some")], "none"), (&[("STANDARDMATERIAL_NORMAL_MAP", "some")], "none"), (&[("SKINNED", "some")], "none"), (&[("TONEMAP_IN_SHADER", "some")], "none"), (&[("DEBAND_DITHER", "some")], "none"), ( &[ ("BLEND_MULTIPLY", "multiply"), ("BLEND_PREMULTIPLIED_ALPHA", "blend_premultiplied_alpha"), ], "none", ), (&[("ENVIRONMENT_MAP", "some")], "none"), (&[("PREMULTIPLY_ALPHA", "some")], "none"), ( &[ ("CLUSTERED_FORWARD_DEBUG_Z_SLICES", "debug_z_slices"), ( "CLUSTERED_FORWARD_DEBUG_CLUSTER_LIGHT_COMPLEXITY", "debug_cluster_light_complexity", ), ( "CLUSTERED_FORWARD_DEBUG_CLUSTER_COHERENCY", "debug_cluster_coherency", ), ], "none", ), ( &[("DIRECTIONAL_LIGHT_SHADOW_MAP_DEBUG_CASCADES", "some")], "none", ), ] } fn constants() -> EntryPointConstants { &["MAX_DIRECTIONAL_LIGHTS", "MAX_CASCADES_PER_LIGHT"] } fn permutation(shader_defs: &Vec<ShaderDefVal>) -> Vec<String> { let mut permutation = vec![]; for (defined, undefined) in Self::parameters().iter() { if let Some(mapping) = defined.iter().find_map(|(def, mapping)| { if shader_defs.contains(&ShaderDefVal::Bool(def.to_string(), true)) { Some(mapping) } else { None } }) { permutation.push(mapping.to_string()); } else { permutation.push(undefined.to_string()) }; } if let Some(ge) = shader_defs.iter().find_map(|def| match def { bevy::render::render_resource::ShaderDefVal::UInt(key, value) => { if key.as_str() == "AVAILABLE_STORAGE_BUFFER_BINDINGS" { Some(*value >= 3) } else { None } } _ => None, }) { if ge { permutation.insert(1, "storage".to_string()) } else { permutation.insert(1, "uniform".to_string()) } } permutation } } /// `StandardMaterial` implementation impl RustGpuMaterial for StandardMaterial { type Vertex = MeshVertex; type Fragment = PbrFragment; }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/lib.rs
src/lib.rs
//! # bevy-rust-gpu //! //! A set of `bevy` plugins supporting the use of `rust-gpu` shaders. //! //! Features include hot-reloading, metadata-based entry point validation, //! and active entry point export. //! //! Can be used in conjunction with `rust-gpu-builder` and `permutate-macro` //! to drive a real-time shader recompilation pipeline. mod builder_output; mod entry_point; mod plugin; mod rust_gpu; mod rust_gpu_material; pub use entry_point::*; pub use plugin::RustGpuPlugin; pub use rust_gpu::*; pub use rust_gpu_material::RustGpuMaterial; pub use rust_gpu_builder_shared::{RustGpuBuilderModules, RustGpuBuilderOutput}; #[cfg(feature = "hot-rebuild")] pub mod entry_point_export; #[cfg(feature = "bevy-pbr-rust")] pub mod bevy_pbr_rust; pub mod prelude;
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/entry_point_export.rs
src/entry_point_export.rs
//! Adds support for exporting the active entry point set to a `.json` file. //! //! This can be used in conjunction with `rust-gpu-builder` and `permutate-macro` to drive hot-recompiles. use std::{ collections::BTreeMap, fs::File, path::PathBuf, sync::mpsc::{Receiver, SyncSender}, }; use bevy::{ prelude::{default, info, CoreSet, Deref, DerefMut, IntoSystemConfig, NonSendMut, Plugin}, render::render_resource::ShaderDefVal, tasks::IoTaskPool, utils::HashMap, }; use serde::{Deserialize, Serialize}; #[cfg(feature = "hot-rebuild")] pub(crate) static EXPORT_HANDLES: once_cell::sync::Lazy< std::sync::RwLock<HashMap<PathBuf, ExportHandle>>, > = once_cell::sync::Lazy::new(default); #[cfg(feature = "hot-rebuild")] pub(crate) static MATERIAL_EXPORTS: once_cell::sync::Lazy< std::sync::RwLock<HashMap<std::any::TypeId, PathBuf>>, > = once_cell::sync::Lazy::new(default); /// Export writer function wrapping `std::fs::File` and `serde_json::to_writer_pretty` pub fn file_writer(path: PathBuf, entry_points: EntryPoints) { let writer = File::create(path).unwrap(); serde_json::to_writer_pretty(writer, &entry_points).unwrap(); } /// Handles exporting known `RustGpuMaterial` permutations to a JSON file for static compilation. pub struct EntryPointExportPlugin<F> { pub writer: F, } impl Default for EntryPointExportPlugin<fn(PathBuf, EntryPoints)> { fn default() -> Self { EntryPointExportPlugin { writer: file_writer, } } } impl<F> Plugin for EntryPointExportPlugin<F> where F: Fn(PathBuf, EntryPoints) + Clone + Send + Sync + 'static, { fn build(&self, app: &mut bevy::prelude::App) { app.world.init_non_send_resource::<EntryPointExport>(); app.add_systems(( EntryPointExport::create_export_containers_system.in_base_set(CoreSet::Update), EntryPointExport::receive_entry_points_system.in_base_set(CoreSet::Last), EntryPointExport::export_entry_points_system(self.writer.clone()) .in_base_set(CoreSet::Last) .after(EntryPointExport::receive_entry_points_system), )); } } /// Handle to an entry point file export pub type ExportHandle = SyncSender<Export>; /// MPSC reciever carrying entry points for export. type EntryPointReceiver = Receiver<Export>; /// MPSC message describing an entry point. #[derive(Debug, Default, Clone)] pub struct Export { pub shader: &'static str, pub permutation: Vec<String>, pub constants: Vec<ShaderDefVal>, pub types: BTreeMap<String, String>, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(untagged)] enum PermutationConstant { Bool(bool), Uint(u32), Int(i32), } #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, Deref, DerefMut)] struct PermutationConstants { #[serde(flatten)] constants: HashMap<String, PermutationConstant>, } impl From<Vec<ShaderDefVal>> for PermutationConstants { fn from(value: Vec<ShaderDefVal>) -> Self { PermutationConstants { constants: value .into_iter() .map(|def| match def { ShaderDefVal::Bool(key, value) => (key, PermutationConstant::Bool(value)), ShaderDefVal::Int(key, value) => (key, PermutationConstant::Int(value)), ShaderDefVal::UInt(key, value) => (key, PermutationConstant::Uint(value)), }) .collect(), } } } #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Permutation { parameters: Vec<String>, constants: PermutationConstants, types: BTreeMap<String, String>, } /// Serializable container for a single entry point #[derive(Debug, Default, Clone, Deref, DerefMut, Serialize, Deserialize)] pub struct EntryPoints { #[serde(flatten)] pub entry_points: HashMap<String, Vec<Permutation>>, } /// Container for a set of entry points, with MPSC handles and change tracking #[derive(Debug)] struct EntryPointExportContainer { rx: EntryPointReceiver, entry_points: EntryPoints, changed: bool, } /// Non-send resource used to register export files and aggregate their entry points. #[derive(Debug, Default, Deref, DerefMut)] struct EntryPointExport { exports: HashMap<PathBuf, EntryPointExportContainer>, } impl EntryPointExport { /// System used to populate export containers for registered materials pub fn create_export_containers_system(mut exports: NonSendMut<Self>) { let material_exports = MATERIAL_EXPORTS.read().unwrap(); for (_, path) in material_exports.iter() { if !exports.contains_key(path) { let (tx, rx) = std::sync::mpsc::sync_channel::<Export>(32); EXPORT_HANDLES.write().unwrap().insert(path.clone(), tx); let container = EntryPointExportContainer { rx, entry_points: default(), changed: default(), }; exports.insert(path.clone(), container); } } } /// System used to receive and store entry points sent from materials. pub fn receive_entry_points_system(mut exports: NonSendMut<Self>) { for (_, export) in exports.exports.iter_mut() { while let Ok(entry_point) = export.rx.try_recv() { if !export.entry_points.contains_key(entry_point.shader) { info!("New entry point: {}", entry_point.shader); export .entry_points .insert(entry_point.shader.to_string(), default()); export.changed = true; } let entry = &export.entry_points[entry_point.shader]; let permutation = Permutation { parameters: entry_point.permutation, constants: entry_point.constants.into(), types: entry_point.types, }; if !entry.contains(&permutation) { info!("New permutation: {:?}", permutation); export .entry_points .get_mut(entry_point.shader) .unwrap() .push(permutation); export.changed = true; } } } } /// System used to write active entry point sets to their respective files on change via the IO task pool. pub fn export_entry_points_system<F>(f: F) -> impl Fn(NonSendMut<Self>) + Send + Sync + 'static where F: Fn(PathBuf, EntryPoints) + Clone + Send + Sync + 'static, { move |mut exports: NonSendMut<Self>| { for (path, export) in exports.exports.iter_mut() { if export.changed { let entry_points = export.entry_points.clone(); let path = path.clone(); let f = f.clone(); info!("Exporting entry points to {:}", path.to_str().unwrap()); IoTaskPool::get() .spawn(async move { f(path, entry_points) }) .detach(); export.changed = false; } } } } }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/rust_gpu.rs
src/rust_gpu.rs
//! Wrapper for extending a `Material` with `rust-gpu` shader functionality. use std::{any::TypeId, marker::PhantomData, path::PathBuf, sync::RwLock}; use bevy::{ asset::Asset, pbr::MaterialPipelineKey, prelude::{ default, info, warn, AssetEvent, Assets, CoreSet, EventReader, Handle, Image, IntoSystemConfig, Material, MaterialPlugin, Plugin, ResMut, }, reflect::TypeUuid, render::render_resource::{ AsBindGroup, PreparedBindGroup, ShaderRef, SpecializedMeshPipelineError, }, sprite::{Material2d, Material2dKey, Material2dPlugin}, utils::HashMap, }; use once_cell::sync::Lazy; use rust_gpu_builder_shared::RustGpuBuilderOutput; use crate::prelude::{EntryPoint, RustGpuMaterial}; static MATERIAL_SETTINGS: Lazy<RwLock<HashMap<TypeId, RustGpuSettings>>> = Lazy::new(default); /// Configures backend [`Material`] support for [`RustGpu<M>`]. pub struct RustGpuMaterialPlugin<M> where M: RustGpuMaterial, { _phantom: PhantomData<M>, } impl<M> Default for RustGpuMaterialPlugin<M> where M: Material + RustGpuMaterial, { fn default() -> Self { RustGpuMaterialPlugin { _phantom: default(), } } } impl<M> Plugin for RustGpuMaterialPlugin<M> where M: Material + RustGpuMaterial, M::Data: Clone + Eq + std::hash::Hash, { fn build(&self, app: &mut bevy::prelude::App) { app.add_plugin(MaterialPlugin::<RustGpu<M>>::default()); app.add_system(reload_materials::<M>.in_base_set(CoreSet::PreUpdate)); } } /// Configures backend [`Material2d`] support for [`RustGpu<M>`]. pub struct RustGpuMaterial2dPlugin<M> where M: RustGpuMaterial, { _phantom: PhantomData<M>, } impl<M> Default for RustGpuMaterial2dPlugin<M> where M: Material2d + RustGpuMaterial, { fn default() -> Self { RustGpuMaterial2dPlugin { _phantom: default(), } } } impl<M> Plugin for RustGpuMaterial2dPlugin<M> where M: Material2d + RustGpuMaterial, M::Data: Clone + Eq + std::hash::Hash, { fn build(&self, app: &mut bevy::prelude::App) { app.add_plugin(Material2dPlugin::<RustGpu<M>>::default()); app.add_system(reload_materials::<M>.in_base_set(CoreSet::PreUpdate)); } } /// Type-level RustGpu material settings #[derive(Debug, Default, Copy, Clone)] pub struct RustGpuSettings { /// If true, use M::vertex as a fallback instead of ShaderRef::default pub fallback_base_vertex: bool, /// If true, use M::fragment as a fallback instead of ShaderRef::default pub fallback_base_fragment: bool, } /// [`RustGpu`] pipeline key. pub struct RustGpuKey<M> where M: AsBindGroup, { pub base: M::Data, pub vertex_shader: Option<Handle<RustGpuBuilderOutput>>, pub fragment_shader: Option<Handle<RustGpuBuilderOutput>>, pub iteration: usize, } impl<M> Clone for RustGpuKey<M> where M: AsBindGroup, M::Data: Clone, { fn clone(&self) -> Self { RustGpuKey { base: self.base.clone(), vertex_shader: self.vertex_shader.clone(), fragment_shader: self.fragment_shader.clone(), iteration: self.iteration.clone(), } } } impl<M> PartialEq for RustGpuKey<M> where M: AsBindGroup, M::Data: PartialEq, { fn eq(&self, other: &Self) -> bool { self.base.eq(&other.base) && self.vertex_shader.eq(&other.vertex_shader) && self.fragment_shader.eq(&other.fragment_shader) && self.iteration.eq(&other.iteration) } } impl<M> Eq for RustGpuKey<M> where M: AsBindGroup, M::Data: Eq, { } impl<M> std::hash::Hash for RustGpuKey<M> where M: AsBindGroup, M::Data: std::hash::Hash, { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.base.hash(state); self.vertex_shader.hash(state); self.fragment_shader.hash(state); self.iteration.hash(state); } } /// Extends a `Material` with `rust-gpu` shader support. #[derive(Debug, Default, Clone, TypeUuid)] #[uuid = "6d355e05-c567-4a29-a84a-362df79111de"] pub struct RustGpu<M> { /// Base material. pub base: M, /// If `Some`, overrides [`Material::vertex_shader`] during specialization. pub vertex_shader: Option<Handle<RustGpuBuilderOutput>>, /// If `Some`, overrides [`Material::fragment_shader`] during specialization. pub fragment_shader: Option<Handle<RustGpuBuilderOutput>>, /// Current reload iteration, used to drive hot-reloading. pub iteration: usize, } impl<M> PartialEq for RustGpu<M> where M: PartialEq, { fn eq(&self, other: &Self) -> bool { self.base.eq(&other.base) && self.vertex_shader.eq(&other.vertex_shader) && self.fragment_shader.eq(&other.fragment_shader) && self.iteration.eq(&other.iteration) } } impl<M> Eq for RustGpu<M> where M: Eq {} impl<M> PartialOrd for RustGpu<M> where M: PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { [ (self.base.partial_cmp(&other.base)), (self.vertex_shader.partial_cmp(&other.vertex_shader)), (self.fragment_shader.partial_cmp(&other.fragment_shader)), (self.iteration.partial_cmp(&other.iteration)), ] .into_iter() .fold(None, |acc, next| match (acc, next) { (None, None) => None, (None, Some(next)) => Some(next), (Some(acc), None) => Some(acc), (Some(acc), Some(next)) => Some(acc.then(next)), }) } } impl<M> Ord for RustGpu<M> where M: Ord, { fn cmp(&self, other: &Self) -> std::cmp::Ordering { [ (self.base.cmp(&other.base)), (self.vertex_shader.cmp(&other.vertex_shader)), (self.fragment_shader.cmp(&other.fragment_shader)), (self.iteration.cmp(&other.iteration)), ] .into_iter() .fold(std::cmp::Ordering::Equal, std::cmp::Ordering::then) } } impl<M> AsBindGroup for RustGpu<M> where M: AsBindGroup, { type Data = RustGpuKey<M>; fn as_bind_group( &self, layout: &bevy::render::render_resource::BindGroupLayout, render_device: &bevy::render::renderer::RenderDevice, images: &bevy::render::render_asset::RenderAssets<Image>, fallback_image: &bevy::render::texture::FallbackImage, ) -> Result< bevy::render::render_resource::PreparedBindGroup<Self::Data>, bevy::render::render_resource::AsBindGroupError, > { self.base .as_bind_group(layout, render_device, images, fallback_image) .map(|base| PreparedBindGroup { bindings: base.bindings, bind_group: base.bind_group, data: RustGpuKey { base: base.data, vertex_shader: self.vertex_shader.clone(), fragment_shader: self.fragment_shader.clone(), iteration: self.iteration, }, }) } fn bind_group_layout( render_device: &bevy::render::renderer::RenderDevice, ) -> bevy::render::render_resource::BindGroupLayout { M::bind_group_layout(render_device) } } impl<M> RustGpu<M> where M: AsBindGroup + RustGpuMaterial + Send + Sync + 'static, { fn specialize_generic( descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor, key: RustGpuKey<M>, ) -> Result<(), SpecializedMeshPipelineError> { info!("Specializing RustGpu material"); let v = 'vertex: { let Some(vertex_shader) = key.vertex_shader else { break 'vertex None; }; info!("Vertex shader is present, aggregating defs"); let entry_point = M::Vertex::build(&descriptor.vertex.shader_defs); info!("Built vertex entrypoint {entry_point:}"); #[cfg(feature = "hot-rebuild")] 'hot_rebuild: { let exports = crate::prelude::MATERIAL_EXPORTS.read().unwrap(); let Some(export) = exports.get(&std::any::TypeId::of::<Self>()) else { break 'hot_rebuild; }; let handles = crate::prelude::EXPORT_HANDLES.read().unwrap(); let Some(handle) = handles.get(export) else { break 'hot_rebuild; }; info!("Entrypoint sender is valid"); handle .send(crate::prelude::Export { shader: M::Vertex::NAME, permutation: M::Vertex::permutation(&descriptor.vertex.shader_defs), constants: M::Vertex::filter_constants(&descriptor.vertex.shader_defs), types: M::Vertex::types() .into_iter() .map(|(key, value)| (key.to_string(), value.to_string())) .collect(), }) .unwrap(); }; info!("Vertex meta is present"); let artifacts = crate::prelude::RUST_GPU_ARTIFACTS.read().unwrap(); let Some(artifact) = artifacts.get(&vertex_shader) else { warn!("Missing vertex artifact."); break 'vertex None; }; info!("Checking entry point {entry_point:}"); if !artifact.entry_points.contains(&entry_point) { warn!("Missing vertex entry point {entry_point:}."); break 'vertex None; } let vertex_shader = match &artifact.modules { crate::prelude::RustGpuModules::Single(single) => single.clone(), crate::prelude::RustGpuModules::Multi(multi) => { let Some(shader) = multi.get(&entry_point) else { break 'vertex None; }; shader.clone() } }; Some((vertex_shader, entry_point)) }; let f = 'fragment: { let (Some(fragment_descriptor), Some(fragment_shader)) = (descriptor.fragment.as_mut(), key.fragment_shader) else { break 'fragment None }; info!("Fragment shader is present, aggregating defs"); let entry_point = M::Fragment::build(&fragment_descriptor.shader_defs); info!("Built fragment entrypoint {entry_point:}"); #[cfg(feature = "hot-rebuild")] 'hot_rebuild: { let exports = crate::prelude::MATERIAL_EXPORTS.read().unwrap(); let Some(export) = exports.get(&std::any::TypeId::of::<Self>()) else { break 'hot_rebuild; }; let handles = crate::prelude::EXPORT_HANDLES.read().unwrap(); let Some(handle) = handles.get(export) else { break 'hot_rebuild; }; info!("Entrypoint sender is valid"); handle .send(crate::prelude::Export { shader: M::Fragment::NAME, permutation: M::Fragment::permutation(&fragment_descriptor.shader_defs), constants: M::Fragment::filter_constants(&fragment_descriptor.shader_defs), types: M::Fragment::types() .into_iter() .map(|(key, value)| (key.to_string(), value.to_string())) .collect(), }) .unwrap(); } info!("Fragment meta is present"); let artifacts = crate::prelude::RUST_GPU_ARTIFACTS.read().unwrap(); let Some(artifact) = artifacts.get(&fragment_shader) else { warn!("Missing fragment artifact."); break 'fragment None; }; info!("Checking entry point {entry_point:}"); if !artifact.entry_points.contains(&entry_point) { warn!("Missing fragment entry point {entry_point:}."); break 'fragment None; } let fragment_shader = match &artifact.modules { crate::prelude::RustGpuModules::Single(single) => single.clone(), crate::prelude::RustGpuModules::Multi(multi) => { let Some(shader) = multi.get(&entry_point) else { warn!("Missing handle for entry point {entry_point:}."); break 'fragment None; }; shader.clone() } }; Some((fragment_shader, entry_point)) }; match (v, descriptor.fragment.as_mut(), f) { (Some((vertex_shader, vertex_entry_point)), None, _) => { info!("Applying vertex shader and entry point"); descriptor.vertex.shader = vertex_shader; descriptor.vertex.entry_point = vertex_entry_point.into(); // Clear shader defs to satify ShaderProcessor descriptor.vertex.shader_defs.clear(); } ( Some((vertex_shader, vertex_entry_point)), Some(fragment_descriptor), Some((fragment_shader, fragment_entry_point)), ) => { info!("Applying vertex shader and entry point"); descriptor.vertex.shader = vertex_shader; descriptor.vertex.entry_point = vertex_entry_point.into(); // Clear shader defs to satify ShaderProcessor descriptor.vertex.shader_defs.clear(); info!("Applying fragment shader and entry point"); fragment_descriptor.shader = fragment_shader; fragment_descriptor.entry_point = fragment_entry_point.into(); // Clear shader defs to satify ShaderProcessor fragment_descriptor.shader_defs.clear(); } _ => warn!("Falling back to default shaders."), } if let Some(label) = &mut descriptor.label { *label = format!("rust_gpu_{}", *label).into(); } Ok(()) } } impl<M> Material for RustGpu<M> where M: Material + RustGpuMaterial, M::Data: Clone, { fn vertex_shader() -> bevy::render::render_resource::ShaderRef { if let Some(true) = MATERIAL_SETTINGS .read() .unwrap() .get(&TypeId::of::<Self>()) .map(|settings| settings.fallback_base_vertex) { M::vertex_shader() } else { ShaderRef::Default } } fn fragment_shader() -> bevy::render::render_resource::ShaderRef { if let Some(true) = MATERIAL_SETTINGS .read() .unwrap() .get(&TypeId::of::<Self>()) .map(|settings| settings.fallback_base_vertex) { M::fragment_shader() } else { ShaderRef::Default } } fn alpha_mode(&self) -> bevy::prelude::AlphaMode { self.base.alpha_mode() } fn depth_bias(&self) -> f32 { self.base.depth_bias() } fn specialize( pipeline: &bevy::pbr::MaterialPipeline<Self>, descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor, layout: &bevy::render::mesh::MeshVertexBufferLayout, key: bevy::pbr::MaterialPipelineKey<Self>, ) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> { M::specialize( // SAFETY: Transmuted element is PhantomData // // Technically relying on a violable implementation detail, // but it seems unlikely to change in such a way that would // introduce UB without a compiler error. unsafe { std::mem::transmute(pipeline) }, descriptor, layout, MaterialPipelineKey { mesh_key: key.mesh_key, bind_group_data: key.bind_group_data.base.clone(), }, )?; RustGpu::<M>::specialize_generic(descriptor, key.bind_group_data)?; Ok(()) } } impl<M> Material2d for RustGpu<M> where M: Material2d + RustGpuMaterial, M::Data: Clone, { fn vertex_shader() -> bevy::render::render_resource::ShaderRef { if let Some(true) = MATERIAL_SETTINGS .read() .unwrap() .get(&TypeId::of::<Self>()) .map(|settings| settings.fallback_base_vertex) { M::vertex_shader() } else { ShaderRef::Default } } fn fragment_shader() -> bevy::render::render_resource::ShaderRef { if let Some(true) = MATERIAL_SETTINGS .read() .unwrap() .get(&TypeId::of::<Self>()) .map(|settings| settings.fallback_base_vertex) { M::fragment_shader() } else { ShaderRef::Default } } fn specialize( descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor, layout: &bevy::render::mesh::MeshVertexBufferLayout, key: bevy::sprite::Material2dKey<Self>, ) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> { M::specialize( descriptor, layout, Material2dKey { mesh_key: key.mesh_key, bind_group_data: key.bind_group_data.base.clone(), }, )?; RustGpu::<M>::specialize_generic(descriptor, key.bind_group_data)?; Ok(()) } } impl<M> RustGpu<M> where M: 'static, { pub fn map_settings<F: FnOnce(&mut RustGpuSettings)>(f: F) { let mut settings = MATERIAL_SETTINGS.write().unwrap(); f(&mut settings.entry(TypeId::of::<Self>()).or_default()); } #[cfg(feature = "hot-rebuild")] pub fn export_to<P: Into<PathBuf>>(path: P) { let mut handles = crate::prelude::MATERIAL_EXPORTS.write().unwrap(); handles.insert(std::any::TypeId::of::<Self>(), path.into()); } } /// [`RustGpuBuilderOutput`] asset event handler. /// /// Handles loading shader assets, maintaining static material data, and respecializing materials on reload. pub fn reload_materials<M>( mut builder_output_events: EventReader<AssetEvent<RustGpuBuilderOutput>>, mut materials: ResMut<Assets<RustGpu<M>>>, ) where M: Asset + RustGpuMaterial, { for event in builder_output_events.iter() { if let AssetEvent::Created { handle } | AssetEvent::Modified { handle } = event { // Mark any materials referencing this asset for respecialization for (_, material) in materials.iter_mut() { let mut reload = false; if let Some(vertex_shader) = &material.vertex_shader { reload |= vertex_shader == handle; } if let Some(fragment_shader) = &material.fragment_shader { reload |= fragment_shader == handle; } if reload { material.iteration += 1; } } } } }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/builder_output.rs
src/builder_output.rs
use std::{collections::BTreeMap, sync::RwLock}; use bevy::prelude::{ default, AssetEvent, Assets, CoreSet, Deref, DerefMut, EventReader, Handle, IntoSystemConfig, Plugin, Res, ResMut, Shader, }; use once_cell::sync::Lazy; use rust_gpu_builder_shared::RustGpuBuilderOutput; /// Static container for `RustGpuArtifacts` to allow access from `Material::specialize` pub static RUST_GPU_ARTIFACTS: Lazy<RwLock<RustGpuArtifacts>> = Lazy::new(default); pub struct BuilderOutputPlugin; impl Plugin for BuilderOutputPlugin { fn build(&self, app: &mut bevy::prelude::App) { #[cfg(feature = "json")] app.add_plugin(bevy_common_assets::json::JsonAssetPlugin::< RustGpuBuilderOutput, >::new(&["rust-gpu.json"])); #[cfg(feature = "msgpack")] app.add_plugin(bevy_common_assets::msgpack::MsgPackAssetPlugin::< RustGpuBuilderOutput, >::new(&["rust-gpu.msgpack"])); app.add_system(builder_output_events.in_base_set(CoreSet::PreUpdate)); } } /// Module shader handle container. #[derive(Debug, Clone)] pub enum RustGpuModules { /// Contains a single unnamed shader. Single(Handle<Shader>), /// Contains multiple named shaders. Multi(BTreeMap<String, Handle<Shader>>), } /// Asset containing loaded rust-gpu shaders and entry point metadata. #[derive(Debug, Clone)] pub struct RustGpuArtifact { pub entry_points: Vec<String>, pub modules: RustGpuModules, } #[derive(Debug, Default, Clone, Deref, DerefMut)] pub struct RustGpuArtifacts { pub artifacts: BTreeMap<Handle<RustGpuBuilderOutput>, RustGpuArtifact>, } /// [`RustGpuBuilderOutput`] asset event handler. /// /// Handles loading shader assets, maintaining static material data, and respecializing materials on reload. pub fn builder_output_events( mut builder_output_events: EventReader<AssetEvent<RustGpuBuilderOutput>>, builder_outputs: Res<Assets<RustGpuBuilderOutput>>, mut shaders: ResMut<Assets<Shader>>, ) { for event in builder_output_events.iter() { if let AssetEvent::Created { handle } | AssetEvent::Modified { handle } = event { let asset = builder_outputs.get(handle).unwrap().clone(); // Create a `RustGpuArtifact` from the affected asset let artifact = match asset.modules { rust_gpu_builder_shared::RustGpuBuilderModules::Single(ref single) => { let shader = shaders.add(Shader::from_spirv(single.clone())); RustGpuArtifact { entry_points: asset.entry_points, modules: RustGpuModules::Single(shader), } } rust_gpu_builder_shared::RustGpuBuilderModules::Multi(multi) => RustGpuArtifact { entry_points: asset.entry_points, modules: RustGpuModules::Multi( multi .into_iter() .map(|(k, module)| (k.clone(), shaders.add(Shader::from_spirv(module)))) .collect(), ), }, }; // Emplace it in static storage RUST_GPU_ARTIFACTS .write() .unwrap() .insert(handle.clone_weak(), artifact); } // On remove, remove the corresponding artifact from static storage if let AssetEvent::Removed { handle } = event { RUST_GPU_ARTIFACTS.write().unwrap().remove(handle); } } }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/entry_point.rs
src/entry_point.rs
//! Trait representation of a `rust-gpu` entry point. use std::collections::BTreeMap; use bevy::render::render_resource::ShaderDefVal; /// An entry point name for use with the [`EntryPoint`] trait. pub type EntryPointName = &'static str; /// A set of entry point compile parameters for use with the [`EntryPoint`] trait. pub type EntryPointParameters = &'static [(&'static [(&'static str, &'static str)], &'static str)]; /// A set of entry point constants for use with the [`EntryPoint`] trait. pub type EntryPointConstants = &'static [&'static str]; /// A set of entry point constants for use with the [`EntryPoint`] trait. pub type EntryPointTypes = Vec<(String, String)>; /// A `rust-gpu` entry point for use with [`RustGpuMaterial`](crate::rust_gpu_material::RustGpuMaterial). pub trait EntryPoint: 'static + Send + Sync { /// The entry point's base function name, including module path /// /// ``` /// # use bevy_rust_gpu::prelude::EntryPointName; /// const NAME: EntryPointName = "mesh::entry_points::vertex"; /// ``` const NAME: &'static str; fn parameters() -> EntryPointParameters { &[] } fn constants() -> EntryPointConstants { &[] } fn types() -> EntryPointTypes { vec![] } /// Constructs a permutation set from the provided shader defs fn permutation(shader_defs: &Vec<ShaderDefVal>) -> Vec<String> { let mut permutation = vec![]; for (defined, undefined) in Self::parameters().iter() { if let Some(mapping) = defined.iter().find_map(|(def, mapping)| { if shader_defs.contains(&ShaderDefVal::Bool(def.to_string(), true)) { Some(mapping) } else { None } }) { permutation.push(mapping.to_string()); } else { permutation.push(undefined.to_string()) }; } permutation } fn filter_constants(shader_defs: &Vec<ShaderDefVal>) -> Vec<ShaderDefVal> { shader_defs .iter() .filter(|def| match def { ShaderDefVal::Bool(key, _) | ShaderDefVal::Int(key, _) | ShaderDefVal::UInt(key, _) => Self::constants().contains(&key.as_str()), }) .cloned() .collect() } /// Build an entry point name from the provided shader defs fn build(shader_defs: &Vec<ShaderDefVal>) -> String { let constants = Self::filter_constants(shader_defs) .into_iter() .map(|def| { ( match &def { ShaderDefVal::Bool(key, _) | ShaderDefVal::Int(key, _) | ShaderDefVal::UInt(key, _) => key.clone(), }, match &def { ShaderDefVal::Bool(value, _) => value.to_string(), ShaderDefVal::Int(_, value) => value.to_string(), ShaderDefVal::UInt(_, value) => value.to_string(), }, ) }) .collect::<BTreeMap<_, _>>(); std::iter::once(Self::NAME.to_string()) .chain( Self::permutation(shader_defs) .into_iter() .map(|variant| "__".to_string() + &variant), ) .chain( constants .into_iter() .map(|(key, value)| key + "_" + &value) .map(|variant| "__".to_string() + &variant), ) .chain( Self::types() .into_iter() .map(|(key, value)| { key.to_string().to_lowercase() + "_" + &value .to_string() .replace(" ", "") .replace("\n", "") .replace("<", "_") .replace(">", "_") .replace("[", "_") .replace("]", "_") .replace("(", "_") .replace(")", "_") .replace("::", "_") .replace(",", "_") .trim_end_matches("_") .to_lowercase() }) .map(|variant| "__".to_string() + &variant), ) .collect::<String>() } } impl EntryPoint for () { const NAME: &'static str = ""; }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
Bevy-Rust-GPU/bevy-rust-gpu
https://github.com/Bevy-Rust-GPU/bevy-rust-gpu/blob/2d9b667d769f49598f28480cc2704890341837b3/src/plugin.rs
src/plugin.rs
//! Main Rust-GPU plugin. use std::path::PathBuf; use bevy::prelude::Plugin; use crate::prelude::{file_writer, BuilderOutputPlugin, EntryPoints}; /// Main Rust-GPU plugin. /// /// Adds support for `RustGpuBuilderOutput` assets, /// and configures entry point export if the `hot-reload` feature is enabled. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct RustGpuPlugin<F> { #[cfg(feature = "hot-rebuild")] pub export_writer: F, #[cfg(not(feature = "hot-rebuild"))] pub _phantom: PhantomData<F>, } impl Default for RustGpuPlugin<fn(PathBuf, EntryPoints)> { fn default() -> Self { Self { #[cfg(target_family = "wasm")] export_writer: |_, _| (), #[cfg(not(target_family = "wasm"))] export_writer: file_writer, } } } impl<F> Plugin for RustGpuPlugin<F> where F: Fn(PathBuf, EntryPoints) + Clone + Send + Sync + 'static, { fn build(&self, app: &mut bevy::prelude::App) { app.add_plugin(BuilderOutputPlugin); #[cfg(feature = "hot-rebuild")] app.add_plugin(crate::prelude::EntryPointExportPlugin { writer: self.export_writer.clone(), }); } }
rust
Apache-2.0
2d9b667d769f49598f28480cc2704890341837b3
2026-01-04T20:18:48.623408Z
false
chaosprint/dattorro-vst-rs
https://github.com/chaosprint/dattorro-vst-rs/blob/4623ad8e38e3df149bc78b5c749fc0db26124554/src/lib.rs
src/lib.rs
//! Barebones baseview egui plugin #[macro_use] extern crate vst; use egui::CtxRef; use baseview::{Size, WindowHandle, WindowOpenOptions, WindowScalePolicy}; use vst::buffer::AudioBuffer; use vst::editor::Editor; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::AtomicFloat; use egui_baseview::{EguiWindow, Queue, RenderSettings, Settings}; use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; use std::sync::Arc; use glicol_synth::{ Message, AudioContext, oscillator::{SinOsc}, filter::{ OnePole, AllPassFilterGain}, effect::Balance, operator::{Mul, Add}, delay::{DelayN, DelayMs}, Pass, AudioContextBuilder, Sum }; const WINDOW_WIDTH: usize = 300; const WINDOW_HEIGHT: usize = 200; // we have only struct definition in this lib struct PluginEditor { params: Arc<EffectParameters>, window_handle: Option<WindowHandle>, is_open: bool, } struct EffectParameters { bandwidth: AtomicFloat, damping: AtomicFloat, decay: AtomicFloat, mix: AtomicFloat, } struct DattorroPlugin { params: Arc<EffectParameters>, editor: Option<PluginEditor>, context: AudioContext<128>, bandwidth: f32, // for checking the diff damping: f32, decay: f32, mix: f32, } impl Editor for PluginEditor { fn position(&self) -> (i32, i32) { (0, 0) } fn size(&self) -> (i32, i32) { (WINDOW_WIDTH as i32, WINDOW_HEIGHT as i32) } fn open(&mut self, parent: *mut ::std::ffi::c_void) -> bool { ::log::info!("Editor open"); if self.is_open { return false; } self.is_open = true; let settings = Settings { window: WindowOpenOptions { title: String::from("Dattorro Reverb"), size: Size::new(WINDOW_WIDTH as f64, WINDOW_HEIGHT as f64), scale: WindowScalePolicy::SystemScaleFactor, }, render_settings: RenderSettings::default(), }; let window_handle = EguiWindow::open_parented( &VstParent(parent), settings, self.params.clone(), |_egui_ctx: &CtxRef, _queue: &mut Queue, _state: &mut Arc<EffectParameters>| {}, |egui_ctx: &CtxRef, _queue: &mut Queue, state: &mut Arc<EffectParameters>| { egui::Window::new("Dattorro Reverb").show(&egui_ctx, |ui| { ui.heading("Made with egui and glicol_synth"); let mut bandwidth = state.bandwidth.get(); let mut damping = state.damping.get(); let mut decay = state.decay.get(); let mut mix = state.mix.get(); if ui .add(egui::Slider::new(&mut bandwidth, 0.0..=1.0).text("bandwidth")) .changed() { state.bandwidth.set(bandwidth) } if ui .add(egui::Slider::new(&mut damping, 0.0..=1.0).text("damping")) .changed() { state.damping.set(damping) } if ui .add(egui::Slider::new(&mut decay, 0.0..=0.9999).text("decay")) .changed() { state.decay.set(decay) } if ui .add(egui::Slider::new(&mut mix, 0.0..=1.0).text("mix")) .changed() { state.mix.set(mix) } }); }, ); self.window_handle = Some(window_handle); true } fn is_open(&mut self) -> bool { self.is_open } fn close(&mut self) { self.is_open = false; if let Some(mut window_handle) = self.window_handle.take() { window_handle.close(); } } } impl Default for DattorroPlugin { fn default() -> Self { let params = Arc::new(EffectParameters::default()); let mut context = AudioContextBuilder::<128>::new() .sr(48000).channels(2).build(); // todo: sr can be different // we create the input manually, and tag it for later use // you will see the tag usage soon let input = context.add_mono_node( Pass{} ); context.tags.insert("input", input); let wet1 = context.add_mono_node(OnePole::new(0.7)); context.tags.insert("inputlpf", wet1); let wet2 = context.add_mono_node(DelayMs::new().delay(50.)); let wet3 = context.add_mono_node(AllPassFilterGain::new().delay(4.771).gain(0.75)); let wet4 = context.add_mono_node(AllPassFilterGain::new().delay(3.595).gain(0.75)); let wet5 = context.add_mono_node(AllPassFilterGain::new().delay(12.72).gain(0.625)); let wet6 = context.add_mono_node(AllPassFilterGain::new().delay(9.307).gain(0.625)); let wet7 = context.add_mono_node(Add::new(0.0)); // fb here let wet8 = context.add_mono_node(AllPassFilterGain::new().delay(100.0).gain(0.7)); // mod here context.chain(vec![input, wet1, wet2, wet3, wet4, wet5, wet6, wet7, wet8]); let mod1 = context.add_mono_node(SinOsc::new().freq(0.1)); let mod2 = context.add_mono_node(Mul::new(5.5)); let mod3 = context.add_mono_node(Add::new(29.5)); let _ = context.chain(vec![mod1, mod2, mod3, wet8]); // we are going to take some halfway delay from line a let aa = context.add_mono_node(DelayN::new(394)); context.connect(wet8, aa); let ab = context.add_mono_node(DelayN::new(2800)); context.connect(aa, ab); let ac = context.add_mono_node(DelayN::new(1204)); context.connect(ab, ac); let ba1 = context.add_mono_node( DelayN::new(2000)); context.connect(ac, ba1); let ba2 = context.add_mono_node( OnePole::new(0.1)); context.tags.insert("tanklpf1", ba2); context.connect(ba1, ba2); let ba3 = context.add_mono_node( AllPassFilterGain::new().delay(7.596).gain(0.5) ); context.connect(ba2, ba3); let bb = context.add_mono_node(AllPassFilterGain::new().delay(35.78).gain(0.5)); context.connect(ba3, bb); let bc = context.add_mono_node(AllPassFilterGain::new().delay(100.).gain(0.5)); context.connect(bb, bc); let _ = context.chain(vec![mod1, mod2, mod3, bc]); // modulate here let ca = context.add_mono_node(DelayN::new(179)); context.connect(bc, ca); let cb = context.add_mono_node(DelayN::new(2679)); context.connect(ca, cb); let cc1 = context.add_mono_node(DelayN::new(3500)); let cc2 = context.add_mono_node(Mul::new(0.3)); // another g5 context.tags.insert("fbrate2", cc2); context.chain(vec![cb, cc1, cc2]); let da1 = context.add_mono_node(AllPassFilterGain::new().delay(30.).gain(0.7)); let da2 = context.add_mono_node(DelayN::new(522)); context.chain(vec![cc2, da1, da2]); let db = context.add_mono_node(DelayN::new(2400)); context.connect(da2, db); let dc = context.add_mono_node(DelayN::new(2400)); context.connect(db, dc); let ea1 = context.add_mono_node(OnePole::new(0.1)); context.tags.insert("tanklpf2", ea1); let ea2 = context.add_mono_node(AllPassFilterGain::new().delay(6.2).gain(0.7)); context.chain(vec![dc, ea1, ea2]); let eb = context.add_mono_node(AllPassFilterGain::new().delay(34.92).gain(0.7)); context.connect(ea2, eb); let fa1 = context.add_mono_node(AllPassFilterGain::new().delay(20.4).gain(0.7)); let fa2 = context.add_mono_node(DelayN::new(1578)); context.chain(vec![eb, fa1, fa2]); let fb = context.add_mono_node(DelayN::new(2378)); context.connect(fa2, fb); let fb1 = context.add_mono_node(DelayN::new(2500)); let fb2 = context.add_mono_node(Mul::new(0.3)); context.tags.insert("fbrate1", fb2); context.chain(vec![fb, fb1, fb2, wet7]); // back to feedback // start to take some signal out let left_subtract = context.add_mono_node( Sum{}); context.connect(bb,left_subtract); context.connect(db,left_subtract); context.connect(ea2,left_subtract); context.connect(fa2,left_subtract); // turn these signal into - let left_subtract2 = context.add_mono_node(Mul::new(-1.0)); context.connect(left_subtract,left_subtract2); let left = context.add_mono_node(Sum{}); context.connect(aa,left); context.connect(ab,left); context.connect(cb,left); context.connect(left_subtract2,left); let leftwet = context.add_mono_node(Mul::new(0.1)); context.tags.insert("mix1", leftwet); let leftmix = context.add_mono_node(Sum{}); // input dry * (1.-mix) let leftdrymix = context.add_mono_node(Mul::new(0.9)); context.tags.insert("mixdiff1", leftdrymix); context.chain(vec![input, leftdrymix, leftmix]); context.chain(vec![left, leftwet, leftmix]); let right_subtract = context.add_mono_node(Sum{}); context.connect(eb,right_subtract); context.connect(ab,right_subtract); context.connect(ba2,right_subtract); context.connect(ca,right_subtract); let right_subtract2 = context.add_mono_node(Mul::new(-1.0)); context.connect(right_subtract,right_subtract2); let right = context.add_mono_node(Sum{}); context.connect(da2,right); context.connect(db,right); context.connect(fb,right); context.connect(right_subtract2,right); let rightwet = context.add_mono_node(Mul::new(0.1)); context.tags.insert("mix2", rightwet); let rightmix = context.add_mono_node(Sum{}); // input dry * (1.-mix) let rightdry = context.add_mono_node(Mul::new(0.9)); context.tags.insert("mixdiff2", rightdry); context.chain(vec![input, rightdry, rightmix]); context.chain(vec![right, rightwet,rightmix]); let balance = context.add_stereo_node(Balance::new()); context.connect(leftmix,balance); context.connect(rightmix,balance); context.connect(balance, context.destination); Self { params: params.clone(), editor: Some(PluginEditor { params: params.clone(), window_handle: None, is_open: false, }), context, bandwidth: 0.7, damping: 0.1, decay: 0.3, mix: 0.1 } } } impl Default for EffectParameters { fn default() -> EffectParameters { EffectParameters { bandwidth: AtomicFloat::new(0.7), damping: AtomicFloat::new(0.1), decay: AtomicFloat::new(0.3), mix: AtomicFloat::new(0.1), } } } impl Plugin for DattorroPlugin { fn get_info(&self) -> Info { Info { name: "Dattorro Reverb".to_string(), vendor: "chaosprint".to_string(), unique_id: 19891010, version: 1, inputs: 1, // channels, dattorro is mono in, stereo out outputs: 2, // This `parameters` bit is important; without it, none of our // parameters will be shown! parameters: 4, category: Category::Effect, ..Default::default() } } fn init(&mut self) { let log_folder = ::dirs::home_dir().unwrap().join("tmp"); let _ = ::std::fs::create_dir(log_folder.clone()); let log_file = ::std::fs::File::create(log_folder.join("EGUIBaseviewTest.log")).unwrap(); let log_config = ::simplelog::ConfigBuilder::new() .set_time_to_local(true) .build(); let _ = ::simplelog::WriteLogger::init(simplelog::LevelFilter::Info, log_config, log_file); ::log_panics::init(); ::log::info!("init"); } fn get_editor(&mut self) -> Option<Box<dyn Editor>> { if let Some(editor) = self.editor.take() { Some(Box::new(editor) as Box<dyn Editor>) } else { None } } // Here is where the bulk of our audio processing code goes. fn process(&mut self, buffer: &mut AudioBuffer<f32>) { let bandwidth = self.params.bandwidth.get(); let damping = self.params.damping.get(); let decay = self.params.decay.get(); let mix = self.params.mix.get(); if bandwidth != self.bandwidth { self.context.send_msg(self.context.tags["inputlpf"], Message::SetToNumber(0, bandwidth)); self.bandwidth = bandwidth; } if damping != self.damping { self.context.send_msg(self.context.tags["tanklpf1"], Message::SetToNumber(0, damping)); self.context.send_msg(self.context.tags["tanklpf2"], Message::SetToNumber(0, damping)); self.damping = damping; } if decay != self.decay { self.context.send_msg(self.context.tags["fbrate1"], Message::SetToNumber(0, decay)); self.context.send_msg(self.context.tags["fbrate2"], Message::SetToNumber(0, decay)); self.decay = decay; } if mix != self.mix { self.context.send_msg(self.context.tags["mix1"], Message::SetToNumber(0, mix)); self.context.send_msg(self.context.tags["mix2"], Message::SetToNumber(0, mix)); self.context.send_msg(self.context.tags["mixdiff1"], Message::SetToNumber(0, 1.-mix)); self.context.send_msg(self.context.tags["mixdiff2"], Message::SetToNumber(0, 1.-mix)); self.mix = mix; } let block_size: usize = buffer.samples(); let (input, mut outputs) = buffer.split(); let output_channels = outputs.len(); let process_times = block_size / 128; for b in 0..process_times { let inp = &input.get(0)[b*128..(b+1)*128]; self.context.graph[ self.context.tags["input"] ].buffers[0].copy_from_slice(inp); // self.context.graph[ // self.context.tags["input"] // ].buffers[1].copy_from_slice(inp[1]); let engine_out = self.context.next_block(); for chan_idx in 0..output_channels { let buff = outputs.get_mut(chan_idx); for n in 0..128 { buff[b*128+n] = engine_out[chan_idx][n]; } } } } // Return the parameter object. This method can be omitted if the // plugin has no parameters. fn get_parameter_object(&mut self) -> Arc<dyn PluginParameters> { Arc::clone(&self.params) as Arc<dyn PluginParameters> } } impl PluginParameters for EffectParameters { // the `get_parameter` function reads the value of a parameter. fn get_parameter(&self, index: i32) -> f32 { match index { 0 => self.bandwidth.get(), 1 => self.damping.get(), 2 => self.decay.get(), 3 => self.mix.get(), _ => 0.0, } } // the `set_parameter` function sets the value of a parameter. fn set_parameter(&self, index: i32, val: f32) { #[allow(clippy::single_match)] match index { 0 => self.bandwidth.set(val), 1 => self.damping.set(val), 2 => self.decay.set(val), 3 => self.mix.set(val), _ => (), } } // This is what will display underneath our control. // For example, in Ableton, the square gui where you drap the fx // format it into a string that makes the most sense. fn get_parameter_text(&self, index: i32) -> String { match index { 0 => format!("{:.2}", self.bandwidth.get()), 1 => format!("{:.2}", self.damping.get()), 2 => format!("{:.2}", self.decay.get()), 3 => format!("{:.2}", self.mix.get()), _ => "".to_string(), } } // This shows the control's name. fn get_parameter_name(&self, index: i32) -> String { match index { 0 => "bandwidth", 1 => "damping", 2 => "decay", 3 => "mix", _ => "", } .to_string() } } // boilerplate code, identical for all vst plugins // just skip to the last line struct VstParent(*mut ::std::ffi::c_void); #[cfg(target_os = "macos")] unsafe impl HasRawWindowHandle for VstParent { fn raw_window_handle(&self) -> RawWindowHandle { use raw_window_handle::macos::MacOSHandle; RawWindowHandle::MacOS(MacOSHandle { ns_view: self.0 as *mut ::std::ffi::c_void, ..MacOSHandle::empty() }) } } #[cfg(target_os = "windows")] unsafe impl HasRawWindowHandle for VstParent { fn raw_window_handle(&self) -> RawWindowHandle { use raw_window_handle::windows::WindowsHandle; RawWindowHandle::Windows(WindowsHandle { hwnd: self.0, ..WindowsHandle::empty() }) } } #[cfg(target_os = "linux")] unsafe impl HasRawWindowHandle for VstParent { fn raw_window_handle(&self) -> RawWindowHandle { use raw_window_handle::unix::XcbHandle; RawWindowHandle::Xcb(XcbHandle { window: self.0 as u32, ..XcbHandle::empty() }) } } // the last thing you need to change is the name plugin_main!(DattorroPlugin);
rust
MIT
4623ad8e38e3df149bc78b5c749fc0db26124554
2026-01-04T20:19:21.735521Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/src/prelude.rs
propfuzz/src/prelude.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Re-exports for the most commonly used APIs of `propfuzz`. //! //! This includes: //! * the `propfuzz` macro from this crate //! * the entire prelude of `proptest`, so existing tests can be migrated with minimal hassle. //! //! ## Examples //! //! There's no need to specify `proptest` as a separate dependency, since you can write: //! //! ``` //! use propfuzz::prelude::*; //! use proptest::collection::vec; //! //! /// Example test. //! #[propfuzz] //! fn test(#[propfuzz(strategy = "vec(any::<u8>(), 0..64)")] v: Vec<u8>) { //! // ... //! } //! ``` #[doc(no_inline)] pub use crate::propfuzz; #[doc(no_inline)] pub use proptest; #[doc(no_inline)] pub use proptest::prelude::*;
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/src/lib.rs
propfuzz/src/lib.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Rust toolkit to combine property-based testing with fuzzing. //! //! For more, see the [`README`](https://github.com/facebookincubator/propfuzz/blob/main/README.md) //! at the root of the `propfuzz` repository. pub mod prelude; pub mod runtime; pub mod traits; // Re-export the propfuzz macro -- this is expected to be the primary interface. #[cfg(feature = "macro")] pub use propfuzz_macro::propfuzz; pub use proptest;
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/src/runtime.rs
propfuzz/src/runtime.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Runtime support. use crate::traits::StructuredTarget; use proptest::test_runner::{TestError, TestRunner}; use std::fmt; /// Executes a propfuzz target as a standard property-based test. pub fn execute_as_proptest(fuzz_target: impl StructuredTarget) { let mut config = fuzz_target.proptest_config(); config.test_name = Some(fuzz_target.name()); let mut test_runner = TestRunner::new(config); match fuzz_target.execute(&mut test_runner) { Ok(()) => (), Err(err) => panic!( "{}{}", TestErrorDisplay::new(&fuzz_target, err), test_runner ), } } struct TestErrorDisplay<'a, PF, T> { fuzz_target: &'a PF, err: TestError<T>, } impl<'a, PF, T> TestErrorDisplay<'a, PF, T> { fn new(fuzz_target: &'a PF, err: TestError<T>) -> Self { Self { fuzz_target, err } } } impl<'a, PF, T> fmt::Display for TestErrorDisplay<'a, PF, T> where PF: StructuredTarget<Value = T>, T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.err { TestError::Abort(why) => write!(f, "Test aborted: {}", why), TestError::Fail(why, what) => { writeln!(f, "Test failed: {}\nminimal failing input:", why)?; self.fuzz_target.fmt_value(&what, f) } } } }
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/src/traits.rs
propfuzz/src/traits.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! The core traits powering `propfuzz`. //! //! `propfuzz` relies on separating out a standard property-based test into its components: //! * constructing a configuration //! * executing the test, given a test runner //! * formatting failing values use proptest::prelude::*; use proptest::test_runner::{TestError, TestRunner}; use std::fmt; /// Represents a structured fuzz target. /// /// Functions written with the `propfuzz` macro are converted to implementations of this trait. /// /// A trait that implements `Propfuzz` can be used both as a standard property-based test, and /// as a target for structured, mutation-based fuzzing. /// /// Structured, mutation-based fuzzers use random byte sequences as a pass-through RNG. In other /// words, the random byte sequences act as something like a DNA for random values. pub trait StructuredTarget: Send + Sync + fmt::Debug { /// The type of values generated by the proptest. type Value: fmt::Debug; /// Returns the name of this structured fuzz target. fn name(&self) -> &'static str; /// Returns an optional description for this structured fuzz target. fn description(&self) -> Option<&'static str>; /// Returns the proptest config for this fuzz target. /// /// The default implementation for the `#[propfuzz]` macro uses the default `proptest` config, /// and sets `source_file` to the file the macro is invoked from. The config can be altered /// through passing arguments to `#[propfuzz]`. fn proptest_config(&self) -> ProptestConfig { ProptestConfig::default() } /// Executes this test using the given test runner. /// /// This is where the main body of the test goes. fn execute(&self, test_runner: &mut TestRunner) -> Result<(), TestError<Self::Value>>; /// Formats a failing test case for displaying to the user. /// /// The default implementation calls the `fmt::Debug` implementation on the value. /// /// The default implementation for the `#[propfuzz]` macro prints out variable names and values. fn fmt_value(&self, value: &Self::Value, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", value) } }
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/trybuild.rs
propfuzz/tests/trybuild.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Trybuild tests for propfuzz-macro. #[test] fn trybuild_tests() { let t = trybuild::TestCases::new(); t.compile_fail("tests/compile-fail/*.rs"); }
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/basic.rs
propfuzz/tests/basic.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 /// Basic tests for propfuzz-macro. use pretty_assertions::assert_eq; use propfuzz::{prelude::*, traits::StructuredTarget}; use proptest::{ collection::vec, test_runner::{FileFailurePersistence, TestError, TestRunner}, }; /// Basic test for foo. /// /// This is a simple test which ensures that adding two numbers returns the expected result. #[propfuzz] fn add_two(a: u64, b: u64) { let sum = a.checked_add(b); assert_eq!(sum, a.checked_add(b)); } #[test] fn propfuzz_add_two() { assert_eq!(__PROPFUZZ__add_two.name(), "basic::add_two"); assert_eq!( __PROPFUZZ__add_two .description() .expect("expected description"), "Basic test for foo.\n\ \n\ This is a simple test which ensures that adding two numbers returns the expected result." ); let config = __PROPFUZZ__add_two.proptest_config(); assert_eq!(config.cases, 256, "correct case count"); assert_eq!(config.fork, false, "correct fork setting"); } #[propfuzz(fork = true)] fn add_pair((a, b): (u64, u64)) { let sum = a.checked_add(b); assert_eq!(sum, a.checked_add(b)); } #[test] fn propfuzz_add_pair() { assert_eq!(__PROPFUZZ__add_pair.name(), "basic::add_pair"); assert!( __PROPFUZZ__add_pair.description().is_none(), "no doc comment" ); let config = __PROPFUZZ__add_pair.proptest_config(); assert_eq!(config.cases, 256, "correct case count"); assert_eq!(config.fork, true, "correct fork setting"); } /// Test that reversing a list twice produces the same results. #[propfuzz(cases = 1024)] fn reverse(#[propfuzz(strategy = "vec(any::<u32>(), 0..64)")] mut list: Vec<u32>) { let list2 = list.clone(); list.reverse(); list.reverse(); prop_assert_eq!(list, list2); } #[test] fn propfuzz_reverse() { assert_eq!(__PROPFUZZ__reverse.name(), "basic::reverse"); assert_eq!( __PROPFUZZ__reverse .description() .expect("expected description"), "Test that reversing a list twice produces the same results." ); let config = __PROPFUZZ__reverse.proptest_config(); assert_eq!(config.cases, 1024, "correct case count"); assert_eq!(config.fork, false, "correct fork setting"); } /// This test fails. It is ignored by default and can be run with `cargo test -- --ignored`. #[propfuzz(fuzz_default = true)] #[ignore] fn failing(#[propfuzz(strategy = "vec(any::<u32>(), 0..64)")] mut list: Vec<u32>) { let list2 = list.clone(); // The list is only reversed once. list.reverse(); prop_assert_eq!(list, list2); } #[test] fn propfuzz_failing() { assert_eq!(__PROPFUZZ__failing.name(), "basic::failing"); assert_eq!( __PROPFUZZ__failing .description() .expect("expected description"), "This test fails. It is ignored by default and can be run with `cargo test -- --ignored`." ); let mut config = __PROPFUZZ__failing.proptest_config(); assert_eq!(config.cases, 256, "correct case count"); assert_eq!(config.fork, false, "correct fork setting"); // Try running the test and ensure it fails with the correct value. (Determinism is ensured // through checking in basic-failing-seed.) config.failure_persistence = Some(Box::new(FileFailurePersistence::Direct( "tests/basic-failing-seed", ))); let mut test_runner = TestRunner::new(config); let err = __PROPFUZZ__failing .execute(&mut test_runner) .expect_err("test should fail"); assert!( matches!(err, TestError::Fail(_, value) if &value.0 == &[0, 1]), "minimal test case" ); } /// Test multiple #[propfuzz] annotations. #[propfuzz(cases = 1024)] #[propfuzz(fork = true)] fn multi(_: Vec<u8>) {} #[test] fn propfuzz_multi() { assert_eq!(__PROPFUZZ__multi.name(), "basic::multi"); assert_eq!( __PROPFUZZ__multi .description() .expect("expected description"), "Test multiple #[propfuzz] annotations." ); let config = __PROPFUZZ__multi.proptest_config(); assert_eq!(config.cases, 1024, "correct case count"); assert_eq!(config.fork, true, "correct fork setting"); } /// Test all proptest options. #[propfuzz(cases = 1, max_local_rejects = 2, max_global_rejects = 3)] #[propfuzz(max_flat_map_regens = 4, fork = true, timeout = 5, max_shrink_time = 6)] #[propfuzz(max_shrink_iters = 7, verbose = 8)] #[ignore] fn all_proptest_options(_: u8) {} #[test] fn propfuzz_all_proptest_options() { let config = __PROPFUZZ__all_proptest_options.proptest_config(); assert_eq!(config.cases, 1); assert_eq!(config.max_local_rejects, 2); assert_eq!(config.max_global_rejects, 3); assert_eq!(config.max_flat_map_regens, 4); assert_eq!(config.fork, true); assert_eq!(config.timeout, 5); assert_eq!(config.max_shrink_time, 6); assert_eq!(config.max_shrink_iters, 7); assert_eq!(config.verbose, 8); }
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/compile-fail/bad-args.rs
propfuzz/tests/compile-fail/bad-args.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Propfuzz with bad arguments. use propfuzz::propfuzz; /// Arguments of the wrong type (note multiple errors). #[propfuzz(cases = true, fork = 1024)] fn wrong_type1(_: u8) {} /// Basic test for repeated arguments. #[propfuzz(cases = 1024, cases = 2048)] fn repeated1(_: Vec<u8>) {} #[propfuzz(cases = 1024)] #[propfuzz(cases = 2048)] fn repeated2(_: Vec<u8>) {} /// Unsupported attribute kinds. #[propfuzz] #[propfuzz(wat)] #[propfuzz = "wat"] fn unsupported_kinds(_: u8) {} /// Repeated arguments and strategies. #[propfuzz(cases = 256)] #[propfuzz(cases = 512)] fn repeated_strategy( #[propfuzz(strategy = "any::<u8>()")] #[propfuzz(strategy = "any::<u8>()")] _: u8, ) { } fn main() {}
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false
facebookarchive/propfuzz
https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/compile-fail/bad_strategies.rs
propfuzz/tests/compile-fail/bad_strategies.rs
// Copyright (c) The propfuzz Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Propfuzz with bad strategies. use propfuzz::prelude::*; use proptest::collection::vec; use std::collections::HashSet; /// Incorrect strategy format. #[propfuzz] fn wrong_format(#[propfuzz(strategy(foo))] _: u8) {} /// Invalid expression (_ is not a valid Rust identifier). #[propfuzz] fn invalid_expr(#[propfuzz(strategy = "_")] _: u8) {} /// Unknown function name. #[propfuzz] fn unknown_name(#[propfuzz(strategy = "xxxxxxx(any::<u64>(), 0..8)")] _: HashSet<u64>) {} /// Unknown attribute. #[propfuzz] fn unknown_attr(#[foo] _: u8) {} /// Wrong type of strategy. #[propfuzz] fn wrong_strategy_type(#[propfuzz(strategy = "vec(any::<u64>(), 0..8)")] _: HashSet<u64>) {} fn main() {}
rust
Apache-2.0
742567d73088988fc24f065a0aba3e88adb049f4
2026-01-04T20:18:50.820316Z
false