Documentation
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::time::{
	Duration,
	SystemTime
};

use serde::{Serialize, Deserialize};

use crate::control::Conspirator;
use crate::message::PingOrPong;

use super::{
	Address,
	Clock,
	link::{
		Link,
		//LinkState,
		LinkTickResult
	},
	NodeID
};
use super::status::{
	elapsed,
	remaining,
	PeerState,
	Status
};

use crate::util::*;


pub const TIME_TO_PING: Duration = Duration::from_secs(30);
//pub const TIME_TO_DOUBLE_PING: Duration = TIME_TO_PING + REPING_DELAY;
pub const TIME_TO_DOUBLE_PING: Duration = Duration::from_secs(33);
pub const REPING_DELAY: Duration = Duration::from_secs(3);
pub const REPING_DELAY_MAX: Duration = Duration::from_secs(60);
pub const REACH_OUT_TIME: Duration = Duration::from_secs(300);
pub const INDIRECT_TIMEOUT: Duration = Duration::from_secs(90);

pub const PINGS_UNTIL_SUSPICIOUS: u8 = 5;
pub const PINGS_UNTIL_UNREACHABLE: u8 = 10;


use Status::*;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Peer {
	pub id: NodeID,
	pub name: String,
	clk: Clock,
	state: Status,
	link: Option<Link>,
	known_addrs: usize,
	pub new_addr_pending: bool,
	seen_by_peer: Option<SystemTime>,
	addr_reach_out_idx: usize,
	reached_out_to: Option<SystemTime>
}

/// The TickResult indicates whether a ping is due now and when to tick next
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TickResult {
	pub address_to_ping: Option<Address>,
	pub state_changed: Option<Status>,
	pub reach_out_to: Option<usize>,
	pub next_tick_in: Duration
}

pub struct LinkUpdateResult {
	pub was_inactive: bool,
	pub new_address: bool
}

/// Calculate re-ping delay with exponential backoff
pub fn reping_delay(unponged: u8) -> Duration {
	// min ( (BASE_REPING_DELAY * 2^k), REPING_DELAY_MAX )
	std::cmp::min(
		REPING_DELAY * u32::pow(2, unponged.into()),
		REPING_DELAY_MAX
	)
}


impl Peer {
	pub fn unknown(id: NodeID) -> Self {
		Self {
			id,
			name: "unknown".to_string(),
			clk: Clock::null_clock(),
			state: Unreachable,
			link: None,
			known_addrs: 0,
			new_addr_pending: false,
			seen_by_peer: None,
			addr_reach_out_idx: 0,
			reached_out_to: None
		}
	}
	pub fn new(id: NodeID, name: String, address: Address) -> Self {
		Self {
			id,
			name,
			clk: Clock::null_clock(),
			state: Unreachable,
			link: Some(Link::new(address)),
			known_addrs: 1,
			new_addr_pending: false,
			seen_by_peer: None,
			addr_reach_out_idx: 0,
			reached_out_to: None
		}
	}
	pub fn load(
		id: NodeID,
		name: String,
		clk: Clock,
		state: Status,
		known_addrs: usize)
		-> Self
	{
		Self {
			id,
			name,
			clk,
			state,
			link: None,
			known_addrs,
			new_addr_pending: false,
			seen_by_peer: None,
			addr_reach_out_idx: 0,
			reached_out_to: None
		}
	}

/*
 *	INTERNAL HELPER METHODS
 */


/*
 *	QUERY
 */


	pub fn is_active(&self) -> bool {
		self.state == Active
	}

	pub fn get_info(&self) -> PeerInfo {
		PeerInfo {
			id: self.id,
			name: self.name.clone()
		}
	}

	pub fn get_peer_state(&self) -> PeerState {
		PeerState {
			id: self.id,
			clk: self.clk,
			state: self.state
		}
	}

	pub fn get_address(&self) -> Option<Address> {
		Some(self.link.as_ref()?.address)
	}
	pub fn get_pending_address(&self) -> Option<Address> {
		if self.new_addr_pending {Some(self.link.as_ref()?.address)}
		else {None}
	}

	#[must_use = "link marked as pinged"]
	pub fn get_address_to_ping(&mut self) -> Option<Address> {
		self.link
			.as_mut()
			.map(|l| {l.been_pinged(); l.address})
	}

	pub fn last_seen(&self) -> Option<Duration> {
		elapsed(self.link.as_ref()?.seen)
	}

/*
 *	UPDATE
 */

	pub fn update_address_count(&mut self, addr_count: usize) {
		if let (0, 1.., Indirect | Unreachable)
			= (self.known_addrs, addr_count, self.state)
		{
			self.reached_out_to = None;
		}
		self.known_addrs = addr_count;
	}

	pub fn new_clock(&mut self, pkt_clock: Clock) -> bool {
		if pkt_clock > self.clk {
			self.clk = pkt_clock;
			true
		}
		else {
			warn!(%self.id, ?self.clk, ?pkt_clock, "packet clock outdated");
			false
		}
	}

	pub fn has_pnged(&mut self, from: Address, png: PingOrPong)
		-> LinkUpdateResult
	{
		let was_inactive = self.state != Active;
		self.state = Active;
		let new_address = match self.link.as_mut() {
			Some(l) if l.address == from => {
				l.has_pnged(png);
				false
			},
			Some(_) | None => {
				self.link
					.insert(Link::new(from))
					.has_pnged(png);
				true
			}
		};
		LinkUpdateResult { was_inactive, new_address }
	}

	#[tracing::instrument]
	pub fn absorb_peer_state(&mut self, state: PeerState) -> Option<Status> {
		if self.clk < state.clk {
			self.clk = state.clk;
			match (self.state, state.state) {
				(Active | Indirect, Active | Indirect) => {
					self.seen_by_peer.set_now();
					None
				},

				(Suspicious, Suspicious) |
				(Quit, Quit) |
				(Unreachable, Unreachable) => None,

				// TODO: ignore this?
				(Unreachable, Suspicious) => None,
				// TODO: ignore this?
				//(Indirect, Suspicious | Unreachable) => None,
				// TODO: ignore this?
				(Suspicious, Indirect) => None,
				// TODO: ignore this also?
				// arguably could set seen_by_peer but since it's Suspicious it must already be pretty old anyway
				(Indirect, Suspicious) => None,

				(Active, new @ (Quit | Unreachable | Suspicious)) |
				(Indirect, new @ (Quit | Unreachable)) |
				(Suspicious, new @ (Active | Quit | Unreachable)) |
				(Quit, new @ (Active | Unreachable | Suspicious | Indirect)) |
				(Unreachable, new @ Quit) => {
					self.state = new;
					Some(new)
				},
				(Unreachable, Active | Indirect) => {
					self.seen_by_peer.set_now();
					self.state = Indirect;
					Some(Indirect)
				}
			}
		}
		//TODO: declared suspicious
		else if self.clk == state.clk
			&& state.state == Unreachable
			&& self.state != Unreachable
		{
			// TODO: re-evaluate
			self.state = Unreachable;
			Some(Unreachable)
		}
		else {
			None
		}
	}

	pub fn has_quit(&mut self) {
		info!("{} quit", self.name);
		self.state = Quit;
		self.link.take();
		// set reached_out_to to delay reach out
		self.reached_out_to.set_now();
	}

/*
 *	TIMED
 */

	/// Timed update, returns which address needs to be pinged now (if any),
	/// whether the peer/link has transitioned to a new state (and that state),
	/// and finally when the next timed update is due.
	///
	/// If `Active` or `Suspicious` delegates to timed update of the link.
	/// Otherwise checks if it is time to reach out, in which case it will
	/// select an address from the known addresses.
	//TODO: fix these docs
	#[tracing::instrument(skip_all, fields(self = %self))]
	#[must_use = "assumes due ping will be sent"]
	pub fn tick(&mut self) -> TickResult {
		let result = match self.state {
			Active | Suspicious => self.tick_link(),
			Indirect => match remaining(self.seen_by_peer, INDIRECT_TIMEOUT) {
				Some(time) => {
					let mut res = self.reach_out();
					res.next_tick_in = res.next_tick_in.min(time);
					res
				},
				//TODO: don't reset reached_out_to here
				None => self.go_unreachable()
			},
			Quit | Unreachable => self.reach_out()
		};
		debug!(?result);
		result
	}

	fn tick_link(&mut self) -> TickResult {
		use LinkTickResult as Ltr;
		match self.link.as_mut().map(Link::tick) {
			Some(Ltr::Ok(time)) => TickResult {
				address_to_ping: None,
				state_changed: None,
				reach_out_to: None,
				next_tick_in: time
			},
			Some(Ltr::PingDue(time)) => TickResult {
				address_to_ping: self.get_address(),
				state_changed: None,
				reach_out_to: None,
				next_tick_in: time
			},
			Some(Ltr::LinkSuspicious(time)) => {
				info!(addr = %self.get_address().unwrap(), "link suspicious");
				self.state = Suspicious;
				TickResult {
					address_to_ping: self.get_address(),
					state_changed: Some(Suspicious),
					reach_out_to: None,
					next_tick_in: time
				}
			},
			Some(Ltr::LinkUnreachable) => self.go_unreachable(),
			None => {
				error!("called tick_link() without active link");
				self.go_unreachable()
			}
		}
	}

	fn go_unreachable(&mut self) -> TickResult {
		info!(addr = ?self.get_address(), "link is unreachable");
		self.state = Unreachable;
		// clear reached_out_to
		self.reached_out_to.take();
		// Link should get dropped at this point
		let mut res = self.reach_out();
		res.state_changed.replace(Unreachable);
		res
	}

	fn reach_out(&mut self) -> TickResult {
		match remaining(self.reached_out_to, REACH_OUT_TIME) {
			_ if self.known_addrs == 0 => TickResult {
				address_to_ping: None,
				state_changed: None,
				reach_out_to: None,
				next_tick_in: Duration::MAX
			},
			Some(next_tick_in) => TickResult {
				address_to_ping: None,
				state_changed: None,
				reach_out_to: None,
				next_tick_in
			},
			None => {
				self.reached_out_to = Some(SystemTime::now());
				self.addr_reach_out_idx += 1;
				TickResult {
					address_to_ping: None,
					state_changed: None,
					reach_out_to: Some(self.addr_reach_out_idx),
					next_tick_in: REACH_OUT_TIME
				}
			}
		}
	}

}

impl From<Peer> for Conspirator {
	fn from(other: Peer) -> Conspirator {
		Conspirator {
			id: other.id.into(),
			name: other.name,
			state: other.state,
			link: other.link
		}
	}
}

impl std::fmt::Display for Peer {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "[{}] {} ({:?})", self.id, self.name, self.state)?;
		if self.clk != Clock::null_clock() {
			write!(f, " @ {}", self.clk)?;
		}
		if let Some(ref l) = self.link {write!(f, ", Link {{{l}}}")?;}
		if self.new_addr_pending {
			write!(f, " (new address, sync pending)")?;
		}
		if let Some(seen) = self.seen_by_peer {
			write!(f, ", seen by peer ")?;
			fmt_time(f, seen)?;
		}
		if self.addr_reach_out_idx != 0 || self.reached_out_to.is_some() {
			write!(
				f,
				", reached out: (idx: {})",
				self.addr_reach_out_idx + 1
			)?;
			//TODO: put known_addrs back in
			if let Some(reached_out) = self.reached_out_to {
				write!(f, " ")?;
				fmt_time(f, reached_out)?;
			}
		}
		Ok(())
	}
}