#![feature(return_position_impl_trait_in_trait)] use std::{ future::Future, sync::Arc, time::{SystemTime, UNIX_EPOCH}, }; use common::{ msg::{MessageHeader, Output}, msg_id::{gen_msg_id, MessageID}, run_server, Handler, }; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; fn main() { run_server::() } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] enum UniqueIdsBody { #[serde(rename = "generate")] Generate { msg_id: MessageID }, #[serde(rename = "generate_ok")] GenerateOk { msg_id: MessageID, in_reply_to: MessageID, id: u128, }, } struct UniqueIdsHandler { output: Output, } impl Handler for UniqueIdsHandler { type Body = UniqueIdsBody; fn init(_node_id: String, _node_ids: Vec, output: Output) -> Self { Self { output } } fn handle<'a>( self: &'a Arc, header: MessageHeader, body: Self::Body, ) -> impl Future + Send + 'a { async move { match body { UniqueIdsBody::Generate { msg_id } => { let id = gen_id(); self.output .send( &header.src, &UniqueIdsBody::GenerateOk { msg_id: gen_msg_id(), in_reply_to: msg_id, id, }, ) .await; } UniqueIdsBody::GenerateOk { .. } => (), }; } } } fn gen_id() -> u128 { // Time since UNIX epoch in milliseconds let now = SystemTime::now(); let time_millis: u128 = now.duration_since(UNIX_EPOCH).unwrap().as_millis(); // 80 bits of randomness let rand1: u16 = thread_rng().gen(); let rand2: u64 = thread_rng().gen(); let rand: u128 = rand1 as u128 | ((rand2 as u128) << 64); (time_millis << 80) | rand }