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
use tokio::sync::mpsc;
use tokio::sync::oneshot;

use crate::error;
use crate::peer::Command;
use crate::Message;

/// A handle for a sent request.
///
/// The handle can be used to receive updates and the response from the remote peer,
/// and to send update messages to the remote peer.
pub struct SentRequest<Body> {
	request_id: u32,
	service_id: i32,
	incoming_rx: mpsc::UnboundedReceiver<Message<Body>>,
	command_tx: mpsc::UnboundedSender<Command<Body>>,
}

/// A handle for a received request.
///
/// The handle can be used to receive updates from the remote peer,
/// and to send updates and the response to the remote peer.
pub struct ReceivedRequest<Body> {
	request_id: u32,
	service_id: i32,
	body: Body,
	incoming_rx: mpsc::UnboundedReceiver<Message<Body>>,
	command_tx: mpsc::UnboundedSender<Command<Body>>,
}

/// An incoming request or stream message.
pub enum Incoming<Body> {
	/// An incoming request.
	Request(ReceivedRequest<Body>),

	/// An incoming stream message.
	Stream(Message<Body>),
}

/// An outgoing request or stream message.
pub enum Outgoing<Body> {
	/// An outgoing request.
	Request(SentRequest<Body>),

	/// An outgoing stream message.
	Stream(Message<Body>),
}

impl<Body> SentRequest<Body> {
	/// Create a new sent request.
	pub(crate) fn new(
		request_id: u32,
		service_id: i32,
		incoming_rx: mpsc::UnboundedReceiver<Message<Body>>,
		command_tx: mpsc::UnboundedSender<Command<Body>>,
	) -> Self {
		Self {
			request_id,
			service_id,
			incoming_rx,
			command_tx,
		}
	}

	/// Get the request ID of the sent request.
	pub fn request_id(&self) -> u32 {
		self.request_id
	}

	/// Get the service ID of the initial request message.
	pub fn service_id(&self) -> i32 {
		self.service_id
	}

	/// Receive the next message from the request.
	///
	/// This could be an update message or a response message.
	// TODO: change return type to eliminate impossible message types?
	pub async fn next_message(&mut self) -> Result<Message<Body>, error::NextMessageError> {
		Ok(self.incoming_rx.recv().await.ok_or_else(error::connection_aborted)?)
	}

	/// Send an update for the request.
	pub async fn send_update(&mut self, service_id: i32, body: impl Into<Body>) -> Result<(), error::WriteMessageError> {
		use crate::peer::SendRawMessage;
		let body = body.into();
		let (result_tx, result_rx) = oneshot::channel();
		let message = Message::requester_update(self.request_id, service_id, body);
		self.command_tx
			.send(SendRawMessage { message, result_tx }.into())
			.map_err(|_| error::connection_aborted())?;
		result_rx.await.map_err(|_| error::connection_aborted())?
	}
}

impl<Body> ReceivedRequest<Body> {
	/// Create a new received request.
	pub(crate) fn new(
		request_id: u32,
		service_id: i32,
		body: Body,
		incoming_rx: mpsc::UnboundedReceiver<Message<Body>>,
		command_tx: mpsc::UnboundedSender<Command<Body>>,
	) -> Self {
		Self {
			request_id,
			service_id,
			body,
			incoming_rx,
			command_tx,
		}
	}

	/// Get the request ID of the received request.
	pub fn request_id(&self) -> u32 {
		self.request_id
	}

	/// Get the service ID of the initial request message.
	pub fn service_id(&self) -> i32 {
		self.service_id
	}

	/// Get the body of the initial request message.
	pub fn body(&self) -> &Body {
		&self.body
	}

	/// Receive the next message from the request.
	///
	/// This can only be an update message.
	// TODO: change return type to eliminate impossible message types?
	pub async fn next_message(&mut self) -> Result<Message<Body>, error::ReadMessageError> {
		Ok(self.incoming_rx.recv().await.ok_or_else(error::connection_aborted)?)
	}

	/// Send an update for the request.
	pub async fn send_update(&mut self, service_id: i32, body: impl Into<Body>) -> Result<(), error::WriteMessageError> {
		let body = body.into();
		self.send_raw_message(Message::responder_update(self.request_id, service_id, body)).await
	}

	/// Send the final response.
	pub async fn send_response(mut self, service_id: i32, body: impl Into<Body>) -> Result<(), error::WriteMessageError> {
		let body = body.into();
		self.send_raw_message(Message::response(self.request_id, service_id, body)).await
	}

	/// Send the final response with an error message.
	pub async fn send_error_response(mut self, message: &str) -> Result<(), error::WriteMessageError>
	where
		Body: crate::Body,
	{
		self.send_raw_message(Message::error_response(self.request_id, message)).await
	}

	/// Send a raw message.
	async fn send_raw_message(&mut self, message: Message<Body>) -> Result<(), error::WriteMessageError> {
		use crate::peer::SendRawMessage;
		let (result_tx, result_rx) = oneshot::channel();
		self.command_tx
			.send(SendRawMessage { message, result_tx }.into())
			.map_err(|_| error::connection_aborted())?;
		result_rx.await.map_err(|_| error::connection_aborted())?
	}
}

impl<Body> std::fmt::Debug for SentRequest<Body> {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		// TODO: use finish_non_exhaustive when it hits stable.
		f.debug_struct("SentRequest")
			.field("request_id", &self.request_id)
			.field("service_id", &self.service_id)
			.finish()
	}
}

impl<Body> std::fmt::Debug for ReceivedRequest<Body> {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		// TODO: use finish_non_exhaustive when it hits stable.
		f.debug_struct("ReceivedRequest")
			.field("request_id", &self.request_id)
			.field("service_id", &self.service_id)
			.finish()
	}
}

impl<Body> std::fmt::Debug for Incoming<Body> {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		match self {
			Self::Request(x) => {
				write!(f, "ReceivedRequest(")?;
				x.fmt(f)?;
				write!(f, ")")?;
			},
			Self::Stream(x) => {
				write!(f, "Stream(")?;
				x.fmt(f)?;
				write!(f, ")")?;
			},
		}
		Ok(())
	}
}