Skip to main content

meio_connect/server/
bind.rs

1//! Helpers for binding a server to a socket address.
2//!
3//! Also contains interactions to get notifications about it.
4
5use super::{HttpServer, HttpServerLink};
6use anyhow::Error;
7use async_trait::async_trait;
8use derive_more::From;
9use meio::prelude::{
10    Action, ActionHandler, Context, Interact, Interaction, InteractionResponder, InteractionTask,
11};
12use std::net::SocketAddr;
13
14/// The interaction event for waiting for the address of the server.
15///
16/// It's used to ensure the server has binded to an address and other
17/// parts can use it to connect to it.
18pub struct WaitForAddress;
19
20impl Interaction for WaitForAddress {
21    type Output = SocketAddr;
22}
23
24impl HttpServerLink {
25    /// Creates a waiting task for server's address.
26    pub fn wait_for_address(&self) -> InteractionTask<WaitForAddress> {
27        self.address.interact(WaitForAddress)
28    }
29}
30
31#[async_trait]
32impl ActionHandler<Interact<WaitForAddress>> for HttpServer {
33    async fn handle(
34        &mut self,
35        msg: Interact<WaitForAddress>,
36        _ctx: &mut Context<Self>,
37    ) -> Result<(), Error> {
38        match &mut self.addr_state {
39            AddrState::NotAssignedYet { listeners } => {
40                listeners.push(msg.responder);
41            }
42            AddrState::Assigned { addr } => {
43                if let Err(err) = msg.responder.send(Ok(*addr)) {
44                    log::error!(target: &self.log_target, "Can't send address result {:?} to the listener.", err);
45                }
46            }
47        }
48        Ok(())
49    }
50}
51
52pub(super) enum AddrState {
53    NotAssignedYet {
54        listeners: Vec<InteractionResponder<SocketAddr>>,
55    },
56    Assigned {
57        addr: SocketAddr,
58    },
59}
60
61impl Default for AddrState {
62    fn default() -> Self {
63        Self::NotAssignedYet {
64            listeners: Vec::new(),
65        }
66    }
67}
68
69#[derive(From)]
70pub(super) struct AddrReady {
71    addr: SocketAddr,
72}
73
74impl Action for AddrReady {}
75
76#[async_trait]
77impl ActionHandler<AddrReady> for HttpServer {
78    async fn handle(&mut self, msg: AddrReady, _ctx: &mut Context<Self>) -> Result<(), Error> {
79        let addr = msg.addr;
80        let mut new_state = AddrState::Assigned { addr };
81        std::mem::swap(&mut self.addr_state, &mut new_state);
82        if let AddrState::NotAssignedYet { listeners } = new_state {
83            for listener in listeners {
84                if let Err(err) = listener.send(Ok(addr)) {
85                    log::error!(target: &self.log_target, "Can't send address result {:?} to the listener.", err);
86                }
87            }
88        }
89        Ok(())
90    }
91}