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
|
#![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::<UniqueIdsHandler>()
}
#[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<UniqueIdsBody>,
}
impl Handler for UniqueIdsHandler {
type Body = UniqueIdsBody;
fn init(_node_id: String, _node_ids: Vec<String>, output: Output<Self::Body>) -> Self {
Self { output }
}
fn handle<'a>(
self: &'a Arc<Self>,
header: MessageHeader,
body: Self::Body,
) -> impl Future<Output = ()> + 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
}
|