DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 1b8eda0a49f5fa733c699116c16f51898f5f06b4 emerwen/emerwen-master/src/ipc_server/mod.rs -rw-r--r-- 2.2 KiB
1b8eda0aJonni Liljamo feat: move emerwen-proto crate out of here 4 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
78
79
80
81
82
83
84
85
86
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

use std::path::Path;

use emerwen_proto::emerwen::webtomaster::{
    web_to_master_server::{WebToMaster, WebToMasterServer},
    WorkersResponse,
};
use tokio::{net::UnixListener, sync::mpsc};
use tokio_stream::wrappers::UnixListenerStream;
use tonic::{Request, Response, Status};
use tonic_async_interceptor::async_interceptor;
use tracing::{error, info, warn};

use crate::db::DatabaseHandle;

mod auth;
use auth::AuthInterceptor;

pub enum Message {}

pub async fn run(
    socket_path: &Path,
    db_handle: DatabaseHandle,
    mut rx: mpsc::Receiver<Message>,
) -> Result<(), Box<dyn std::error::Error>> {
    let _db_handle_two = db_handle.clone();
    tokio::spawn(async move {
        while let Some(msg) = rx.recv().await {
            match msg {}
        }
    });

    if socket_path.exists() {
        warn!(
            msg = "Socket path is not empty, trying to clear",
            ?socket_path
        );
        if let Err(err) = std::fs::remove_file(socket_path) {
            error!(msg = "Failed to clear socket file in the way", %err);
            return Err(err.into());
        }
        info!(msg = "Successfully cleared socket file in the way");
    }

    let uds = UnixListener::bind(socket_path)?;
    let uds_stream = UnixListenerStream::new(uds);

    tonic::transport::Server::builder()
        // TODO: auth token from elsewhere.
        .layer(async_interceptor(AuthInterceptor::new(
            "avain_perkele".into(),
        )))
        .add_service(WebToMasterServer::new(Server::new(db_handle.clone()).await))
        .serve_with_incoming(uds_stream)
        .await?;

    Ok(())
}

struct Server {
    db_handle: DatabaseHandle,
}

impl Server {
    async fn new(db_handle: DatabaseHandle) -> Self {
        Self { db_handle }
    }
}

#[tonic::async_trait]
impl WebToMaster for Server {
    async fn get_workers(
        &self,
        _request: Request<()>,
    ) -> Result<Response<WorkersResponse>, Status> {
        let workers = self.db_handle.read_workers().await;

        Ok(Response::new(WorkersResponse { workers }))
    }
}