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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! JSON-RPC client implementation.

#![deny(missing_docs)]

use jsonrpc_core::futures::channel::{mpsc, oneshot};
use jsonrpc_core::futures::{
	self,
	task::{Context, Poll},
	Future, Stream, StreamExt,
};
use jsonrpc_core::{Error, Params};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::marker::PhantomData;
use std::pin::Pin;

pub mod transports;

#[cfg(test)]
mod logger;

/// The errors returned by the client.
#[derive(Debug, derive_more::Display)]
pub enum RpcError {
	/// An error returned by the server.
	#[display(fmt = "Server returned rpc error {}", _0)]
	JsonRpcError(Error),
	/// Failure to parse server response.
	#[display(fmt = "Failed to parse server response as {}: {}", _0, _1)]
	ParseError(String, Box<dyn std::error::Error + Send>),
	/// Request timed out.
	#[display(fmt = "Request timed out")]
	Timeout,
	/// A general client error.
	#[display(fmt = "Client error: {}", _0)]
	Client(String),
	/// Not rpc specific errors.
	#[display(fmt = "{}", _0)]
	Other(Box<dyn std::error::Error + Send>),
}

impl std::error::Error for RpcError {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		match *self {
			Self::JsonRpcError(ref e) => Some(e),
			Self::ParseError(_, ref e) => Some(&**e),
			Self::Other(ref e) => Some(&**e),
			_ => None,
		}
	}
}

impl From<Error> for RpcError {
	fn from(error: Error) -> Self {
		RpcError::JsonRpcError(error)
	}
}

/// A result returned by the client.
pub type RpcResult<T> = Result<T, RpcError>;

/// An RPC call message.
struct CallMessage {
	/// The RPC method name.
	method: String,
	/// The RPC method parameters.
	params: Params,
	/// The oneshot channel to send the result of the rpc
	/// call to.
	sender: oneshot::Sender<RpcResult<Value>>,
}

/// An RPC notification.
struct NotifyMessage {
	/// The RPC method name.
	method: String,
	/// The RPC method paramters.
	params: Params,
}

/// An RPC subscription.
struct Subscription {
	/// The subscribe method name.
	subscribe: String,
	/// The subscribe method parameters.
	subscribe_params: Params,
	/// The name of the notification.
	notification: String,
	/// The unsubscribe method name.
	unsubscribe: String,
}

/// An RPC subscribe message.
struct SubscribeMessage {
	/// The subscription to subscribe to.
	subscription: Subscription,
	/// The channel to send notifications to.
	sender: mpsc::UnboundedSender<RpcResult<Value>>,
}

/// A message sent to the `RpcClient`.
enum RpcMessage {
	/// Make an RPC call.
	Call(CallMessage),
	/// Send a notification.
	Notify(NotifyMessage),
	/// Subscribe to a notification.
	Subscribe(SubscribeMessage),
}

impl From<CallMessage> for RpcMessage {
	fn from(msg: CallMessage) -> Self {
		RpcMessage::Call(msg)
	}
}

impl From<NotifyMessage> for RpcMessage {
	fn from(msg: NotifyMessage) -> Self {
		RpcMessage::Notify(msg)
	}
}

impl From<SubscribeMessage> for RpcMessage {
	fn from(msg: SubscribeMessage) -> Self {
		RpcMessage::Subscribe(msg)
	}
}

/// A channel to a `RpcClient`.
#[derive(Clone)]
pub struct RpcChannel(mpsc::UnboundedSender<RpcMessage>);

impl RpcChannel {
	fn send(&self, msg: RpcMessage) -> Result<(), mpsc::TrySendError<RpcMessage>> {
		self.0.unbounded_send(msg)
	}
}

impl From<mpsc::UnboundedSender<RpcMessage>> for RpcChannel {
	fn from(sender: mpsc::UnboundedSender<RpcMessage>) -> Self {
		RpcChannel(sender)
	}
}

/// The future returned by the rpc call.
pub type RpcFuture = oneshot::Receiver<Result<Value, RpcError>>;

/// The stream returned by a subscribe.
pub type SubscriptionStream = mpsc::UnboundedReceiver<Result<Value, RpcError>>;

/// A typed subscription stream.
pub struct TypedSubscriptionStream<T> {
	_marker: PhantomData<T>,
	returns: &'static str,
	stream: SubscriptionStream,
}

impl<T> TypedSubscriptionStream<T> {
	/// Creates a new `TypedSubscriptionStream`.
	pub fn new(stream: SubscriptionStream, returns: &'static str) -> Self {
		TypedSubscriptionStream {
			_marker: PhantomData,
			returns,
			stream,
		}
	}
}

impl<T: DeserializeOwned + Unpin + 'static> Stream for TypedSubscriptionStream<T> {
	type Item = RpcResult<T>;

	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
		let result = futures::ready!(self.stream.poll_next_unpin(cx));
		match result {
			Some(Ok(value)) => Some(
				serde_json::from_value::<T>(value)
					.map_err(|error| RpcError::ParseError(self.returns.into(), Box::new(error))),
			),
			None => None,
			Some(Err(err)) => Some(Err(err)),
		}
		.into()
	}
}

/// Client for raw JSON RPC requests
#[derive(Clone)]
pub struct RawClient(RpcChannel);

impl From<RpcChannel> for RawClient {
	fn from(channel: RpcChannel) -> Self {
		RawClient(channel)
	}
}

impl RawClient {
	/// Call RPC method with raw JSON.
	pub fn call_method(&self, method: &str, params: Params) -> impl Future<Output = RpcResult<Value>> {
		let (sender, receiver) = oneshot::channel();
		let msg = CallMessage {
			method: method.into(),
			params,
			sender,
		};
		let result = self.0.send(msg.into());
		async move {
			let () = result.map_err(|e| RpcError::Other(Box::new(e)))?;

			receiver.await.map_err(|e| RpcError::Other(Box::new(e)))?
		}
	}

	/// Send RPC notification with raw JSON.
	pub fn notify(&self, method: &str, params: Params) -> RpcResult<()> {
		let msg = NotifyMessage {
			method: method.into(),
			params,
		};
		match self.0.send(msg.into()) {
			Ok(()) => Ok(()),
			Err(error) => Err(RpcError::Other(Box::new(error))),
		}
	}

	/// Subscribe to topic with raw JSON.
	pub fn subscribe(
		&self,
		subscribe: &str,
		subscribe_params: Params,
		notification: &str,
		unsubscribe: &str,
	) -> RpcResult<SubscriptionStream> {
		let (sender, receiver) = mpsc::unbounded();
		let msg = SubscribeMessage {
			subscription: Subscription {
				subscribe: subscribe.into(),
				subscribe_params,
				notification: notification.into(),
				unsubscribe: unsubscribe.into(),
			},
			sender,
		};

		self.0
			.send(msg.into())
			.map(|()| receiver)
			.map_err(|e| RpcError::Other(Box::new(e)))
	}
}

/// Client for typed JSON RPC requests
#[derive(Clone)]
pub struct TypedClient(RawClient);

impl From<RpcChannel> for TypedClient {
	fn from(channel: RpcChannel) -> Self {
		TypedClient(channel.into())
	}
}

impl TypedClient {
	/// Create a new `TypedClient`.
	pub fn new(raw_cli: RawClient) -> Self {
		TypedClient(raw_cli)
	}

	/// Call RPC with serialization of request and deserialization of response.
	pub fn call_method<T: Serialize, R: DeserializeOwned>(
		&self,
		method: &str,
		returns: &str,
		args: T,
	) -> impl Future<Output = RpcResult<R>> {
		let returns = returns.to_owned();
		let args =
			serde_json::to_value(args).expect("Only types with infallible serialisation can be used for JSON-RPC");
		let params = match args {
			Value::Array(vec) => Ok(Params::Array(vec)),
			Value::Null => Ok(Params::None),
			Value::Object(map) => Ok(Params::Map(map)),
			_ => Err(RpcError::Client(
				"RPC params should serialize to a JSON array, JSON object or null".into(),
			)),
		};
		let result = params.map(|params| self.0.call_method(method, params));

		async move {
			let value: Value = result?.await?;

			log::debug!("response: {:?}", value);

			serde_json::from_value::<R>(value).map_err(|error| RpcError::ParseError(returns, Box::new(error)))
		}
	}

	/// Call RPC with serialization of request only.
	pub fn notify<T: Serialize>(&self, method: &str, args: T) -> RpcResult<()> {
		let args =
			serde_json::to_value(args).expect("Only types with infallible serialisation can be used for JSON-RPC");
		let params = match args {
			Value::Array(vec) => Params::Array(vec),
			Value::Null => Params::None,
			_ => {
				return Err(RpcError::Client(
					"RPC params should serialize to a JSON array, or null".into(),
				))
			}
		};

		self.0.notify(method, params)
	}

	/// Subscribe with serialization of request and deserialization of response.
	pub fn subscribe<T: Serialize, R: DeserializeOwned + 'static>(
		&self,
		subscribe: &str,
		subscribe_params: T,
		topic: &str,
		unsubscribe: &str,
		returns: &'static str,
	) -> RpcResult<TypedSubscriptionStream<R>> {
		let args = serde_json::to_value(subscribe_params)
			.expect("Only types with infallible serialisation can be used for JSON-RPC");

		let params = match args {
			Value::Array(vec) => Params::Array(vec),
			Value::Null => Params::None,
			_ => {
				return Err(RpcError::Client(
					"RPC params should serialize to a JSON array, or null".into(),
				))
			}
		};

		self.0
			.subscribe(subscribe, params, topic, unsubscribe)
			.map(move |stream| TypedSubscriptionStream::new(stream, returns))
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::transports::local;
	use crate::{RpcChannel, TypedClient};
	use jsonrpc_core::futures::{future, FutureExt};
	use jsonrpc_core::{self as core, IoHandler};
	use jsonrpc_pubsub::{PubSubHandler, Subscriber, SubscriptionId};
	use std::sync::atomic::{AtomicBool, Ordering};
	use std::sync::Arc;

	#[derive(Clone)]
	struct AddClient(TypedClient);

	impl From<RpcChannel> for AddClient {
		fn from(channel: RpcChannel) -> Self {
			AddClient(channel.into())
		}
	}

	impl AddClient {
		fn add(&self, a: u64, b: u64) -> impl Future<Output = RpcResult<u64>> {
			self.0.call_method("add", "u64", (a, b))
		}

		fn completed(&self, success: bool) -> RpcResult<()> {
			self.0.notify("completed", (success,))
		}
	}

	#[test]
	fn test_client_terminates() {
		crate::logger::init_log();
		let mut handler = IoHandler::new();
		handler.add_sync_method("add", |params: Params| {
			let (a, b) = params.parse::<(u64, u64)>()?;
			let res = a + b;
			Ok(jsonrpc_core::to_value(res).unwrap())
		});

		let (tx, rx) = std::sync::mpsc::channel();
		let (client, rpc_client) = local::connect::<AddClient, _, _>(handler);
		let fut = async move {
			let res = client.add(3, 4).await?;
			let res = client.add(res, 5).await?;
			assert_eq!(res, 12);
			tx.send(()).unwrap();
			Ok(()) as RpcResult<_>
		};
		let pool = futures::executor::ThreadPool::builder().pool_size(1).create().unwrap();
		pool.spawn_ok(rpc_client.map(|x| x.unwrap()));
		pool.spawn_ok(fut.map(|x| x.unwrap()));
		rx.recv().unwrap()
	}

	#[test]
	fn should_send_notification() {
		crate::logger::init_log();
		let (tx, rx) = std::sync::mpsc::sync_channel(1);
		let mut handler = IoHandler::new();
		handler.add_notification("completed", move |params: Params| {
			let (success,) = params.parse::<(bool,)>().expect("expected to receive one boolean");
			assert_eq!(success, true);
			tx.send(()).unwrap();
		});

		let (client, rpc_client) = local::connect::<AddClient, _, _>(handler);
		client.completed(true).unwrap();
		let pool = futures::executor::ThreadPool::builder().pool_size(1).create().unwrap();
		pool.spawn_ok(rpc_client.map(|x| x.unwrap()));
		rx.recv().unwrap()
	}

	#[test]
	fn should_handle_subscription() {
		crate::logger::init_log();
		// given
		let (finish, finished) = std::sync::mpsc::sync_channel(1);
		let mut handler = PubSubHandler::<local::LocalMeta, _>::default();
		let called = Arc::new(AtomicBool::new(false));
		let called2 = called.clone();
		handler.add_subscription(
			"hello",
			("subscribe_hello", move |params, _meta, subscriber: Subscriber| {
				assert_eq!(params, core::Params::None);
				let sink = subscriber
					.assign_id(SubscriptionId::Number(5))
					.expect("assigned subscription id");
				let finish = finish.clone();
				std::thread::spawn(move || {
					for i in 0..3 {
						std::thread::sleep(std::time::Duration::from_millis(100));
						let value = serde_json::json!({
							"subscription": 5,
							"result": vec![i],
						});
						let _ = sink.notify(serde_json::from_value(value).unwrap());
					}
					finish.send(()).unwrap();
				});
			}),
			("unsubscribe_hello", move |id, _meta| {
				// Should be called because session is dropped.
				called2.store(true, Ordering::SeqCst);
				assert_eq!(id, SubscriptionId::Number(5));
				future::ready(Ok(core::Value::Bool(true)))
			}),
		);

		// when
		let (tx, rx) = std::sync::mpsc::channel();
		let (client, rpc_client) = local::connect_with_pubsub::<TypedClient, _>(handler);
		let received = Arc::new(std::sync::Mutex::new(vec![]));
		let r2 = received.clone();
		let fut = async move {
			let mut stream =
				client.subscribe::<_, (u32,)>("subscribe_hello", (), "hello", "unsubscribe_hello", "u32")?;
			let result = stream.next().await;
			r2.lock().unwrap().push(result.expect("Expected at least one item."));
			tx.send(()).unwrap();
			Ok(()) as RpcResult<_>
		};

		let pool = futures::executor::ThreadPool::builder().pool_size(1).create().unwrap();
		pool.spawn_ok(rpc_client.map(|_| ()));
		pool.spawn_ok(fut.map(|x| x.unwrap()));

		rx.recv().unwrap();
		assert!(
			!received.lock().unwrap().is_empty(),
			"Expected at least one received item."
		);
		// The session is being dropped only when another notification is received.
		// TODO [ToDr] we should unsubscribe as soon as the stream is dropped instead!
		finished.recv().unwrap();
		assert_eq!(called.load(Ordering::SeqCst), true, "Unsubscribe not called.");
	}
}