├── .gitignore ├── images ├── title.png ├── library-schema.png └── no-hosting-server.png ├── src ├── services.rs ├── connectors.rs ├── lib.rs ├── services │ ├── echo.rs │ ├── public_ip.rs │ ├── alarm.rs │ └── process.rs ├── connectors │ ├── stdout.rs │ ├── mpsc.rs │ ├── stdin.rs │ ├── smtp.rs │ └── imap.rs ├── util.rs ├── channel.rs ├── interface.rs ├── message.rs └── engine.rs ├── examples ├── stdio.rs ├── stdin_to_email.rs ├── email_to_stdout.rs └── email_server.rs ├── Cargo.toml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /images/title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lemunozm/service-io/HEAD/images/title.png -------------------------------------------------------------------------------- /images/library-schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lemunozm/service-io/HEAD/images/library-schema.png -------------------------------------------------------------------------------- /images/no-hosting-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lemunozm/service-io/HEAD/images/no-hosting-server.png -------------------------------------------------------------------------------- /src/services.rs: -------------------------------------------------------------------------------- 1 | //! Default services comming with `service-io`. 2 | 3 | mod echo; 4 | pub use echo::Echo; 5 | 6 | mod alarm; 7 | pub use alarm::Alarm; 8 | 9 | mod public_ip; 10 | pub use self::public_ip::PublicIp; 11 | 12 | mod process; 13 | pub use process::Process; 14 | -------------------------------------------------------------------------------- /src/connectors.rs: -------------------------------------------------------------------------------- 1 | //! Default connectors comming with `service-io`. 2 | 3 | mod mpsc; 4 | 5 | mod stdin; 6 | pub use stdin::UserStdin; 7 | 8 | mod stdout; 9 | pub use stdout::DebugStdout; 10 | 11 | mod imap; 12 | pub use self::imap::ImapClient; 13 | 14 | mod smtp; 15 | pub use smtp::SmtpClient; 16 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Check the [Github README](https://github.com/lemunozm/service-io), 2 | //! to see an overview of the library. 3 | 4 | #[cfg(doctest)] 5 | // Tells rustdoc where is the README to compile and test the rust code found there 6 | doc_comment::doctest!("../README.md"); 7 | 8 | pub mod channel; 9 | pub mod interface; 10 | pub mod message; 11 | 12 | pub mod engine; 13 | 14 | pub mod connectors; 15 | pub mod services; 16 | 17 | pub mod util; 18 | -------------------------------------------------------------------------------- /examples/stdio.rs: -------------------------------------------------------------------------------- 1 | use service_io::connectors::{DebugStdout, UserStdin}; 2 | use service_io::engine::Engine; 3 | use service_io::services::{Alarm, Echo, Process, PublicIp}; 4 | 5 | #[tokio::main] 6 | async fn main() { 7 | Engine::default() 8 | .input(UserStdin("stdin-user")) 9 | .output(DebugStdout) 10 | .add_service("s-echo", Echo) 11 | .add_service("s-public-ip", PublicIp) 12 | .add_service("s-alarm", Alarm) 13 | .add_service("s-process", Process) 14 | .run() 15 | .await; 16 | } 17 | -------------------------------------------------------------------------------- /src/services/echo.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver, Sender}; 2 | use crate::interface::Service; 3 | 4 | use async_trait::async_trait; 5 | 6 | /// Returns the same received message without modifications 7 | pub struct Echo; 8 | 9 | #[async_trait] 10 | impl Service for Echo { 11 | async fn run( 12 | self: Box, 13 | mut input: Receiver, 14 | output: Sender, 15 | ) -> Result<(), ClosedChannel> { 16 | loop { 17 | let message = input.recv().await?; 18 | output.send(message).await?; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/connectors/stdout.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver}; 2 | use crate::interface::OutputConnector; 3 | 4 | use tokio::io::AsyncWriteExt; 5 | 6 | use async_trait::async_trait; 7 | 8 | /// Print the message to the stdout. 9 | pub struct DebugStdout; 10 | 11 | #[async_trait] 12 | impl OutputConnector for DebugStdout { 13 | async fn run(mut self: Box, mut receiver: Receiver) -> Result<(), ClosedChannel> { 14 | loop { 15 | let message = receiver.recv().await?; 16 | tokio::io::stdout() 17 | .write_all(format!("{:#?}\n", message).as_bytes()) 18 | .await 19 | .unwrap(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/connectors/mpsc.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver, Sender}; 2 | use crate::interface::{InputConnector, OutputConnector}; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | use tokio::sync::mpsc; 7 | 8 | #[async_trait] 9 | impl InputConnector for mpsc::Receiver { 10 | async fn run(mut self: Box, sender: Sender) -> Result<(), ClosedChannel> { 11 | loop { 12 | match self.recv().await { 13 | Some(message) => sender.send(message).await?, 14 | None => break Ok(()), 15 | }; 16 | } 17 | } 18 | } 19 | 20 | #[async_trait] 21 | impl OutputConnector for mpsc::Sender { 22 | async fn run(self: Box, mut receiver: Receiver) -> Result<(), ClosedChannel> { 23 | loop { 24 | let message = receiver.recv().await?; 25 | if self.send(message).await.is_err() { 26 | break Ok(()); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/services/public_ip.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver, Sender}; 2 | use crate::interface::Service; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | 7 | /// Serve the public IP of the server. 8 | /// No args are required. 9 | pub struct PublicIp; 10 | 11 | #[async_trait] 12 | impl Service for PublicIp { 13 | async fn run( 14 | self: Box, 15 | mut input: Receiver, 16 | output: Sender, 17 | ) -> Result<(), ClosedChannel> { 18 | loop { 19 | let request = input.recv().await?; 20 | let response = match public_ip::addr().await { 21 | Some(ip_addr) => Message::response(&request).body(format!("{}", ip_addr)), 22 | None => { 23 | let msg = "Failed to get IP address"; 24 | log::error!("{}", msg); 25 | Message::response(&request).args(["error"]).body(msg) 26 | } 27 | }; 28 | output.send(response).await?; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "service-io" 3 | version = "0.1.0" 4 | authors = ["lemunozm "] 5 | edition = "2021" 6 | readme = "README.md" 7 | license = "Apache-2.0" 8 | description = "Build your service-server fast, easy (and without hosting!)" 9 | homepage = "https://github.com/lemunozm/service-io/" 10 | repository = "https://github.com/lemunozm/service-io/" 11 | keywords = ["email", "message", "service", "server", "async"] 12 | categories = ["asynchronous", "email"] 13 | 14 | [badges] 15 | maintenance = { status = "actively-developed" } 16 | 17 | [dependencies] 18 | tokio = { version = "1", features = ["rt", "macros", "sync", "time", "io-std", "io-util", "rt-multi-thread"] } 19 | async-trait = "0.1" 20 | imap = "2.4" 21 | native-tls = "0.2.8" 22 | mailparse = "0.13" 23 | log = "0.4" 24 | lettre = { version = "0.10.0-rc.4", features = ["smtp-transport", "tokio1-native-tls", "builder"] } 25 | public-ip = "0.2" 26 | 27 | [dev-dependencies] 28 | clap = { version = "3.1", features = ["derive", "cargo"] } 29 | clap-verbosity-flag = "1.0" 30 | fern = "0.6" 31 | chrono = "0.4" 32 | doc-comment = "0.3" 33 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | //! Generic utilities 2 | 3 | /// Transform a parameter value into an Option. 4 | /// # Example 5 | /// ```rust 6 | /// use service_io::util::IntoOption; 7 | /// 8 | /// fn foo(param: impl IntoOption) -> Option { 9 | /// return param.into_some(); 10 | /// } 11 | /// 12 | /// let expected = Some(String::from("data")); 13 | /// 14 | /// assert_eq!(expected, foo(Some(String::from("data")))); 15 | /// assert_eq!(expected, foo(String::from("data"))); 16 | /// assert_eq!(expected, foo(Some("data"))); 17 | /// assert_eq!(expected, foo("data")); 18 | /// ``` 19 | pub trait IntoOption { 20 | fn into_some(self) -> Option; 21 | } 22 | 23 | impl IntoOption for T { 24 | fn into_some(self) -> Option { 25 | Some(self) 26 | } 27 | } 28 | 29 | impl IntoOption for Option { 30 | fn into_some(self) -> Option { 31 | self 32 | } 33 | } 34 | 35 | impl<'a> IntoOption for &'a str { 36 | fn into_some(self) -> Option { 37 | Some(self.into()) 38 | } 39 | } 40 | 41 | impl<'a> IntoOption for Option<&'a str> { 42 | fn into_some(self) -> Option { 43 | self.map(|s| s.into()) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /examples/stdin_to_email.rs: -------------------------------------------------------------------------------- 1 | use service_io::connectors::{SmtpClient, UserStdin}; 2 | use service_io::engine::Engine; 3 | use service_io::services::{Alarm, Echo, Process, PublicIp}; 4 | 5 | use clap::Parser; 6 | 7 | /// Creates an email using the first line read by the stdin 8 | /// and send it to the same address as configured by smtp 9 | #[derive(Parser, Debug)] 10 | #[clap()] 11 | struct Cli { 12 | /// Example: smtp.gmail.com 13 | #[clap(long)] 14 | smtp_domain: String, 15 | 16 | #[clap(long)] 17 | email: String, 18 | 19 | #[clap(long)] 20 | password: String, 21 | 22 | /// Alias name for 'From' address 23 | #[clap(long)] 24 | sender_name: Option, 25 | } 26 | 27 | #[tokio::main] 28 | async fn main() { 29 | let cli = Cli::parse(); 30 | 31 | Engine::default() 32 | .input(UserStdin(cli.email.clone())) 33 | .output( 34 | SmtpClient::default() 35 | .domain(cli.smtp_domain) 36 | .email(cli.email) 37 | .password(cli.password) 38 | .sender_name(cli.sender_name), 39 | ) 40 | .add_service("s-echo", Echo) 41 | .add_service("s-alarm", Alarm) 42 | .add_service("s-public-ip", PublicIp) 43 | .add_service("s-process", Process) 44 | .run() 45 | .await; 46 | } 47 | -------------------------------------------------------------------------------- /examples/email_to_stdout.rs: -------------------------------------------------------------------------------- 1 | use service_io::connectors::{DebugStdout, ImapClient}; 2 | use service_io::engine::Engine; 3 | use service_io::message::util; 4 | use service_io::services::{Alarm, Echo, Process, PublicIp}; 5 | 6 | use clap::Parser; 7 | 8 | use std::time::Duration; 9 | 10 | /// Reads emails by imap and show it by the stdout 11 | #[derive(Parser, Debug)] 12 | #[clap()] 13 | struct Cli { 14 | /// Example: imap.gmail.com 15 | #[clap(long)] 16 | imap_domain: String, 17 | 18 | #[clap(long)] 19 | email: String, 20 | 21 | #[clap(long)] 22 | password: String, 23 | 24 | /// Waiting time (in secs) to make request to the imap server 25 | #[clap(long, default_value = "3")] 26 | polling_time: u64, 27 | } 28 | 29 | #[tokio::main] 30 | async fn main() { 31 | let cli = Cli::parse(); 32 | 33 | Engine::default() 34 | .input( 35 | ImapClient::default() 36 | .domain(cli.imap_domain) 37 | .email(cli.email) 38 | .password(cli.password) 39 | .polling_time(Duration::from_secs(cli.polling_time)), 40 | ) 41 | .output(DebugStdout) 42 | .map_input(util::service_name_first_char_to_lowercase) 43 | .add_service("s-echo", Echo) 44 | .add_service("s-public-ip", PublicIp) 45 | .add_service("s-alarm", Alarm) 46 | .add_service("s-process", Process) 47 | .run() 48 | .await; 49 | } 50 | -------------------------------------------------------------------------------- /src/connectors/stdin.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Sender}; 2 | use crate::interface::InputConnector; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | 7 | use std::io::{self, BufRead}; 8 | 9 | /// Reads a line from the stdin. 10 | /// The service accepts a parameter that corresponds with the user. 11 | /// The first word of the line is interpreted as the service name. 12 | /// The following spaced-separated words are the arguments. 13 | /// Neither body nor attach fields are populated. 14 | pub struct UserStdin(pub N); 15 | 16 | #[async_trait] 17 | impl + Send> InputConnector for UserStdin { 18 | async fn run(mut self: Box, sender: Sender) -> Result<(), ClosedChannel> { 19 | let user_name = self.0.into(); 20 | loop { 21 | let line = 22 | tokio::task::spawn_blocking(|| io::stdin().lock().lines().next().unwrap().unwrap()) 23 | .await 24 | .unwrap(); 25 | 26 | let mut words = line.split_whitespace(); 27 | if let Some(service) = words.next() { 28 | let message = Message { 29 | user: user_name.clone(), 30 | service_name: service.into(), 31 | args: words.map(|s| s.into()).collect(), 32 | ..Default::default() 33 | }; 34 | 35 | sender.send(message).await?; 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/services/alarm.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver, Sender}; 2 | use crate::interface::Service; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | use tokio::time; 7 | 8 | use std::time::Duration; 9 | 10 | /// Allow to create alarms given a name and a time in minutes. 11 | /// Once the time is over, a response is generated. 12 | pub struct Alarm; 13 | 14 | #[async_trait] 15 | impl Service for Alarm { 16 | async fn run( 17 | self: Box, 18 | mut input: Receiver, 19 | output: Sender, 20 | ) -> Result<(), ClosedChannel> { 21 | loop { 22 | let request = input.recv().await?; 23 | let args = request.args.iter().map(|s| s.as_str()).collect::>(); 24 | 25 | if let [name, minutes] = args.as_slice() { 26 | if let Ok(minutes) = minutes.parse::() { 27 | tokio::spawn({ 28 | let output = output.clone(); 29 | let response = Message::response(&request).args([*name]); 30 | async move { 31 | time::sleep(Duration::from_secs(minutes * 60)).await; 32 | output.send(response).await.ok(); 33 | } 34 | }); 35 | continue; 36 | } 37 | } 38 | 39 | let response = Message::response(&request) 40 | .args(["format error"]) 41 | .body("Expected args: "); 42 | 43 | output.send(response).await?; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/channel.rs: -------------------------------------------------------------------------------- 1 | //! Channels used to connect inputs with services and services with outputs. 2 | //! It basically wraps a [`tokio::sync::mpsc`] for easy management inside input/output/services 3 | //! implementations. 4 | 5 | use crate::message::Message; 6 | 7 | use tokio::sync::mpsc; 8 | 9 | /// Error indicating that the channel was closed. 10 | #[derive(Debug)] 11 | pub struct ClosedChannel; 12 | 13 | /// Sender side of the channel. 14 | /// It basically wraps a [`tokio::sync::mpsc::Sender`] for easy management inside input/output/services 15 | /// implementations. 16 | #[derive(Clone)] 17 | pub struct Sender(pub(crate) mpsc::Sender); 18 | 19 | impl Sender { 20 | /// Send asynchronously a message. 21 | /// 22 | /// This method is a wrapper over [`tokio::sync::mpsc::Sender::send()`] with an specific 23 | /// mapped error. 24 | pub async fn send(&self, message: Message) -> Result<(), ClosedChannel> { 25 | self.0.send(message).await.map_err(|_| ClosedChannel) 26 | } 27 | 28 | /// Send a message. 29 | /// 30 | /// This method is a wrapper over [`tokio::sync::mpsc::Sender::blocking_send()`] with an 31 | /// specific mapped error. 32 | pub fn blocking_send(&self, message: Message) -> Result<(), ClosedChannel> { 33 | self.0.blocking_send(message).map_err(|_| ClosedChannel) 34 | } 35 | } 36 | 37 | /// Receiver side of the channel. 38 | /// It basically wraps a [`tokio::sync::mpsc::Receiver`] for easy management inside input/output/services 39 | /// implementations. 40 | pub struct Receiver(pub(crate) mpsc::Receiver); 41 | 42 | impl Receiver { 43 | /// Receive asynchronously a message. 44 | /// 45 | /// This method is a wrapper over [`tokio::sync::mpsc::Receiver::recv()`] with an specific 46 | /// mapped error. 47 | pub async fn recv(&mut self) -> Result { 48 | self.0.recv().await.ok_or(ClosedChannel) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/services/process.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver, Sender}; 2 | use crate::interface::Service; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | use tokio::process::Command; 7 | 8 | /// Allow to run any process. 9 | /// Each arg of the message is interpreted as a process arg, being arg0 the name of the process. 10 | /// The stdout of the process once finalized will be returned as a message body. 11 | pub struct Process; 12 | 13 | #[async_trait] 14 | impl Service for Process { 15 | async fn run( 16 | self: Box, 17 | mut input: Receiver, 18 | output: Sender, 19 | ) -> Result<(), ClosedChannel> { 20 | loop { 21 | let request = input.recv().await?; 22 | match request.args.get(0) { 23 | Some(_) => spawn_process(request, output.clone()), 24 | None => { 25 | let response = Message::response(&request) 26 | .args(["format error"]) 27 | .body(format!("You need to specify a process to run")); 28 | 29 | output.send(response).await?; 30 | } 31 | } 32 | } 33 | } 34 | } 35 | 36 | fn spawn_process(request: Message, output: Sender) { 37 | let mut program_args = request.args.iter(); 38 | let arg0 = program_args.next().unwrap(); 39 | let child = Command::new(arg0).args(program_args).output(); 40 | 41 | tokio::spawn({ 42 | let output = output.clone(); 43 | async move { 44 | let cmd_str = request.args.join(" "); 45 | if let Ok(child_output) = child.await { 46 | let response = Message::response(&request) 47 | .args([format!("Terminated ({}): {}", child_output.status, cmd_str)]) 48 | .body(std::str::from_utf8(&child_output.stdout).unwrap_or("[binary]")); 49 | 50 | output.send(response).await.ok(); 51 | } else { 52 | let response = Message::response(&request) 53 | .args(["error"]) 54 | .body(format!("Error while running: {}", cmd_str)); 55 | 56 | output.send(response).await.ok(); 57 | } 58 | } 59 | }); 60 | } 61 | -------------------------------------------------------------------------------- /examples/email_server.rs: -------------------------------------------------------------------------------- 1 | use service_io::connectors::{ImapClient, SmtpClient}; 2 | use service_io::engine::Engine; 3 | use service_io::message::util; 4 | use service_io::services::{Alarm, Echo, Process, PublicIp}; 5 | 6 | use clap::Parser; 7 | 8 | use std::time::Duration; 9 | 10 | /// Emulate a server: reads emails by imap as requests and send emails by stmp as responses. 11 | #[derive(Parser, Debug)] 12 | #[clap()] 13 | struct Cli { 14 | /// Example: imap.gmail.com 15 | #[clap(long)] 16 | imap_domain: String, 17 | 18 | /// Example: smtp.gmail.com 19 | #[clap(long)] 20 | smtp_domain: String, 21 | 22 | #[clap(long)] 23 | email: String, 24 | 25 | #[clap(long)] 26 | password: String, 27 | 28 | /// Waiting time (in secs) to make request to the imap server 29 | #[clap(long, default_value = "3")] 30 | polling_time: u64, 31 | 32 | /// Alias name for 'From' address 33 | #[clap(long)] 34 | sender_name: Option, 35 | 36 | #[clap(flatten)] 37 | verbose: clap_verbosity_flag::Verbosity, 38 | } 39 | 40 | #[tokio::main] 41 | async fn main() { 42 | let cli = Cli::parse(); 43 | 44 | configure_logger(cli.verbose.log_level_filter()).unwrap(); 45 | 46 | Engine::default() 47 | .input( 48 | ImapClient::default() 49 | .domain(cli.imap_domain) 50 | .email(cli.email.clone()) 51 | .password(cli.password.clone()) 52 | .polling_time(Duration::from_secs(cli.polling_time)), 53 | ) 54 | .output( 55 | SmtpClient::default() 56 | .domain(cli.smtp_domain) 57 | .email(cli.email) 58 | .password(cli.password) 59 | .sender_name(cli.sender_name), 60 | ) 61 | .map_input(util::service_name_first_char_to_lowercase) 62 | .add_service("s-echo", Echo) 63 | .add_service("s-alarm", Alarm) 64 | .add_service("s-public-ip", PublicIp) 65 | .add_service("s-process", Process) 66 | .run() 67 | .await; 68 | } 69 | 70 | fn configure_logger(level_filter: log::LevelFilter) -> Result<(), log::SetLoggerError> { 71 | let crate_filter = clap::crate_name!().replace("-", "_"); 72 | fern::Dispatch::new() 73 | .level(level_filter) 74 | .filter(move |metadata| metadata.target().starts_with(&crate_filter)) 75 | .format(move |out, message, record| { 76 | out.finish(format_args!( 77 | "[{}] [{}] {}", 78 | chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(), 79 | record.level(), 80 | message 81 | )) 82 | }) 83 | .chain(std::io::stdout()) 84 | .apply() 85 | } 86 | -------------------------------------------------------------------------------- /src/connectors/smtp.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Receiver}; 2 | use crate::interface::OutputConnector; 3 | use crate::message::Message; 4 | use crate::util::IntoOption; 5 | 6 | use lettre::message::{header::ContentType, Attachment, Mailbox, MultiPart, SinglePart}; 7 | use lettre::transport::smtp::authentication::Credentials; 8 | use lettre::{Address, AsyncSmtpTransport, AsyncTransport, Tokio1Executor}; 9 | 10 | use async_trait::async_trait; 11 | 12 | /// Output connector that acts as a SMTP client 13 | /// The service sends emails to the SMTP server. 14 | /// The service name is added as first word of the subject following by space. 15 | /// The arguments are added as a words to the subject separated by spaces. 16 | #[derive(Default, Clone)] 17 | pub struct SmtpClient { 18 | smtp_domain: String, 19 | email: String, 20 | password: String, 21 | sender_name: Option, 22 | } 23 | 24 | impl SmtpClient { 25 | pub fn domain(mut self, value: impl Into) -> Self { 26 | self.smtp_domain = value.into(); 27 | self 28 | } 29 | 30 | pub fn email(mut self, value: impl Into) -> Self { 31 | self.email = value.into(); 32 | self 33 | } 34 | 35 | pub fn password(mut self, value: impl Into) -> Self { 36 | self.password = value.into(); 37 | self 38 | } 39 | 40 | /// Name alias for the email 41 | pub fn sender_name(mut self, value: impl IntoOption) -> Self { 42 | self.sender_name = value.into_some(); 43 | self 44 | } 45 | } 46 | 47 | #[async_trait] 48 | impl OutputConnector for SmtpClient { 49 | async fn run(mut self: Box, mut receiver: Receiver) -> Result<(), ClosedChannel> { 50 | let address = self.email.parse::
().unwrap(); 51 | let user = address.user().to_string(); 52 | let credentials = Credentials::new(user, self.password.into()); 53 | 54 | let from = Mailbox::new(self.sender_name, address); 55 | let mailer = AsyncSmtpTransport::::relay(self.smtp_domain.as_ref()) 56 | .unwrap() 57 | .credentials(credentials) 58 | .build(); 59 | 60 | loop { 61 | let message = receiver.recv().await?; 62 | if let Some(email) = message_to_email(message, from.clone()) { 63 | if let Err(err) = mailer.send(email).await { 64 | log::error!("Sending error: {}", err); 65 | } 66 | } 67 | } 68 | } 69 | } 70 | 71 | fn message_to_email(message: Message, from: Mailbox) -> Option { 72 | let to_address = message 73 | .user 74 | .parse::
() 75 | .map_err(|err| log::error!("{}", err)) 76 | .ok()?; 77 | 78 | let single_parts = message 79 | .attached_data 80 | .into_iter() 81 | .map(|(filename, filebody)| { 82 | Some( 83 | Attachment::new(filename).body( 84 | filebody, 85 | ContentType::parse("application/octet-stream") 86 | .map_err(|err| log::error!("{}", err)) 87 | .ok()?, 88 | ), 89 | ) 90 | }) 91 | .collect::>(); 92 | 93 | let mut multipart = MultiPart::alternative().singlepart(SinglePart::plain(message.body)); 94 | for single in single_parts { 95 | multipart = multipart.singlepart(single?); 96 | } 97 | 98 | let subject = message.args.join(" "); 99 | 100 | lettre::Message::builder() 101 | .from(from) 102 | .to(Mailbox::new(None, to_address)) 103 | .subject(format!("{} {}", message.service_name, subject)) 104 | .multipart(multipart) 105 | .map_err(|err| log::error!("{}", err)) 106 | .ok() 107 | } 108 | -------------------------------------------------------------------------------- /src/interface.rs: -------------------------------------------------------------------------------- 1 | //! Traits for building [`InputConnector`], [`OutputConnector`], and [`Service`] 2 | //! 3 | //! [`InputConnector`]: interface::InputConnector 4 | //! [`OutputConnector`]: interface::OutputConnector 5 | //! [`Service`]: interface::Service 6 | 7 | use crate::channel::{ClosedChannel, Receiver, Sender}; 8 | 9 | use async_trait::async_trait; 10 | 11 | /// Implement an input connector. 12 | /// An input connector is in change of creating [`Message`] and sending asynchronously 13 | /// to the services. 14 | /// 15 | /// If the sender return a [`ClosedChannel`] error, it is expected to propagate this error. 16 | /// 17 | /// See default implementations in [`connectors`] 18 | /// 19 | /// Do not forget to add the [`mod@async_trait`] crate when implement this trait 20 | /// 21 | /// [`connectors`]: crate::connectors 22 | /// [`Message`]: crate::message::Message 23 | /// 24 | /// # Example 25 | /// ```rust 26 | /// use service_io::interface::{InputConnector}; 27 | /// use service_io::channel::{ClosedChannel, Sender}; 28 | /// use service_io::message::{Message}; 29 | /// 30 | /// use async_trait::async_trait; 31 | /// 32 | /// struct MyInput; 33 | /// 34 | /// #[async_trait] 35 | /// impl InputConnector for MyInput { 36 | /// async fn run(self: Box, sender: Sender) -> Result<(), ClosedChannel> { 37 | /// // Load phase 38 | /// // ... 39 | /// loop { 40 | /// // Get the message from your implementation 41 | /// // ... 42 | /// let message = Message::default(); 43 | /// 44 | /// // Send the message to the service 45 | /// sender.send(message).await?; 46 | /// } 47 | /// } 48 | /// } 49 | /// ``` 50 | #[async_trait] 51 | pub trait InputConnector { 52 | async fn run(self: Box, sender: Sender) -> Result<(), ClosedChannel>; 53 | } 54 | 55 | /// Implement an output connector. 56 | /// An output connector is waiting asynchronously for messages comming from the services 57 | /// and deliver them. 58 | /// 59 | /// If the receiver return a [`ClosedChannel`] error, it is expected to propagate this error. 60 | /// 61 | /// See default implementations in [`connectors`] 62 | /// 63 | /// Do not forget to add the [`mod@async_trait`] crate when implement this trait 64 | /// 65 | /// [`connectors`]: crate::connectors 66 | /// [`Message`]: crate::message::Message 67 | /// 68 | /// # Example 69 | /// ```rust 70 | /// 71 | /// use service_io::interface::{OutputConnector}; 72 | /// use service_io::channel::{ClosedChannel, Receiver}; 73 | /// 74 | /// use async_trait::async_trait; 75 | /// 76 | /// struct MyOutput; 77 | /// 78 | /// #[async_trait] 79 | /// impl OutputConnector for MyOutput { 80 | /// async fn run(self: Box, mut receiver: Receiver) -> Result<(), ClosedChannel> { 81 | /// // Load phase 82 | /// // ... 83 | /// loop { 84 | /// // Get the message from the service... 85 | /// let message = receiver.recv().await?; 86 | /// 87 | /// // Do whatever your output impl must do. i.e send the message by email 88 | /// // ... 89 | /// } 90 | /// } 91 | /// } 92 | /// ``` 93 | #[async_trait] 94 | pub trait OutputConnector { 95 | async fn run(self: Box, receiver: Receiver) -> Result<(), ClosedChannel>; 96 | } 97 | 98 | /// Implement a service. 99 | /// A Service is an entity that processes input messages asynchronously and send output messages 100 | /// asynchronously. 101 | /// 102 | /// If both, sender or receiver return a [`ClosedChannel`] error, 103 | /// it is expected to propagate this error. 104 | /// 105 | /// See default implementations in [`services`] 106 | /// 107 | /// Do not forget to add the [`mod@async_trait`] crate when implement this trait 108 | /// 109 | /// [`services`]: crate::services 110 | /// 111 | /// # Example 112 | /// ```rust 113 | /// use service_io::interface::{Service}; 114 | /// use service_io::channel::{ClosedChannel, Receiver, Sender}; 115 | /// 116 | /// use async_trait::async_trait; 117 | /// 118 | /// struct MyService; 119 | /// 120 | /// #[async_trait] 121 | /// impl Service for MyService { 122 | /// async fn run(self: Box, mut input: Receiver, output: Sender) -> Result<(), ClosedChannel> { 123 | /// // Load phase 124 | /// // ... 125 | /// loop { 126 | /// // Get the message from the input connector. 127 | /// let message = input.recv().await?; 128 | /// 129 | /// // Do whatever your service impl must do. 130 | /// // ... 131 | /// 132 | /// // Send the message to the output connector. 133 | /// output.send(message).await?; 134 | /// } 135 | /// } 136 | /// } 137 | /// ``` 138 | #[async_trait] 139 | pub trait Service { 140 | async fn run(self: Box, input: Receiver, output: Sender) -> Result<(), ClosedChannel>; 141 | } 142 | -------------------------------------------------------------------------------- /src/message.rs: -------------------------------------------------------------------------------- 1 | //! Common data shared among input/output/services and utilities related to it. 2 | 3 | use std::collections::HashMap; 4 | 5 | /// Common data shared among input/output/services. 6 | /// This is the language `service-io` talk. 7 | /// Each input/output/service understand this structure. 8 | /// 9 | /// # Example 10 | /// ```rust 11 | /// use service_io::message::Message; 12 | /// 13 | /// let request = Message::default() 14 | /// .user("user_01") 15 | /// .service_name("my_service") 16 | /// .args(["arg0", "arg1", "arg2", "this is arg3"]) 17 | /// .body("body of the message") 18 | /// .attach([ 19 | /// ("file1.txt", b"content data".to_vec()), 20 | /// ("file2.txt", b"1234".to_vec()) 21 | /// ]); 22 | /// ``` 23 | /// 24 | #[derive(Default, Debug, Clone, PartialEq)] 25 | pub struct Message { 26 | /// The user this message is related to. 27 | /// If the message is in the input side, this user means the originator of the message. 28 | /// If the message is in the output side, this user means the recipient of the message. 29 | pub user: String, 30 | 31 | /// The service name this message going to/come from. 32 | /// The value of this field should match to any name used for register services. 33 | /// 34 | /// See also: [`Engine::add_service()`] 35 | /// 36 | /// [`Engine::add_service()`]: crate::engine::Engine::add_service() 37 | pub service_name: String, 38 | 39 | /// Arguments of the message. 40 | /// Each service implementation will understand these values in their own way. 41 | pub args: Vec, 42 | 43 | /// Main body of the message. 44 | /// Each service implementation will understand this value in their own way. 45 | pub body: String, 46 | 47 | /// Attached content of the message. 48 | /// Each service implementation will understand these values in their own way. 49 | pub attached_data: HashMap>, 50 | } 51 | 52 | impl Message { 53 | /// Sugar to perform a response of a received message. 54 | /// Creates an empty message with same [`Message::user`] 55 | /// and [`Message::service_name`] as the passed message. 56 | /// 57 | /// # Example 58 | /// ```rust 59 | /// use service_io::message::Message; 60 | /// 61 | /// let request = Message::default() 62 | /// .user("user_01") 63 | /// .service_name("my_service") 64 | /// .body("1234"); 65 | /// 66 | /// let response = Message::response(&request); 67 | /// 68 | /// // Name and service_name are copied 69 | /// assert_eq!(request.user, response.user); 70 | /// assert_eq!(request.service_name, response.service_name); 71 | /// 72 | /// // But other fields as body are not copied. 73 | /// assert_ne!(request.body, response.body); 74 | /// ``` 75 | pub fn response(message: &Message) -> Message { 76 | Message { 77 | user: message.user.clone(), 78 | service_name: message.service_name.clone(), 79 | ..Default::default() 80 | } 81 | } 82 | 83 | /// Set a user for the message 84 | pub fn user(mut self, user: impl Into) -> Self { 85 | self.user = user.into(); 86 | self 87 | } 88 | 89 | /// Set a service name for the message 90 | pub fn service_name(mut self, service_name: impl Into) -> Self { 91 | self.service_name = service_name.into(); 92 | self 93 | } 94 | 95 | /// Set args for the message 96 | pub fn args>(mut self, args: impl IntoIterator) -> Self { 97 | self.args = args.into_iter().map(|s| s.into()).collect(); 98 | self 99 | } 100 | 101 | /// Set a body for the message 102 | pub fn body(mut self, body: impl Into) -> Self { 103 | self.body = body.into(); 104 | self 105 | } 106 | 107 | /// Set attached data for the message 108 | pub fn attach>( 109 | mut self, 110 | attached: impl IntoIterator)>, 111 | ) -> Self { 112 | self.attached_data = attached 113 | .into_iter() 114 | .map(|(name, data)| (name.into(), data)) 115 | .collect(); 116 | self 117 | } 118 | } 119 | 120 | /// Utilities related to the `Message` 121 | pub mod util { 122 | use super::Message; 123 | 124 | /// Modify the [`Message::service_name`] value to make the first letter lowercase. 125 | /// 126 | /// This utility can be used in [`Engine::map_input()`] to send always 127 | /// a first letter lowercase version of the service_name to the engine to make the correct 128 | /// service match. 129 | /// 130 | /// This is useful because some users could specify a first capital letter without realizing 131 | /// (usually in email clients where the first letter is uppercase by default). 132 | /// If the service_name is registered with lowercase, their message will not match. 133 | /// 134 | /// [`Engine::map_input()`]: crate::engine::Engine::map_input() 135 | pub fn service_name_first_char_to_lowercase(mut message: Message) -> Message { 136 | let mut chars = message.service_name.chars(); 137 | message.service_name = match chars.next() { 138 | Some(first_letter) => first_letter.to_lowercase().collect::() + chars.as_str(), 139 | None => String::new(), 140 | }; 141 | message 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/connectors/imap.rs: -------------------------------------------------------------------------------- 1 | use crate::channel::{ClosedChannel, Sender}; 2 | use crate::interface::InputConnector; 3 | use crate::message::Message; 4 | 5 | use async_trait::async_trait; 6 | use imap::{error::Error, Session}; 7 | use mailparse::{DispositionType, MailHeaderMap, ParsedMail}; 8 | use native_tls::{TlsConnector, TlsStream}; 9 | 10 | use std::collections::HashMap; 11 | use std::io::{Read, Write}; 12 | use std::net::TcpStream; 13 | use std::time::Duration; 14 | 15 | /// Input connector that acts as an IMAP client 16 | /// The service fetchs and removes the email from the server, and transforms it to messages. 17 | /// The first word of the subjet is interpreted as the service name. 18 | /// The following spaced-separated words are the arguments. 19 | /// 20 | /// This connector makes attempts to the ICMP server each [`ImapClient::polling_time`] seconds. 21 | #[derive(Default, Clone)] 22 | pub struct ImapClient { 23 | imap_domain: String, 24 | email: String, 25 | password: String, 26 | polling_time: Duration, 27 | } 28 | 29 | impl ImapClient { 30 | pub fn domain(mut self, value: impl Into) -> Self { 31 | self.imap_domain = value.into(); 32 | self 33 | } 34 | 35 | pub fn email(mut self, value: impl Into) -> Self { 36 | self.email = value.into(); 37 | self 38 | } 39 | 40 | pub fn password(mut self, value: impl Into) -> Self { 41 | self.password = value.into(); 42 | self 43 | } 44 | 45 | pub fn polling_time(mut self, duration: Duration) -> Self { 46 | self.polling_time = duration; 47 | self 48 | } 49 | 50 | fn connect(&self) -> Result>, Error> { 51 | let tls = TlsConnector::builder().build().unwrap(); 52 | let client = imap::connect( 53 | (self.imap_domain.as_str(), 993), 54 | self.imap_domain.as_str(), 55 | &tls, 56 | )?; 57 | 58 | client.login(&self.email, &self.password).map_err(|e| e.0) 59 | } 60 | } 61 | 62 | #[async_trait] 63 | impl InputConnector for ImapClient { 64 | async fn run(mut self: Box, sender: Sender) -> Result<(), ClosedChannel> { 65 | tokio::task::spawn_blocking(move || { 66 | let mut session = self.connect().unwrap(); 67 | loop { 68 | std::thread::sleep(self.polling_time); 69 | 70 | match read_inbox(&mut session) { 71 | Ok(Some(message)) => sender.blocking_send(message)?, 72 | Ok(None) => (), 73 | Err(err) => { 74 | log::warn!("{}", err); 75 | session = match self.connect() { 76 | Ok(session) => { 77 | log::info!("Connection restored"); 78 | session 79 | } 80 | Err(err) => { 81 | log::error!("{}", err); 82 | continue; 83 | } 84 | } 85 | } 86 | } 87 | } 88 | }) 89 | .await 90 | .unwrap() 91 | } 92 | } 93 | 94 | fn read_inbox(session: &mut Session) -> Result, Error> { 95 | session.select("INBOX")?; 96 | 97 | let emails = session.fetch("1", "RFC822")?; 98 | 99 | if let Some(email) = emails.iter().next() { 100 | session.store(format!("{}", email.message), "+FLAGS (\\Deleted)")?; 101 | 102 | session.expunge()?; 103 | 104 | if let Some(body) = email.body() { 105 | log::trace!( 106 | "Raw email:\n{}", 107 | std::str::from_utf8(body).unwrap_or("No utf8") 108 | ); 109 | 110 | match mailparse::parse_mail(body) { 111 | Ok(parsed) => return Ok(Some(email_to_message(parsed))), 112 | Err(err) => log::error!("{}", err), 113 | } 114 | } 115 | } 116 | 117 | Ok(None) 118 | } 119 | 120 | fn email_to_message(email: ParsedMail) -> Message { 121 | let subject = email.headers.get_first_value("Subject").unwrap_or_default(); 122 | let mut subject_args = subject.split_whitespace().map(|s| s.to_owned()); 123 | 124 | let mut body = String::default(); 125 | for part in &email.subparts { 126 | if part.ctype.mimetype.starts_with("text/plain") { 127 | body = part.get_body().unwrap_or_default(); 128 | } 129 | } 130 | 131 | let mut files = HashMap::default(); 132 | for part in &email.subparts { 133 | let content_disposition = part.get_content_disposition(); 134 | if let DispositionType::Attachment = content_disposition.disposition { 135 | if let Some(filename) = content_disposition.params.get("filename") { 136 | files.insert(filename.into(), part.get_body_raw().unwrap_or_default()); 137 | } 138 | } 139 | } 140 | 141 | Message { 142 | user: email 143 | .headers 144 | .get_first_value("From") 145 | .map(|from_list| { 146 | mailparse::addrparse(&from_list) 147 | .expect("Have a 'From' email") 148 | .extract_single_info() 149 | .expect("Have at least one 'From' email") 150 | .addr 151 | }) 152 | .unwrap_or_default(), 153 | service_name: subject_args.next().unwrap_or_default(), 154 | args: subject_args.collect(), 155 | body, 156 | attached_data: files, 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![](https://img.shields.io/crates/v/service-io)](https://crates.io/crates/service-io) 2 | [![](https://img.shields.io/docsrs/service-io)](https://docs.rs/service-io) 3 | [![](https://img.shields.io/crates/l/service-io)](https://www.apache.org/licenses/LICENSE-2.0.txt) 4 | [![](https://img.shields.io/badge/bymeacoffee-donate-yellow)](https://www.buymeacoffee.com/lemunozm) 5 | 6 | **NOTE: This crate is archived, use [`mailfred`](https://github.com/lemunozm/mailfred) instead.** 7 | 8 |

9 | 10 |

11 | 12 | `service-io` is a library to build servers that offering services with really little effort. 13 | 14 | 1. Choose an input connector. 15 | 2. Choose an output connector. 16 | 3. Choose your services. 17 | 4. Run it! 18 | 19 | One of the main use-cases is to offer services [without a hosting server](#no-hosting-server). 20 | 21 | ## How it works? 22 |

23 | 24 |

25 | 26 | All of them, **inputs**/**outputs** and **services** "speak" the same language: 27 | the [`Message`](https://docs.rs/service-io/latest/service_io/message/struct.Message.html) type. 28 | 29 | Inputs obtain and transform input data into a `Message`. 30 | Services receive `Message`s and generate other `Message`s usually doing some kind of processing. 31 | Outputs transform a `Message` into output data and deliver it. 32 | 33 | Check the current built-in input/output 34 | [connectors](https://docs.rs/service-io/latest/service_io/connectors/index.html) 35 | and 36 | [services](https://docs.rs/service-io/latest/service_io/services/index.html). 37 | 38 | ## Features 39 | - **Easy to use**. Running a server with a bunch of services with (really) few lines of code. 40 | - **Hostingless**. Run custom server code without hosting server using the existing email infrastructure 41 | using the IMAP/SMTP connectors. 42 | - **Scalable**. Create your own inputs/outputs/services implementing a trait with a single method. 43 | [Check docs](https://docs.rs/service-io/latest/service_io/interface/index.html) 44 | - **Multiplatform**. Run your local service-server in any computer you have. 45 | 46 | ## Getting Started 47 | - [API Docs](https://docs.rs/service-io/latest/service_io/) 48 | - [Examples](examples) 49 | 50 | Add the following to your `Cargo.toml` 51 | ```toml 52 | service-io = "0.1" 53 | ``` 54 | 55 | ## Example 56 | Running this example in any of your home computer, 57 | and sending an email (as an example, to `services@domain.com`) 58 | with `public-ip` in the subject, you will obtain a response email with your home public IP! 59 | 60 | In a similar way, sending an email with `process ls -l` in the subject will return 61 | an email with the files of the folder used to run the example. 62 | 63 | ```rust,no_run 64 | use service_io::engine::Engine; 65 | use service_io::connectors::{ImapClient, SmtpClient}; 66 | use service_io::services::{PublicIp, Process, Echo, Alarm}; 67 | 68 | #[tokio::main] 69 | async fn main() { 70 | Engine::default() 71 | .input( 72 | ImapClient::default() 73 | .domain("imap.domain.com") 74 | .email("services@domain.com") 75 | .password("1234") 76 | ) 77 | .output( 78 | SmtpClient::default() 79 | .domain("smtp.domain.com") 80 | .email("services@domain.com") 81 | .password("1234") 82 | ) 83 | .add_service("echo", Echo) 84 | .add_service("alarm", Alarm) 85 | .add_service("public-ip", PublicIp) 86 | .add_service("process", Process) 87 | // Add any other service you want 88 | .run() 89 | .await; 90 | } 91 | ``` 92 | 93 | Any email sent to `services@domain.com` will be interpreted as a request by the `ImapClient` connector. 94 | If the first word of the subject matches `public-ip`, the request will be processed by the `PublicIp` service. 95 | The service `PublicIp` will generate a response that `SmtpClient` will be deliver by email 96 | to the remitter of the request email. 97 | 98 | Check the [Engine](https://docs.rs/service-io/latest/service_io/engine/struct.Engine.html) type 99 | for additional methods as input mapping/filters or adding whitelists to your services. 100 | 101 | Test it yourself with [examples/email_server.rs](examples/email_server.rs). 102 | Run the following to see all config options. 103 | ```sh 104 | cargo run --example email_server -- --help 105 | ``` 106 | 107 | ## Configuring a gmail account to use with `service-io`. 108 | For use `service-io` with IMAP and SMTP connectors with gmail you need to configure some points 109 | of your gmail account: 110 | - Enable IMAP in account settings: Check this [Step 1](https://support.google.com/mail/answer/7126229?hl=en#zippy=%2Cpaso-comprueba-que-imap-est%C3%A9-activado%2Cstep-check-that-imap-is-turned-on). 111 | - Enable [unsecure app access](https://support.google.com/accounts/answer/6010255?hl=en) 112 | to allow login with password from an app. 113 | (Pending work to make it available through *oauth2* and avoid this point). 114 | 115 | ## No hosting server use-case 116 | If you want to offer some custom service that uses *custom server code* 117 | you are forced to pay and maintain a hosting server, 118 | even if the service you are offering is eventual or does not use many resources. 119 | 120 | To solve this problem, you can use the already existent email infrastructure 121 | using the IMAP and SMTP protocols to handle the emails as requests/responses and link them with your services. 122 | 123 | `service-io` helps in this context. 124 | Run locally an instance of `service-io` with IMAP/SMTP connectors. 125 | The IMAP connector will periodically fetch the emails your clients sends, 126 | then your services will process those emails and generate a response, 127 | and finally the SMTP connector will deliver the response emails back to the user. 128 | 129 | Anyone from any device with an email client can interact with your local server deployment. 130 | There is **no hosting maintenance** and **no front-end app development**. 131 | 132 |

133 | 134 |

135 | 136 | ## Contribute 137 | - *Have you implemented a **service** or **connector**?* 138 | If its functionallity is not private, share it with others! 139 | Make a *Pull Request* so everyone can use it :) 140 | 141 | - *Do you have any cool **idea**, found a **bug** or have any **question** or **doubt**?* 142 | Do not hesitate and open an issue! 143 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/engine.rs: -------------------------------------------------------------------------------- 1 | //! Main entity of `service-io`. 2 | //! Connects input, output, and services and run them. 3 | 4 | use crate::channel::{ClosedChannel, Receiver, Sender}; 5 | use crate::interface::{InputConnector, OutputConnector, Service}; 6 | use crate::message::Message; 7 | 8 | use tokio::{ 9 | sync::mpsc, 10 | task::{JoinError, JoinHandle}, 11 | }; 12 | 13 | use std::collections::{HashMap, HashSet}; 14 | 15 | struct ServiceConfig { 16 | name: String, 17 | service: Box, 18 | whitelist: Option>, 19 | } 20 | 21 | struct ServiceHandle { 22 | input_sender: mpsc::Sender, 23 | whitelist: Option>, 24 | } 25 | 26 | impl ServiceHandle { 27 | async fn process_message(&self, message: Message) { 28 | let allowed = match &self.whitelist { 29 | Some(whitelist) => whitelist.contains(&message.user), 30 | None => true, 31 | }; 32 | 33 | if allowed { 34 | let user = message.user.clone(); 35 | let service_name = message.service_name.clone(); 36 | let args = message.args.join(" "); 37 | match self.input_sender.send(message).await { 38 | Ok(()) => log::info!( 39 | "Processing message from '{}' for service '{}' with args '{}'", 40 | user, 41 | service_name, 42 | args 43 | ), 44 | Err(_) => log::warn!("Drop message for removed service '{}'", service_name), 45 | } 46 | } else { 47 | log::warn!( 48 | "Drop message for service '{}' not allowed for user '{}'", 49 | message.service_name, 50 | message.user, 51 | ); 52 | } 53 | } 54 | } 55 | 56 | /// Main entity of `service-io`. 57 | /// 58 | /// It defines the following schema that runs asynchronously: `Input -> n Services -> Output` 59 | /// 60 | /// A message received by the [`InputConnector`] will be sent to a specific [`Service`] based on the 61 | /// [`Message::service_name`]. The [`Service`] will process the message and optionally can sent any 62 | /// number of output messages that will be delivered by the [`OutputConnector`]. 63 | /// 64 | /// # Example 65 | /// ```rust no_run 66 | /// use service_io::connectors::{ImapClient, SmtpClient}; 67 | /// use service_io::engine::Engine; 68 | /// use service_io::services::{Echo, Alarm}; 69 | /// 70 | /// #[tokio::main] 71 | /// async fn main() { 72 | /// Engine::default() 73 | /// .input( 74 | /// ImapClient::default() 75 | /// .domain("imap.domain.com") 76 | /// .email("service@domain.com") 77 | /// .password("1234"), 78 | /// ) 79 | /// .output( 80 | /// SmtpClient::default() 81 | /// .domain("smtp.domain.com") 82 | /// .email("service@domain.com") 83 | /// .password("1234"), 84 | /// ) 85 | /// .add_service("s-echo", Echo) 86 | /// .add_service("s-alarm", Alarm) 87 | /// .run() 88 | /// .await; 89 | /// } 90 | /// ``` 91 | /// 92 | #[derive(Default)] 93 | pub struct Engine { 94 | input: Option>, 95 | output: Option>, 96 | input_mapping: Option Message + Send>>, 97 | input_filtering: Option bool + Send>>, 98 | service_configs: Vec, 99 | } 100 | 101 | impl Engine { 102 | /// Set an input connector for this engine that will be run after calling [`Engine::run()`]. 103 | /// 104 | /// Default connectors can be found in [`connectors`]. 105 | /// This call is mandatory in order to run the engine. 106 | /// 107 | /// [`connectors`]: crate::connectors 108 | pub fn input(mut self, input: impl InputConnector + Send + 'static) -> Engine { 109 | self.input = Some(Box::new(input)); 110 | self 111 | } 112 | 113 | /// Set an output connector for this engine that will be run after calling [`Engine::run()`]. 114 | /// 115 | /// Default connectors can be found in [`connectors`]. 116 | /// This call is mandatory in order to run the engine. 117 | /// 118 | /// [`connectors`]: crate::connectors 119 | pub fn output(mut self, output: impl OutputConnector + Send + 'static) -> Engine { 120 | self.output = Some(Box::new(output)); 121 | self 122 | } 123 | 124 | /// Maps the message processed by the input connector into other message before checking the 125 | /// destination service the message is for. 126 | /// 127 | /// # Example 128 | /// ```rust no_run 129 | /// use service_io::connectors::{ImapClient, SmtpClient}; 130 | /// use service_io::engine::Engine; 131 | /// use service_io::services::Echo; 132 | /// use service_io::message::util; 133 | /// 134 | /// #[tokio::main] 135 | /// async fn main() { 136 | /// Engine::default() 137 | /// .input( 138 | /// ImapClient::default() 139 | /// .domain("imap.domain.com") 140 | /// .email("service@domain.com") 141 | /// .password("1234"), 142 | /// ) 143 | /// .output( 144 | /// SmtpClient::default() 145 | /// .domain("smtp.domain.com") 146 | /// .email("service@domain.com") 147 | /// .password("1234"), 148 | /// ) 149 | /// // Now, if the user writes "S-echo", it will found the service "s-echo" 150 | /// .map_input(util::service_name_first_char_to_lowercase) 151 | /// .add_service("s-echo", Echo) 152 | /// .run() 153 | /// .await; 154 | /// } 155 | /// ``` 156 | pub fn map_input(mut self, mapping: impl Fn(Message) -> Message + Send + 'static) -> Engine { 157 | self.input_mapping = Some(Box::new(mapping)); 158 | self 159 | } 160 | 161 | /// Allow or disallow passing the message to the service based of the message itself. 162 | /// This filter method is applied just after the mapping method set by [`Engine::map_input`]. 163 | /// 164 | /// # Example 165 | /// ```rust no_run 166 | /// use service_io::connectors::{ImapClient, SmtpClient}; 167 | /// use service_io::engine::Engine; 168 | /// use service_io::services::Echo; 169 | /// 170 | /// #[tokio::main] 171 | /// async fn main() { 172 | /// Engine::default() 173 | /// .input( 174 | /// ImapClient::default() 175 | /// .domain("imap.domain.com") 176 | /// .email("service@domain.com") 177 | /// .password("1234"), 178 | /// ) 179 | /// .output( 180 | /// SmtpClient::default() 181 | /// .domain("smtp.domain.com") 182 | /// .email("service@domain.com") 183 | /// .password("1234"), 184 | /// ) 185 | /// // Now, only input messages from gmail are allowed 186 | /// .filter_input(|message| message.user.ends_with("gmail.com")) 187 | /// .add_service("s-echo", Echo) 188 | /// .run() 189 | /// .await; 190 | /// } 191 | /// ``` 192 | pub fn filter_input(mut self, filtering: impl Fn(&Message) -> bool + Send + 'static) -> Engine { 193 | self.input_filtering = Some(Box::new(filtering)); 194 | self 195 | } 196 | 197 | /// Add a service to the engine registered with a `name`. If the [`Message::service_name`] value 198 | /// matches with this `name`, the message will be redirected to the service. 199 | /// 200 | /// Note that the service will not run until you call [`Engine::run()`] 201 | /// 202 | /// Default services can be found in [`services`] 203 | /// 204 | /// [`services`]: crate::services 205 | pub fn add_service( 206 | mut self, 207 | name: impl Into, 208 | service: impl Service + Send + 'static, 209 | ) -> Engine { 210 | self.service_configs.push(ServiceConfig { 211 | name: name.into(), 212 | service: Box::new(service), 213 | whitelist: None, 214 | }); 215 | self 216 | } 217 | 218 | /// Similar to [`Engine::add_service()`] but service only allow receive message for a whitelist of users. 219 | /// If the [`Message::user`] of the incoming message not belong to that list, the message is 220 | /// discarded. 221 | /// 222 | /// # Example 223 | /// ```rust no_run 224 | /// use service_io::connectors::{ImapClient, SmtpClient}; 225 | /// use service_io::engine::Engine; 226 | /// use service_io::services::Process; 227 | /// 228 | /// #[tokio::main] 229 | /// async fn main() { 230 | /// Engine::default() 231 | /// .input( 232 | /// ImapClient::default() 233 | /// .domain("imap.domain.com") 234 | /// .email("service@domain.com") 235 | /// .password("1234"), 236 | /// ) 237 | /// .output( 238 | /// SmtpClient::default() 239 | /// .domain("smtp.domain.com") 240 | /// .email("service@domain.com") 241 | /// .password("1234"), 242 | /// ) 243 | /// // We only want messages comming from the admin user 244 | /// // to go to s-process service to avoid attacks. 245 | /// .add_service_for("s-process", Process, ["admin@domain.com"]) 246 | /// .run() 247 | /// .await; 248 | /// } 249 | /// ``` 250 | pub fn add_service_for>( 251 | mut self, 252 | name: impl Into, 253 | service: impl Service + Send + 'static, 254 | whitelist: impl IntoIterator, 255 | ) -> Engine { 256 | self.service_configs.push(ServiceConfig { 257 | name: name.into(), 258 | service: Box::new(service), 259 | whitelist: Some(whitelist.into_iter().map(|s| s.into()).collect()), 260 | }); 261 | self 262 | } 263 | 264 | /// Run asynchronously the input, output and all services configured for this engine. 265 | /// The engine will run until all services finished or the input/output connector finalizes. 266 | pub async fn run(self) { 267 | log::info!("Initializing engine..."); 268 | 269 | let (input_sender, mut input_receiver) = mpsc::channel(32); 270 | Self::load_input(self.input.unwrap(), input_sender); 271 | 272 | let (output_sender, output_receiver) = mpsc::channel(32); 273 | let mut output_task = Self::load_output(self.output.unwrap(), output_receiver); 274 | 275 | let services = Self::load_services(self.service_configs, output_sender); 276 | 277 | loop { 278 | tokio::select! { 279 | Some(message) = input_receiver.recv() => { 280 | let message = match &self.input_mapping { 281 | Some(map) => map(message), 282 | None => message, 283 | }; 284 | 285 | let allowed = match &self.input_filtering { 286 | Some(filter) => filter(&message), 287 | None => true, 288 | }; 289 | 290 | if allowed { 291 | match services.get(&message.service_name) { 292 | Some(handle) => handle.process_message(message).await, 293 | None => log::trace!( 294 | "Drop Message from {} for unknown service '{}'", 295 | message.user, 296 | message.service_name 297 | ), 298 | } 299 | } 300 | } 301 | _ = &mut output_task => break, 302 | else => break, 303 | } 304 | } 305 | } 306 | 307 | fn load_input( 308 | input: Box, 309 | sender: mpsc::Sender, 310 | ) -> JoinHandle<()> { 311 | tokio::spawn(async move { 312 | log::info!("Loading input connector"); 313 | 314 | let result = tokio::spawn(async move { input.run(Sender(sender)).await }).await; 315 | 316 | Self::log_join_result(result, "Input connector"); 317 | }) 318 | } 319 | 320 | fn load_output( 321 | output: Box, 322 | receiver: mpsc::Receiver, 323 | ) -> JoinHandle<()> { 324 | tokio::spawn(async move { 325 | log::info!("Loading output connector"); 326 | 327 | let result = tokio::spawn(async move { output.run(Receiver(receiver)).await }).await; 328 | 329 | Self::log_join_result(result, "Output connector"); 330 | }) 331 | } 332 | 333 | fn load_service( 334 | service: Box, 335 | receiver: mpsc::Receiver, 336 | sender: mpsc::Sender, 337 | name: String, 338 | ) -> JoinHandle<()> { 339 | tokio::spawn(async move { 340 | log::info!("Loading service '{}'", name); 341 | 342 | let result = 343 | tokio::spawn(async move { service.run(Receiver(receiver), Sender(sender)).await }) 344 | .await; 345 | 346 | Self::log_join_result(result, &format!("Service '{}'", name)); 347 | }) 348 | } 349 | 350 | fn load_services( 351 | configs: Vec, 352 | output_sender: mpsc::Sender, 353 | ) -> HashMap { 354 | let services = configs 355 | .into_iter() 356 | .map(|config| { 357 | let (input_sender, input_receiver) = mpsc::channel(32); 358 | let output_sender = output_sender.clone(); 359 | let service_name = config.name.clone(); 360 | 361 | Self::load_service(config.service, input_receiver, output_sender, service_name); 362 | 363 | ( 364 | config.name, 365 | ServiceHandle { 366 | whitelist: config.whitelist, 367 | input_sender, 368 | }, 369 | ) 370 | }) 371 | .collect(); 372 | 373 | drop(output_sender); 374 | 375 | services 376 | } 377 | 378 | fn log_join_result(result: Result, JoinError>, name: &str) { 379 | match result { 380 | Ok(Ok(())) => log::info!("{} down (finished)", name), 381 | Ok(Err(_)) => log::info!("{} down (disconnected)", name), 382 | Err(_) => log::error!("{} down (panicked)", name), 383 | } 384 | } 385 | } 386 | 387 | #[cfg(test)] 388 | mod tests { 389 | use super::*; 390 | use crate::channel::ClosedChannel; 391 | use crate::message::util; 392 | 393 | use async_trait::async_trait; 394 | use tokio::time::timeout; 395 | 396 | use std::time::Duration; 397 | 398 | #[derive(Clone)] 399 | pub struct EchoOnce; 400 | 401 | #[async_trait] 402 | impl Service for EchoOnce { 403 | async fn run( 404 | self: Box, 405 | mut input: Receiver, 406 | output: Sender, 407 | ) -> Result<(), ClosedChannel> { 408 | let message = input.recv().await?; 409 | output.send(message).await 410 | } 411 | } 412 | 413 | fn build_message(user: &str, service: &str) -> Message { 414 | Message { 415 | user: user.into(), 416 | service_name: service.into(), 417 | args: vec!["arg0".into(), "arg1".into()], 418 | body: "abcd".into(), 419 | attached_data: [ 420 | ("file1".to_string(), b"1234".to_vec()), 421 | ("file2".to_string(), b"5678".to_vec()), 422 | ] 423 | .into_iter() 424 | .collect(), 425 | } 426 | } 427 | 428 | #[tokio::test] 429 | async fn echo() { 430 | let (input_sender, input_receiver) = mpsc::channel(32); 431 | let (output_sender, mut output_receiver) = mpsc::channel(32); 432 | 433 | let task = tokio::spawn(async move { 434 | Engine::default() 435 | .input(input_receiver) 436 | .output(output_sender) 437 | .add_service("s-test", EchoOnce) 438 | .run() 439 | .await; 440 | }); 441 | 442 | let message = build_message("user_0", "s-test"); 443 | input_sender.send(message.clone()).await.unwrap(); 444 | assert_eq!(Some(message), output_receiver.recv().await); 445 | 446 | task.await.unwrap(); 447 | } 448 | 449 | #[tokio::test] 450 | async fn echo_with_input_mapping() { 451 | let (input_sender, input_receiver) = mpsc::channel(32); 452 | let (output_sender, mut output_receiver) = mpsc::channel(32); 453 | 454 | let task = tokio::spawn(async move { 455 | Engine::default() 456 | .input(input_receiver) 457 | .output(output_sender) 458 | .map_input(util::service_name_first_char_to_lowercase) 459 | .add_service("s-test", EchoOnce) 460 | .run() 461 | .await; 462 | }); 463 | 464 | let message = build_message("user_0", "S-test"); 465 | input_sender.send(message.clone()).await.unwrap(); 466 | assert_eq!( 467 | Some(util::service_name_first_char_to_lowercase(message)), 468 | output_receiver.recv().await 469 | ); 470 | 471 | task.await.unwrap(); 472 | } 473 | 474 | #[tokio::test] 475 | async fn echo_with_input_filtering() { 476 | let (input_sender, input_receiver) = mpsc::channel(32); 477 | let (output_sender, mut output_receiver) = mpsc::channel(32); 478 | 479 | tokio::spawn(async move { 480 | Engine::default() 481 | .input(input_receiver) 482 | .output(output_sender) 483 | .filter_input(|message| !message.service_name.starts_with("s-")) 484 | .add_service("s-test", EchoOnce) 485 | .run() 486 | .await; 487 | }); 488 | 489 | let message = build_message("user_0", "s-test"); 490 | input_sender.send(message.clone()).await.unwrap(); 491 | assert!(timeout(Duration::from_millis(100), output_receiver.recv()) 492 | .await 493 | .is_err()); 494 | } 495 | 496 | #[tokio::test] 497 | async fn no_services() { 498 | let (_input_sender, input_receiver) = mpsc::channel(32); 499 | let (output_sender, mut _output_receiver) = mpsc::channel(32); 500 | 501 | tokio::spawn(async move { 502 | Engine::default() 503 | .input(input_receiver) 504 | .output(output_sender) 505 | .run() 506 | .await; 507 | }) 508 | .await 509 | .unwrap(); 510 | } 511 | 512 | #[tokio::test] 513 | async fn service_not_found() { 514 | let (input_sender, input_receiver) = mpsc::channel(32); 515 | let (output_sender, mut output_receiver) = mpsc::channel(32); 516 | 517 | tokio::spawn(async move { 518 | Engine::default() 519 | .input(input_receiver) 520 | .output(output_sender) 521 | .add_service("s-test", EchoOnce) 522 | .run() 523 | .await; 524 | }); 525 | 526 | let message = build_message("user_0", "unknown"); 527 | input_sender.send(message.clone()).await.unwrap(); 528 | assert!(timeout(Duration::from_millis(100), output_receiver.recv()) 529 | .await 530 | .is_err()); 531 | } 532 | 533 | #[tokio::test] 534 | async fn whitelist() { 535 | let (input_sender, input_receiver) = mpsc::channel(32); 536 | let (output_sender, mut output_receiver) = mpsc::channel(32); 537 | 538 | let task = tokio::spawn(async move { 539 | Engine::default() 540 | .input(input_receiver) 541 | .output(output_sender) 542 | .add_service_for("s-test", EchoOnce, ["user_allowed"]) 543 | .run() 544 | .await; 545 | }); 546 | 547 | let message = build_message("user_not_allowed", "s-test"); 548 | input_sender.send(message.clone()).await.unwrap(); 549 | assert!(timeout(Duration::from_millis(100), output_receiver.recv()) 550 | .await 551 | .is_err()); 552 | 553 | let message = build_message("user_allowed", "s-test"); 554 | input_sender.send(message.clone()).await.unwrap(); 555 | assert_eq!(Some(message), output_receiver.recv().await); 556 | 557 | task.await.unwrap(); 558 | } 559 | } 560 | --------------------------------------------------------------------------------