meio_connect/server/
bind.rs1use 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
14pub struct WaitForAddress;
19
20impl Interaction for WaitForAddress {
21 type Output = SocketAddr;
22}
23
24impl HttpServerLink {
25 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}