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
//!
//!

pub(crate) mod client;
pub(crate) mod server;

use crate::error::{StreamError, TaskError};
use crate::util::watch;

use tokio::sync::{oneshot, mpsc};
use tokio::task::JoinHandle;

/// Used in Client and Server
pub(crate) enum SendBack<P> {
	None,
	Packet(P),
	Close,
	CloseWithPacket
}

/// A Handle to a background task, if this handle is dropped
/// the connection will be dropped.
pub(crate) struct TaskHandle {
	pub close: oneshot::Sender<()>,
	pub task: JoinHandle<Result<(), TaskError>>
}

impl TaskHandle {
	/// Wait until the connection has nothing more todo which will then close
	/// the connection.
	pub async fn wait(self) -> Result<(), TaskError> {
		self.task.await
			.map_err(TaskError::Join)?
	}

	/// Send a close signal to the background task and wait until it closes.
	pub async fn close(self) -> Result<(), TaskError> {
		let _ = self.close.send(());
		self.task.await
			.map_err(TaskError::Join)?
	}

	// used for testing
	#[cfg(test)]
	pub fn abort(self) {
		self.task.abort();
	}
}

/// A sender of packets to an open stream.
#[derive(Debug, Clone)]
pub struct StreamSender<P> {
	pub(crate) inner: mpsc::Sender<P>
}

impl<P> StreamSender<P> {
	pub(crate) fn new(inner: mpsc::Sender<P>) -> Self {
		Self { inner }
	}

	/// Sends a packet to the client or the server.
	pub async fn send(&self, packet: P) -> Result<(), StreamError> {
		self.inner.send(packet).await
			.map_err(|_| StreamError::StreamAlreadyClosed)
	}
}

/// A stream of packets which is inside of a connection.
#[derive(Debug)]
pub struct StreamReceiver<P> {
	pub(crate) inner: mpsc::Receiver<P>
}

impl<P> StreamReceiver<P> {
	pub(crate) fn new(inner: mpsc::Receiver<P>) -> Self {
		Self { inner }
	}

	/// If none is returned this can mean that the connection
	/// was closed or the other side is finished sending.
	pub async fn receive(&mut self) -> Option<P> {
		self.inner.recv().await
	}

	/// Marks the stream as closed but allows to receive the remaining
	/// messages.
	pub fn close(&mut self) {
		self.inner.close();
	}
}

#[derive(Debug, Clone)]
pub struct Configurator<C> {
	inner: watch::Sender<C>
}

impl<C> Configurator<C> {
	pub(crate) fn new(inner: watch::Sender<C>) -> Self {
		Self { inner }
	}

	/// It is possible that there are no receivers left.
	/// 
	/// This is not checked
	pub fn update(&self, cfg: C) {
		self.inner.send(cfg);
	}

	pub fn read(&self) -> C
	where C: Clone {
		self.inner.newest()
	}
}