Struct hydra::Process

source ·
pub struct Process { /* private fields */ }
Expand description

A light weight task that can send and receive messages.

Implementations§

source§

impl Process

source

pub fn alias(reply: bool) -> Reference

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.

source

pub fn unalias(alias: Reference) -> bool

Explicitly deactivates a process alias.

Returns true if the alias was currently-active for the current process, or false otherwise.

source

pub fn current() -> Pid

Returns the current Pid.

Examples found in repository?
examples/supervisor.rs (line 75)
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    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(())
    }
source

pub fn whereis<S: AsRef<str>>(name: S) -> Option<Pid>

Returns the Pid registered under name or None if the name is not registered.

source

pub fn send<D: Into<Dests>, M: Receivable>(dests: D, message: M)

Sends a message to dests.

§Example:

This method allows sending to multiple targets with certain trade offs:

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!");
source

pub fn send_after<D: Into<Dests>, M: Receivable>( dest: D, message: M, duration: Duration ) -> Reference

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:

Process::send_after(pid, "hello world!", Duration::from_secs(5));
source

pub fn cancel_timer(timer: Reference)

Cancels a timer created by send_after.

source

pub fn read_timer(timer: Reference) -> Option<Duration>

Reads a timer created by send_after.

It returns the time remaining until the timer expires.

source

pub fn receiver() -> ProcessReceiver<()>

Creates a receiver with advanced filtering options from the current processes mailbox.

source

pub async fn receive<T: Receivable>() -> Message<T>

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.

source

pub fn spawn<T>(function: T) -> Pid
where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static,

Spawns the given function as a process and returns it’s Pid.

Examples found in repository?
examples/supervisor.rs (lines 77-90)
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    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(())
    }
More examples
Hide additional examples
examples/registry.rs (line 73)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    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
    }

Spawns the given function as a process, creates a link between the calling process, and returns the new Pid.

source

pub fn spawn_monitor<T>(function: T) -> (Pid, Reference)
where T: Future<Output = ()> + Send + 'static, T::Output: Send + 'static,

Spawns the given function as a process, creates a monitor for the calling process, and returns the new Pid.

source

pub fn alive(pid: Pid) -> bool

Returns true if the given Pid is alive on the local node.

source

pub async fn sleep(duration: Duration)

Sleeps the current process for the given duration.

Examples found in repository?
examples/registry.rs (line 110)
107
108
109
110
111
    async fn terminate(&mut self, _reason: ExitReason) {
        tracing::info!("Shutting down MySpace! {:?}", self.id);

        Process::sleep(Duration::from_secs(5)).await;
    }
More examples
Hide additional examples
examples/supervisor.rs (line 86)
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    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(())
    }
source

pub async fn timeout<F>( duration: Duration, future: F ) -> Result<<F as Future>::Output, Timeout>
where F: Future,

Waits for the given future to complete until the given duration is up.

source

pub fn register<S: Into<String>>(pid: Pid, name: S) -> Result<(), ArgumentError>

Registers the given Pid under name if the process is local, active, and the name is not already registered.

source

pub fn unregister<S: AsRef<str>>(name: S)

Removes the registered name, associated with a Pid.

source

pub fn registered() -> Vec<String>

Returns a Vec of registered process names.

source

pub fn list() -> Vec<Pid>

Returns a Vec of Pid’s on the local node.

Creates a bi-directional link between the current process and the given process.

Removes the link between the calling process and the given process.

source

pub fn monitor<T: Into<Dest>>(process: T) -> Reference

Starts monitoring the given process from the calling process. If the process is already dead a message is sent immediately.

source

pub fn monitor_alias<T: Into<Dest>>(process: T, reply: bool) -> 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.
source

pub fn demonitor(monitor: 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.

source

pub fn flags() -> ProcessFlags

Returns the current process flags.

source

pub fn set_flags(flags: ProcessFlags)

Sets one or more process flags.

Examples found in repository?
examples/registry.rs (line 100)
99
100
101
102
103
104
105
    async fn init(&mut self) -> Result<(), ExitReason> {
        Process::set_flags(ProcessFlags::TRAP_EXIT);

        tracing::info!("Init MySpace for {:?}", self.id);

        Ok(())
    }
source

pub fn exit<E: Into<ExitReason>>(pid: Pid, exit_reason: E)

Sends an exit signal with the given reason to Pid.

Trait Implementations§

source§

impl Drop for Process

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl !Freeze for Process

§

impl !RefUnwindSafe for Process

§

impl Send for Process

§

impl !Sync for Process

§

impl Unpin for Process

§

impl !UnwindSafe for Process

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more