summaryrefslogtreecommitdiff
path: root/src/server.rs
blob: 2d18d97b2af7ec30bf63f39922ade0a129da07e5 (plain)
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
use std::net::SocketAddr;
use std::process::exit;

use log::info;
mod logger;
use tonic::{transport::Server, Request, Response, Status};

use clawflake::clawflake_server::{Clawflake, ClawflakeServer};
use clawflake::{IdReply, IdRequest};

pub mod clawflake {
    tonic::include_proto!("clawflake");
}

mod id_worker;
use id_worker::IdWorker;

const EPOCH: i64 = 1_564_790_400_000; // todo(n1c00o): find a good custom epoch for production cuz its fun
const WORKER_ID: i64 = 0; // todo(n1c00o): need a way to detect the worker id from Kubernetes
const DATACENTER_ID: i64 = 0; // todo(n1c00o): need a way to detect the data center id from idk

#[derive(Debug, Default)]
pub struct MyClawflakeService {
}

#[tonic::async_trait]
impl Clawflake for MyClawflakeService {
    async fn get_id(
        &self,
        _: Request<IdRequest>,
    ) -> Result<Response<IdReply>, Status> {
        info!("request on GetID");

        let mut worker: IdWorker = IdWorker::new(EPOCH, WORKER_ID, DATACENTER_ID);

        let reply: IdReply = clawflake::IdReply {
            id: format!("{}", worker.next_id()).into(),
        };

        Ok(Response::new(reply))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // init logger
    match logger::init() {
      Err(e) => {
        eprintln!("failed to init logger: {}", &e);
        exit(1);
      }
      _ => {}
    }

    // init tonic and IdWorker
    let addr: SocketAddr = "[::1]:50051".parse()?; //todo(n1c00o): make sure we can manage addr, then make the Dockerfile
    let srv: MyClawflakeService = MyClawflakeService::default();

    println!("Service listening on {}", addr);

    Server::builder()
        .add_service(ClawflakeServer::new(srv))
        .serve(addr)
        .await?;

    Ok(())
}