1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::error::{Error, Result};
use crate::events::error_event::{ErrorEventData, ERROR_EVENT_NAME};
use crate::events::event::Event;
use crate::events::event_handler::EventHandler;
use crate::ipc::client::IPCClient;
use crate::ipc::context::{Context, PooledContext, ReplyListeners};
use crate::ipc::server::IPCServer;
use crate::namespaces::builder::NamespaceBuilder;
use crate::namespaces::namespace::Namespace;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::RwLock;
use typemap_rev::{TypeMap, TypeMapKey};

/// A builder for the IPC server or client.
/// ```no_run
///use typemap_rev::TypeMapKey;
/// use rmp_ipc::IPCBuilder;
///
/// struct CustomKey;
///
/// impl TypeMapKey for CustomKey {
///     type Value = String;
/// }
///
///# async fn a() {
/// IPCBuilder::new()
///     .address("127.0.0.1:2020")
///    // register callback
///     .on("ping", |_ctx, _event| Box::pin(async move {
///         println!("Received ping event.");
///         Ok(())
///     }))
///     // register a namespace    
///     .namespace("namespace")
///     .on("namespace-event", |_ctx, _event| Box::pin(async move {
///         println!("Namespace event.");
///         Ok(())
///     }))
///     .build()
///     // add context shared data
///     .insert::<CustomKey>("Hello World".to_string())
///     // can also be build_client which would return an emitter for events
///     .build_server().await.unwrap();
///# }
/// ```
pub struct IPCBuilder {
    handler: EventHandler,
    address: Option<String>,
    namespaces: HashMap<String, Namespace>,
    data: TypeMap,
}

impl IPCBuilder {
    pub fn new() -> Self {
        let mut handler = EventHandler::new();
        handler.on(ERROR_EVENT_NAME, |_, event| {
            Box::pin(async move {
                let error_data = event.data::<ErrorEventData>()?;
                tracing::warn!(error_data.code);
                tracing::warn!("error_data.message = '{}'", error_data.message);

                Ok(())
            })
        });
        Self {
            handler,
            address: None,
            namespaces: HashMap::new(),
            data: TypeMap::new(),
        }
    }

    /// Adds globally shared data
    pub fn insert<K: TypeMapKey>(mut self, value: K::Value) -> Self {
        self.data.insert::<K>(value);

        self
    }

    /// Adds an event callback
    pub fn on<F: 'static>(mut self, event: &str, callback: F) -> Self
    where
        F: for<'a> Fn(
                &'a Context,
                Event,
            ) -> Pin<Box<(dyn Future<Output = Result<()>> + Send + 'a)>>
            + Send
            + Sync,
    {
        self.handler.on(event, callback);

        self
    }

    /// Adds the address to connect to
    pub fn address<S: ToString>(mut self, address: S) -> Self {
        self.address = Some(address.to_string());

        self
    }

    /// Adds a namespace
    pub fn namespace<S: ToString>(self, name: S) -> NamespaceBuilder {
        NamespaceBuilder::new(self, name.to_string())
    }

    /// Adds a namespace to the ipc server
    pub fn add_namespace(mut self, namespace: Namespace) -> Self {
        self.namespaces
            .insert(namespace.name().to_owned(), namespace);

        self
    }

    /// Builds an ipc server
    #[tracing::instrument(skip(self))]
    pub async fn build_server(self) -> Result<()> {
        self.validate()?;
        let server = IPCServer {
            namespaces: self.namespaces,
            handler: self.handler,
            data: self.data,
        };
        server.start(&self.address.unwrap()).await?;

        Ok(())
    }

    /// Builds an ipc client
    #[tracing::instrument(skip(self))]
    pub async fn build_client(self) -> Result<Context> {
        self.validate()?;
        let data = Arc::new(RwLock::new(self.data));
        let reply_listeners = ReplyListeners::default();
        let client = IPCClient {
            namespaces: self.namespaces,
            handler: self.handler,
            data,
            reply_listeners,
        };

        let ctx = client.connect(&self.address.unwrap()).await?;

        Ok(ctx)
    }

    /// Builds a pooled IPC client
    /// This causes the builder to actually create `pool_size` clients and
    /// return a [crate::context::PooledContext] that allows one to [crate::context::PooledContext::acquire] a single context
    /// to emit events.
    #[tracing::instrument(skip(self))]
    pub async fn build_pooled_client(self, pool_size: usize) -> Result<PooledContext> {
        if pool_size == 0 {
            Error::BuildError("Pool size must be greater than 0".to_string());
        }
        self.validate()?;
        let data = Arc::new(RwLock::new(self.data));
        let mut contexts = Vec::new();
        let address = self.address.unwrap();
        let reply_listeners = ReplyListeners::default();

        for _ in 0..pool_size {
            let client = IPCClient {
                namespaces: self.namespaces.clone(),
                handler: self.handler.clone(),
                data: Arc::clone(&data),
                reply_listeners: Arc::clone(&reply_listeners),
            };

            let ctx = client.connect(&address).await?;
            contexts.push(ctx);
        }

        Ok(PooledContext::new(contexts))
    }

    /// Validates that all required fields have been provided
    #[tracing::instrument(skip(self))]
    fn validate(&self) -> Result<()> {
        if self.address.is_none() {
            Err(Error::BuildError("Missing Address".to_string()))
        } else {
            Ok(())
        }
    }
}