DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: ef2b830165b22e9bcc235221875b81e359a8bb7d emerwen/emerwen-worker/src/main.rs -rw-r--r-- 2.0 KiB
ef2b8301Jonni Liljamo feat: 2nd protocol iteration 15 days ago
                                                                                
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
use clap::Parser;
use emerwen_protocol::Message;
use tokio::net::TcpListener;
use tracing::{debug, error, 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 worker...");

    debug!("Hello, debug!");

    let worker_server = WorkerServer::new("127.0.0.1:8000");
    let _ = worker_server.run().await;
}

struct WorkerServer {
    addr: String,
}

impl WorkerServer {
    pub fn new(addr: impl Into<String>) -> WorkerServer {
        WorkerServer { addr: addr.into() }
    }

    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        let listener = TcpListener::bind(&self.addr).await?;
        info!("Worker Server listening on {}", self.addr);

        loop {
            let (mut stream, addr) = listener.accept().await?;
            info!("Client '{}' connected", addr);

            tokio::task::spawn(async move {
                loop {
                    let message = match Message::decode(&mut stream).await {
                        Ok(message) => message,
                        Err(e) => {
                            error!("Error decoding message: {:?}", e);

                            continue;
                        }
                    };
                    debug!("{:?}", message);
                }
            });
        }
    }
}