sc_utils/
notification.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Provides mpsc notification channel that can be instantiated
19//! _after_ it's been shared to the consumer and producers entities.
20//!
21//! Useful when building RPC extensions where, at service definition time, we
22//! don't know whether the specific interface where the RPC extension will be
23//! exposed is safe or not and we want to lazily build the RPC extension
24//! whenever we bind the service to an interface.
25//!
26//! See [`sc-service::builder::RpcExtensionBuilder`] for more details.
27
28use futures::stream::{FusedStream, Stream};
29use std::{
30	pin::Pin,
31	task::{Context, Poll},
32};
33
34use crate::pubsub::{Hub, Receiver};
35
36mod registry;
37use registry::Registry;
38
39#[cfg(test)]
40mod tests;
41
42/// Trait used to define the "tracing key" string used to tag
43/// and identify the mpsc channels.
44pub trait TracingKeyStr {
45	/// Const `str` representing the "tracing key" used to tag and identify
46	/// the mpsc channels owned by the object implementing this trait.
47	const TRACING_KEY: &'static str;
48}
49
50/// The receiving half of the notifications channel.
51///
52/// The [`NotificationStream`] entity stores the [`Hub`] so it can be
53/// used to add more subscriptions.
54#[derive(Clone)]
55pub struct NotificationStream<Payload, TK: TracingKeyStr> {
56	hub: Hub<Payload, Registry>,
57	_pd: std::marker::PhantomData<TK>,
58}
59
60/// The receiving half of the notifications channel(s).
61#[derive(Debug)]
62pub struct NotificationReceiver<Payload> {
63	receiver: Receiver<Payload, Registry>,
64}
65
66/// The sending half of the notifications channel(s).
67pub struct NotificationSender<Payload> {
68	hub: Hub<Payload, Registry>,
69}
70
71impl<Payload, TK: TracingKeyStr> NotificationStream<Payload, TK> {
72	/// Creates a new pair of receiver and sender of `Payload` notifications.
73	pub fn channel() -> (NotificationSender<Payload>, Self) {
74		let hub = Hub::new(TK::TRACING_KEY);
75		let sender = NotificationSender { hub: hub.clone() };
76		let receiver = NotificationStream { hub, _pd: Default::default() };
77		(sender, receiver)
78	}
79
80	/// Subscribe to a channel through which the generic payload can be received.
81	pub fn subscribe(&self, queue_size_warning: usize) -> NotificationReceiver<Payload> {
82		let receiver = self.hub.subscribe((), queue_size_warning);
83		NotificationReceiver { receiver }
84	}
85}
86
87impl<Payload> NotificationSender<Payload> {
88	/// Send out a notification to all subscribers that a new payload is available for a
89	/// block.
90	pub fn notify<Error>(
91		&self,
92		payload: impl FnOnce() -> Result<Payload, Error>,
93	) -> Result<(), Error>
94	where
95		Payload: Clone,
96	{
97		self.hub.send(payload)
98	}
99}
100
101impl<Payload> Clone for NotificationSender<Payload> {
102	fn clone(&self) -> Self {
103		Self { hub: self.hub.clone() }
104	}
105}
106
107impl<Payload> Unpin for NotificationReceiver<Payload> {}
108
109impl<Payload> Stream for NotificationReceiver<Payload> {
110	type Item = Payload;
111
112	fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Payload>> {
113		Pin::new(&mut self.get_mut().receiver).poll_next(cx)
114	}
115}
116
117impl<Payload> FusedStream for NotificationReceiver<Payload> {
118	fn is_terminated(&self) -> bool {
119		self.receiver.is_terminated()
120	}
121}