use clap::Parser;
use emerwen_protocol::Message;
use tokio::{io::AsyncWriteExt, net::TcpStream};
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};
#[derive(Parser)]
#[command(version)]
struct Args {
/// Enable debug logging
#[arg(long)]
debug: bool,
}
#[tokio::main]
async fn main() {
let args = Args::parse();
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_file(args.debug)
.with_line_number(args.debug)
.with_level(true),
)
.with(
EnvFilter::builder()
.with_default_directive(if args.debug {
LevelFilter::DEBUG.into()
} else {
LevelFilter::INFO.into()
})
.from_env_lossy(),
)
.init();
info!("Starting emerwen master...");
debug!("Hello, debug!");
let mut worker_client = WorkerClient::new("127.0.0.1:8000");
let _ = worker_client.connect().await;
let _ = worker_client
.send_message(&Message::Authentication {
key: "test".to_owned(),
})
.await;
let _ = worker_client
.send_message(&Message::Authentication {
key: "askdas".to_owned(),
})
.await;
}
struct WorkerClient {
addr: String,
stream: Option<TcpStream>,
}
impl WorkerClient {
pub fn new(addr: impl Into<String>) -> WorkerClient {
WorkerClient {
addr: addr.into(),
stream: None,
}
}
pub async fn connect(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.stream = Some(TcpStream::connect(&self.addr).await?);
Ok(())
}
pub async fn send_message(
&mut self,
message: &Message,
) -> Result<(), Box<dyn std::error::Error>> {
if let Some(stream) = &mut self.stream {
stream.write_all(&message.encode()?).await?;
}
Ok(())
}
}