aboutsummaryrefslogtreecommitdiff
path: root/examples/fullmesh.rs
blob: 972bec09d8935fbc3c64bdb821317309db6f8401 (plain) (blame)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::io::Write;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use bytes::Bytes;
use futures::{stream, StreamExt};
use log::*;
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use tokio::sync::watch;

use sodiumoxide::crypto::auth;
use sodiumoxide::crypto::sign::ed25519;

use netapp::endpoint::*;
use netapp::message::*;
use netapp::peering::fullmesh::*;
use netapp::util::*;
use netapp::{NetApp, NodeID};

#[derive(StructOpt, Debug)]
#[structopt(name = "netapp")]
pub struct Opt {
	#[structopt(long = "network-key", short = "n")]
	network_key: Option<String>,

	#[structopt(long = "private-key", short = "p")]
	private_key: Option<String>,

	#[structopt(long = "bootstrap-peer", short = "b")]
	bootstrap_peers: Vec<String>,

	#[structopt(long = "listen-addr", short = "l", default_value = "127.0.0.1:1980")]
	listen_addr: String,

	#[structopt(long = "public-addr", short = "a")]
	public_addr: Option<String>,
}

#[tokio::main]
async fn main() {
	env_logger::Builder::new()
		.parse_env("RUST_LOG")
		.format(|buf, record| {
			writeln!(
				buf,
				"{} {}	{} {}",
				chrono::Local::now().format("%s%.6f"),
				record.module_path().unwrap_or("_"),
				record.level(),
				record.args()
			)
		})
		.init();

	let opt = Opt::from_args();

	let netid = match &opt.network_key {
		Some(k) => auth::Key::from_slice(&hex::decode(k).unwrap()).unwrap(),
		None => auth::gen_key(),
	};
	info!("Network key: {}", hex::encode(&netid));

	let privkey = match &opt.private_key {
		Some(k) => ed25519::SecretKey::from_slice(&hex::decode(k).unwrap()).unwrap(),
		None => {
			let (_pk, sk) = ed25519::gen_keypair();
			sk
		}
	};

	info!("Node private key: {}", hex::encode(&privkey));
	info!("Node public key: {}", hex::encode(&privkey.public_key()));

	let public_addr = opt.public_addr.map(|x| x.parse().unwrap());
	let listen_addr: SocketAddr = opt.listen_addr.parse().unwrap();
	info!("Node public address: {:?}", public_addr);
	info!("Node listen address: {}", listen_addr);

	let netapp = NetApp::new(0u64, netid.clone(), privkey.clone());

	let mut bootstrap_peers = vec![];
	for peer in opt.bootstrap_peers.iter() {
		bootstrap_peers.push(parse_peer_addr(peer).expect("Invalid peer address"));
	}

	let peering = FullMeshPeeringStrategy::new(
		netapp.clone(),
		bootstrap_peers,
		public_addr.map(|a| SocketAddr::new(a, listen_addr.port())),
	);

	info!("Add more peers to this mesh by running: fullmesh -n {} -l 127.0.0.1:$((1000 + $RANDOM)) -b {}@{}",
		hex::encode(&netid),
		hex::encode(&privkey.public_key()),
		listen_addr);

	let watch_cancel = netapp::util::watch_ctrl_c();

	let example = Arc::new(Example {
		netapp: netapp.clone(),
		fullmesh: peering.clone(),
		example_endpoint: netapp.endpoint("__netapp/examples/fullmesh.rs/Example".into()),
	});
	example.example_endpoint.set_handler(example.clone());

	tokio::join!(
		example.exchange_loop(watch_cancel.clone()),
		netapp.listen(listen_addr, public_addr, watch_cancel.clone()),
		peering.run(watch_cancel),
	);
}

// ----

struct Example {
	netapp: Arc<NetApp>,
	fullmesh: Arc<FullMeshPeeringStrategy>,
	example_endpoint: Arc<Endpoint<ExampleMessage, Self>>,
}

impl Example {
	async fn exchange_loop(self: Arc<Self>, must_exit: watch::Receiver<bool>) {
		let mut i = 12000;
		while !*must_exit.borrow() {
			tokio::time::sleep(Duration::from_secs(2)).await;

			let peers = self.fullmesh.get_peer_list();
			for p in peers.iter() {
				let id = p.id;
				if id == self.netapp.id {
					continue;
				}
				i += 1;
				let example_field = i;
				let self2 = self.clone();
				tokio::spawn(async move {
					info!(
						"Send example query {} to {}",
						example_field,
						hex::encode(id)
					);
					let stream =
						Box::pin(stream::iter([100, 200, 300, 400]).then(|x| async move {
							tokio::time::sleep(Duration::from_millis(500)).await;
							Ok(Bytes::from(vec![(x % 256) as u8; 133 * x]))
						}));
					match self2
						.example_endpoint
						.call_streaming(
							&id,
							Req::new(ExampleMessage { example_field })
								.unwrap()
								.with_stream(stream),
							PRIO_NORMAL,
						)
						.await
					{
						Ok(resp) => {
							let (resp, stream) = resp.into_parts();
							info!(
								"Got example response to {} from {}: {:?}",
								example_field,
								hex::encode(id),
								resp
							);
							let mut stream = stream.unwrap();
							while let Some(x) = stream.next().await {
								info!("Response: stream got bytes {:?}", x.map(|b| b.len()));
							}
						}
						Err(e) => warn!("Error with example request: {}", e),
					}
				});
			}
		}
	}
}

#[async_trait]
impl StreamingEndpointHandler<ExampleMessage> for Example {
	async fn handle(
		self: &Arc<Self>,
		mut msg: Req<ExampleMessage>,
		_from: NodeID,
	) -> Resp<ExampleMessage> {
		info!(
			"Got example message: {:?}, sending example response",
			msg.msg()
		);
		let source_stream = msg.take_stream().unwrap();
		let new_stream = Box::pin(source_stream.then(|x| async move {
			info!(
				"Handler: stream got bytes {:?}",
				x.as_ref().map(|b| b.len())
			);
			tokio::time::sleep(Duration::from_millis(300)).await;
			Ok(Bytes::from(vec![
				10u8;
				x.map(|b| b.len()).unwrap_or(1422) * 2
			]))
		}));
		Resp::new(ExampleResponse {
			example_field: false,
		})
		.with_stream(new_stream)
	}
}

#[derive(Serialize, Deserialize, Debug)]
struct ExampleMessage {
	example_field: usize,
}

#[derive(Serialize, Deserialize, Debug)]
struct ExampleResponse {
	example_field: bool,
}

impl Message for ExampleMessage {
	type Response = ExampleResponse;
}