lib.rs 53.6 KB
Newer Older
Fedor Sakharov's avatar
Fedor Sakharov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! # Overseer
//!
//! `overseer` implements the Overseer architecture described in the
20
//! [implementers-guide](https://github.com/paritytech/polkadot/blob/master/roadmap/implementers-guide/guide.md).
Fedor Sakharov's avatar
Fedor Sakharov committed
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
//! For the motivations behind implementing the overseer itself you should
//! check out that guide, documentation in this crate will be mostly discussing
//! technical stuff.
//!
//! An `Overseer` is something that allows spawning/stopping and overseing
//! asynchronous tasks as well as establishing a well-defined and easy to use
//! protocol that the tasks can use to communicate with each other. It is desired
//! that this protocol is the only way tasks communicate with each other, however
//! at this moment there are no foolproof guards against other ways of communication.
//!
//! The `Overseer` is instantiated with a pre-defined set of `Subsystems` that
//! share the same behavior from `Overseer`'s point of view.
//!
//! ```text
//!                              +-----------------------------+
//!                              |         Overseer            |
//!                              +-----------------------------+
//!
//!             ................|  Overseer "holds" these and uses |..............
//!             .                  them to (re)start things                      .
//!             .                                                                .
//!             .  +-------------------+                +---------------------+  .
//!             .  |   Subsystem1      |                |   Subsystem2        |  .
//!             .  +-------------------+                +---------------------+  .
//!             .           |                                       |            .
//!             ..................................................................
//!                         |                                       |
//!                       start()                                 start()
//!                         V                                       V
//!             ..................| Overseer "runs" these |.......................
//!             .  +--------------------+               +---------------------+  .
//!             .  | SubsystemInstance1 |               | SubsystemInstance2  |  .
//!             .  +--------------------+               +---------------------+  .
//!             ..................................................................
//! ```

use std::fmt::Debug;
use std::pin::Pin;
59
use std::sync::Arc;
Fedor Sakharov's avatar
Fedor Sakharov committed
60
61
use std::task::Poll;
use std::time::Duration;
62
use std::collections::HashSet;
Fedor Sakharov's avatar
Fedor Sakharov committed
63
64
65
66

use futures::channel::{mpsc, oneshot};
use futures::{
	pending, poll, select,
67
	future::BoxFuture,
68
	stream::{self, FuturesUnordered},
Fedor Sakharov's avatar
Fedor Sakharov committed
69
70
71
72
73
	Future, FutureExt, SinkExt, StreamExt,
};
use futures_timer::Delay;
use streamunordered::{StreamYield, StreamUnordered};

asynchronous rob's avatar
asynchronous rob committed
74
use polkadot_primitives::v1::{Block, BlockNumber, Hash};
75
use client::{BlockImportNotification, BlockchainEvents, FinalityNotification};
76

77
use polkadot_subsystem::messages::{
78
	CandidateValidationMessage, CandidateBackingMessage,
79
	CandidateSelectionMessage, ChainApiMessage, StatementDistributionMessage,
80
	AvailabilityDistributionMessage, BitfieldSigningMessage, BitfieldDistributionMessage,
81
82
	ProvisionerMessage, PoVDistributionMessage, RuntimeApiMessage,
	AvailabilityStoreMessage, NetworkBridgeMessage, AllMessages, CollationGenerationMessage, CollatorProtocolMessage,
83
84
85
};
pub use polkadot_subsystem::{
	Subsystem, SubsystemContext, OverseerSignal, FromOverseer, SubsystemError, SubsystemResult,
86
	SpawnedSubsystem, ActiveLeavesUpdate,
87
};
88
use polkadot_node_primitives::SpawnNamed;
89

Fedor Sakharov's avatar
Fedor Sakharov committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

// A capacity of bounded channels inside the overseer.
const CHANNEL_CAPACITY: usize = 1024;
// A graceful `Overseer` teardown time delay.
const STOP_DELAY: u64 = 1;

/// A type of messages that are sent from [`Subsystem`] to [`Overseer`].
///
/// It wraps a system-wide [`AllMessages`] type that represents all possible
/// messages in the system.
///
/// [`AllMessages`]: enum.AllMessages.html
/// [`Subsystem`]: trait.Subsystem.html
/// [`Overseer`]: struct.Overseer.html
enum ToOverseer {
	/// This is a message sent by a `Subsystem`.
	SubsystemMessage(AllMessages),

	/// A message that wraps something the `Subsystem` is desiring to
	/// spawn on the overseer and a `oneshot::Sender` to signal the result
	/// of the spawn.
	SpawnJob {
112
		name: &'static str,
Fedor Sakharov's avatar
Fedor Sakharov committed
113
114
		s: BoxFuture<'static, ()>,
	},
115
116
117
118
119
120
121

	/// Same as `SpawnJob` but for blocking tasks to be executed on a
	/// dedicated thread pool.
	SpawnBlockingJob {
		name: &'static str,
		s: BoxFuture<'static, ()>,
	},
Fedor Sakharov's avatar
Fedor Sakharov committed
122
123
}

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/// An event telling the `Overseer` on the particular block
/// that has been imported or finalized.
///
/// This structure exists solely for the purposes of decoupling
/// `Overseer` code from the client code and the necessity to call
/// `HeaderBackend::block_number_from_id()`.
pub struct BlockInfo {
	/// hash of the block.
	pub hash: Hash,
	/// hash of the parent block.
	pub parent_hash: Hash,
	/// block's number.
	pub number: BlockNumber,
}

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
impl From<BlockImportNotification<Block>> for BlockInfo {
	fn from(n: BlockImportNotification<Block>) -> Self {
		BlockInfo {
			hash: n.hash,
			parent_hash: n.header.parent_hash,
			number: n.header.number,
		}
	}
}

impl From<FinalityNotification<Block>> for BlockInfo {
	fn from(n: FinalityNotification<Block>) -> Self {
		BlockInfo {
			hash: n.hash,
			parent_hash: n.header.parent_hash,
			number: n.header.number,
		}
	}
}

Fedor Sakharov's avatar
Fedor Sakharov committed
159
160
/// Some event from outer world.
enum Event {
161
162
	BlockImported(BlockInfo),
	BlockFinalized(BlockInfo),
Fedor Sakharov's avatar
Fedor Sakharov committed
163
164
165
166
167
168
169
	MsgToSubsystem(AllMessages),
	Stop,
}

/// A handler used to communicate with the [`Overseer`].
///
/// [`Overseer`]: struct.Overseer.html
170
#[derive(Clone)]
Fedor Sakharov's avatar
Fedor Sakharov committed
171
172
173
174
175
176
pub struct OverseerHandler {
	events_tx: mpsc::Sender<Event>,
}

impl OverseerHandler {
	/// Inform the `Overseer` that that some block was imported.
177
178
	pub async fn block_imported(&mut self, block: BlockInfo) -> SubsystemResult<()> {
		self.events_tx.send(Event::BlockImported(block)).await?;
Fedor Sakharov's avatar
Fedor Sakharov committed
179
180
181
182
183
184
185
186
187
188
189
190

		Ok(())
	}

	/// Send some message to one of the `Subsystem`s.
	pub async fn send_msg(&mut self, msg: AllMessages) -> SubsystemResult<()> {
		self.events_tx.send(Event::MsgToSubsystem(msg)).await?;

		Ok(())
	}

	/// Inform the `Overseer` that that some block was finalized.
191
192
	pub async fn block_finalized(&mut self, block: BlockInfo) -> SubsystemResult<()> {
		self.events_tx.send(Event::BlockFinalized(block)).await?;
Fedor Sakharov's avatar
Fedor Sakharov committed
193
194
195
196
197
198
199
200
201
202
203
204

		Ok(())
	}

	/// Tell `Overseer` to shutdown.
	pub async fn stop(&mut self) -> SubsystemResult<()> {
		self.events_tx.send(Event::Stop).await?;

		Ok(())
	}
}

205
/// Glues together the [`Overseer`] and `BlockchainEvents` by forwarding
206
207
208
209
210
/// import and finality notifications into the [`OverseerHandler`].
///
/// [`Overseer`]: struct.Overseer.html
/// [`OverseerHandler`]: struct.OverseerHandler.html
pub async fn forward_events<P: BlockchainEvents<Block>>(
211
	client: Arc<P>,
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
	mut handler: OverseerHandler,
) -> SubsystemResult<()> {
	let mut finality = client.finality_notification_stream();
	let mut imports = client.import_notification_stream();

	loop {
		select! {
			f = finality.next() => {
				match f {
					Some(block) => {
						handler.block_finalized(block.into()).await?;
					}
					None => break,
				}
			},
			i = imports.next() => {
				match i {
					Some(block) => {
						handler.block_imported(block.into()).await?;
					}
					None => break,
				}
			},
			complete => break,
		}
	}

	Ok(())
}

Fedor Sakharov's avatar
Fedor Sakharov committed
242
243
244
245
246
247
impl Debug for ToOverseer {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			ToOverseer::SubsystemMessage(msg) => {
				write!(f, "OverseerMessage::SubsystemMessage({:?})", msg)
			}
248
249
			ToOverseer::SpawnJob { .. } => write!(f, "OverseerMessage::Spawn(..)"),
			ToOverseer::SpawnBlockingJob { .. } => write!(f, "OverseerMessage::SpawnBlocking(..)")
Fedor Sakharov's avatar
Fedor Sakharov committed
250
251
252
253
254
255
256
		}
	}
}

/// A running instance of some [`Subsystem`].
///
/// [`Subsystem`]: trait.Subsystem.html
257
struct SubsystemInstance<M> {
Fedor Sakharov's avatar
Fedor Sakharov committed
258
259
260
261
262
263
264
265
266
267
	tx: mpsc::Sender<FromOverseer<M>>,
}

/// A context type that is given to the [`Subsystem`] upon spawning.
/// It can be used by [`Subsystem`] to communicate with other [`Subsystem`]s
/// or to spawn it's [`SubsystemJob`]s.
///
/// [`Overseer`]: struct.Overseer.html
/// [`Subsystem`]: trait.Subsystem.html
/// [`SubsystemJob`]: trait.SubsystemJob.html
268
269
#[derive(Debug)]
pub struct OverseerSubsystemContext<M>{
Fedor Sakharov's avatar
Fedor Sakharov committed
270
271
272
273
	rx: mpsc::Receiver<FromOverseer<M>>,
	tx: mpsc::Sender<ToOverseer>,
}

274
275
276
277
278
#[async_trait::async_trait]
impl<M: Send + 'static> SubsystemContext for OverseerSubsystemContext<M> {
	type Message = M;

	async fn try_recv(&mut self) -> Result<Option<FromOverseer<M>>, ()> {
Fedor Sakharov's avatar
Fedor Sakharov committed
279
280
281
282
283
284
285
		match poll!(self.rx.next()) {
			Poll::Ready(Some(msg)) => Ok(Some(msg)),
			Poll::Ready(None) => Err(()),
			Poll::Pending => Ok(None),
		}
	}

286
	async fn recv(&mut self) -> SubsystemResult<FromOverseer<M>> {
Fedor Sakharov's avatar
Fedor Sakharov committed
287
288
289
		self.rx.next().await.ok_or(SubsystemError)
	}

290
291
292
	async fn spawn(&mut self, name: &'static str, s: Pin<Box<dyn Future<Output = ()> + Send>>)
		-> SubsystemResult<()>
	{
Fedor Sakharov's avatar
Fedor Sakharov committed
293
		self.tx.send(ToOverseer::SpawnJob {
294
			name,
Fedor Sakharov's avatar
Fedor Sakharov committed
295
296
297
			s,
		}).await?;

298
		Ok(())
Fedor Sakharov's avatar
Fedor Sakharov committed
299
300
	}

301
302
303
304
305
306
307
308
309
310
311
	async fn spawn_blocking(&mut self, name: &'static str, s: Pin<Box<dyn Future<Output = ()> + Send>>)
		-> SubsystemResult<()>
	{
		self.tx.send(ToOverseer::SpawnBlockingJob {
			name,
			s,
		}).await?;

		Ok(())
	}

312
	async fn send_message(&mut self, msg: AllMessages) -> SubsystemResult<()> {
Fedor Sakharov's avatar
Fedor Sakharov committed
313
314
315
316
317
		self.tx.send(ToOverseer::SubsystemMessage(msg)).await?;

		Ok(())
	}

318
319
320
321
322
323
324
	async fn send_messages<T>(&mut self, msgs: T) -> SubsystemResult<()>
		where T: IntoIterator<Item = AllMessages> + Send, T::IntoIter: Send
	{
		let mut msgs = stream::iter(msgs.into_iter().map(ToOverseer::SubsystemMessage).map(Ok));
		self.tx.send_all(&mut msgs).await?;

		Ok(())
Fedor Sakharov's avatar
Fedor Sakharov committed
325
326
327
	}
}

328
329
330
/// A subsystem compatible with the overseer - one which can be run in the context of the
/// overseer.
pub type CompatibleSubsystem<M> = Box<dyn Subsystem<OverseerSubsystemContext<M>> + Send>;
Fedor Sakharov's avatar
Fedor Sakharov committed
331
332
333
334
335
336
337
338
339

/// A subsystem that we oversee.
///
/// Ties together the [`Subsystem`] itself and it's running instance
/// (which may be missing if the [`Subsystem`] is not running at the moment
/// for whatever reason).
///
/// [`Subsystem`]: trait.Subsystem.html
#[allow(dead_code)]
340
struct OverseenSubsystem<M> {
Fedor Sakharov's avatar
Fedor Sakharov committed
341
342
343
344
	instance: Option<SubsystemInstance<M>>,
}

/// The `Overseer` itself.
345
pub struct Overseer<S: SpawnNamed> {
346
347
	/// A candidate validation subsystem.
	candidate_validation_subsystem: OverseenSubsystem<CandidateValidationMessage>,
Fedor Sakharov's avatar
Fedor Sakharov committed
348

349
	/// A candidate backing subsystem.
350
	candidate_backing_subsystem: OverseenSubsystem<CandidateBackingMessage>,
Fedor Sakharov's avatar
Fedor Sakharov committed
351

352
353
354
355
356
357
358
359
360
	/// A candidate selection subsystem.
	candidate_selection_subsystem: OverseenSubsystem<CandidateSelectionMessage>,

	/// A statement distribution subsystem.
	statement_distribution_subsystem: OverseenSubsystem<StatementDistributionMessage>,

	/// An availability distribution subsystem.
	availability_distribution_subsystem: OverseenSubsystem<AvailabilityDistributionMessage>,

361
362
363
	/// A bitfield signing subsystem.
	bitfield_signing_subsystem: OverseenSubsystem<BitfieldSigningMessage>,

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
	/// A bitfield distribution subsystem.
	bitfield_distribution_subsystem: OverseenSubsystem<BitfieldDistributionMessage>,

	/// A provisioner subsystem.
	provisioner_subsystem: OverseenSubsystem<ProvisionerMessage>,

	/// A PoV distribution subsystem.
	pov_distribution_subsystem: OverseenSubsystem<PoVDistributionMessage>,

	/// A runtime API subsystem.
	runtime_api_subsystem: OverseenSubsystem<RuntimeApiMessage>,

	/// An availability store subsystem.
	availability_store_subsystem: OverseenSubsystem<AvailabilityStoreMessage>,

	/// A network bridge subsystem.
	network_bridge_subsystem: OverseenSubsystem<NetworkBridgeMessage>,

382
	/// A Chain API subsystem.
383
	chain_api_subsystem: OverseenSubsystem<ChainApiMessage>,
384

385
386
387
388
389
390
	/// A Collation Generation subsystem.
	collation_generation_subsystem: OverseenSubsystem<CollationGenerationMessage>,

	/// A Collator Protocol subsystem.
	collator_protocol_subsystem: OverseenSubsystem<CollatorProtocolMessage>,

Fedor Sakharov's avatar
Fedor Sakharov committed
391
392
393
394
	/// Spawner to spawn tasks to.
	s: S,

	/// Here we keep handles to spawned subsystems to be notified when they terminate.
395
	running_subsystems: FuturesUnordered<BoxFuture<'static, ()>>,
Fedor Sakharov's avatar
Fedor Sakharov committed
396
397
398
399
400
401

	/// Gather running subsystms' outbound streams into one.
	running_subsystems_rx: StreamUnordered<mpsc::Receiver<ToOverseer>>,

	/// Events that are sent to the overseer from the outside world
	events_rx: mpsc::Receiver<Event>,
402
403
404
405
406
407
408
409

	/// A set of leaves that `Overseer` starts working with.
	///
	/// Drained at the beginning of `run` and never used again.
	leaves: Vec<(Hash, BlockNumber)>,

	/// The set of the "active leaves".
	active_leaves: HashSet<(Hash, BlockNumber)>,
Fedor Sakharov's avatar
Fedor Sakharov committed
410
411
}

412
413
414
415
416
417
418
419
420
421
422
/// This struct is passed as an argument to create a new instance of an [`Overseer`].
///
/// As any entity that satisfies the interface may act as a [`Subsystem`] this allows
/// mocking in the test code:
///
/// Each [`Subsystem`] is supposed to implement some interface that is generic over
/// message type that is specific to this [`Subsystem`]. At the moment not all
/// subsystems are implemented and the rest can be mocked with the [`DummySubsystem`].
///
/// [`Subsystem`]: trait.Subsystem.html
/// [`DummySubsystem`]: struct.DummySubsystem.html
423
pub struct AllSubsystems<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP> {
424
425
426
427
428
429
430
431
432
433
	/// A candidate validation subsystem.
	pub candidate_validation: CV,
	/// A candidate backing subsystem.
	pub candidate_backing: CB,
	/// A candidate selection subsystem.
	pub candidate_selection: CS,
	/// A statement distribution subsystem.
	pub statement_distribution: SD,
	/// An availability distribution subsystem.
	pub availability_distribution: AD,
434
435
	/// A bitfield signing subsystem.
	pub bitfield_signing: BS,
436
437
438
439
440
441
442
443
444
445
446
447
	/// A bitfield distribution subsystem.
	pub bitfield_distribution: BD,
	/// A provisioner subsystem.
	pub provisioner: P,
	/// A PoV distribution subsystem.
	pub pov_distribution: PoVD,
	/// A runtime API subsystem.
	pub runtime_api: RA,
	/// An availability store subsystem.
	pub availability_store: AS,
	/// A network bridge subsystem.
	pub network_bridge: NB,
448
449
	/// A Chain API subsystem.
	pub chain_api: CA,
450
451
452
453
	/// A Collation Generation subsystem.
	pub collation_generation: CG,
	/// A Collator Protocol subsystem.
	pub collator_protocol: CP,
454
455
}

Fedor Sakharov's avatar
Fedor Sakharov committed
456
457
impl<S> Overseer<S>
where
458
	S: SpawnNamed,
Fedor Sakharov's avatar
Fedor Sakharov committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
{
	/// Create a new intance of the `Overseer` with a fixed set of [`Subsystem`]s.
	///
	/// ```text
	///                  +------------------------------------+
	///                  |            Overseer                |
	///                  +------------------------------------+
	///                    /            |             |      \
	///      ................. subsystems...................................
	///      . +-----------+    +-----------+   +----------+   +---------+ .
	///      . |           |    |           |   |          |   |         | .
	///      . +-----------+    +-----------+   +----------+   +---------+ .
	///      ...............................................................
	///                              |
	///                        probably `spawn`
	///                            a `job`
	///                              |
	///                              V
	///                         +-----------+
	///                         |           |
	///                         +-----------+
	///
	/// ```
	///
	/// [`Subsystem`]: trait.Subsystem.html
	///
	/// # Example
	///
	/// The [`Subsystems`] may be any type as long as they implement an expected interface.
488
489
	/// Here, we create a mock validation subsystem and a few dummy ones and start the `Overseer` with them.
	/// For the sake of simplicity the termination of the example is done with a timeout.
Fedor Sakharov's avatar
Fedor Sakharov committed
490
491
492
493
	/// ```
	/// # use std::time::Duration;
	/// # use futures::{executor, pin_mut, select, FutureExt};
	/// # use futures_timer::Delay;
494
	/// # use polkadot_overseer::{Overseer, AllSubsystems};
495
	/// # use polkadot_subsystem::{
496
497
	/// #     Subsystem, DummySubsystem, SpawnedSubsystem, SubsystemContext,
	/// #     messages::CandidateValidationMessage,
Fedor Sakharov's avatar
Fedor Sakharov committed
498
499
500
	/// # };
	///
	/// struct ValidationSubsystem;
501
502
503
504
	///
	/// impl<C> Subsystem<C> for ValidationSubsystem
	/// 	where C: SubsystemContext<Message=CandidateValidationMessage>
	/// {
Fedor Sakharov's avatar
Fedor Sakharov committed
505
	///     fn start(
506
	///         self,
507
	///         mut ctx: C,
Fedor Sakharov's avatar
Fedor Sakharov committed
508
	///     ) -> SpawnedSubsystem {
509
510
511
512
513
514
515
516
	///         SpawnedSubsystem {
	///             name: "validation-subsystem",
	///             future: Box::pin(async move {
	///                 loop {
	///                     Delay::new(Duration::from_secs(1)).await;
	///                 }
	///             }),
	///         }
Fedor Sakharov's avatar
Fedor Sakharov committed
517
518
519
520
	///     }
	/// }
	///
	/// # fn main() { executor::block_on(async move {
Bastian Köcher's avatar
Bastian Köcher committed
521
	/// let spawner = sp_core::testing::TaskExecutor::new();
522
523
524
525
526
527
	/// let all_subsystems = AllSubsystems {
	///     candidate_validation: ValidationSubsystem,
	///     candidate_backing: DummySubsystem,
	///     candidate_selection: DummySubsystem,
	///     statement_distribution: DummySubsystem,
	///     availability_distribution: DummySubsystem,
528
	///     bitfield_signing: DummySubsystem,
529
530
531
532
533
534
	///     bitfield_distribution: DummySubsystem,
	///     provisioner: DummySubsystem,
	///     pov_distribution: DummySubsystem,
	///     runtime_api: DummySubsystem,
	///     availability_store: DummySubsystem,
	///     network_bridge: DummySubsystem,
535
	///     chain_api: DummySubsystem,
536
537
	///     collation_generation: DummySubsystem,
	///     collator_protocol: DummySubsystem,
538
	/// };
Fedor Sakharov's avatar
Fedor Sakharov committed
539
	/// let (overseer, _handler) = Overseer::new(
540
	///     vec![],
541
	///     all_subsystems,
Fedor Sakharov's avatar
Fedor Sakharov committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
	///     spawner,
	/// ).unwrap();
	///
	/// let timer = Delay::new(Duration::from_millis(50)).fuse();
	///
	/// let overseer_fut = overseer.run().fuse();
	/// pin_mut!(timer);
	/// pin_mut!(overseer_fut);
	///
	/// select! {
	///     _ = overseer_fut => (),
	///     _ = timer => (),
	/// }
	/// #
	/// # }); }
	/// ```
558
	pub fn new<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP>(
559
		leaves: impl IntoIterator<Item = BlockInfo>,
560
		all_subsystems: AllSubsystems<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP>,
Fedor Sakharov's avatar
Fedor Sakharov committed
561
		mut s: S,
562
563
564
565
566
567
568
	) -> SubsystemResult<(Self, OverseerHandler)>
	where
		CV: Subsystem<OverseerSubsystemContext<CandidateValidationMessage>> + Send,
		CB: Subsystem<OverseerSubsystemContext<CandidateBackingMessage>> + Send,
		CS: Subsystem<OverseerSubsystemContext<CandidateSelectionMessage>> + Send,
		SD: Subsystem<OverseerSubsystemContext<StatementDistributionMessage>> + Send,
		AD: Subsystem<OverseerSubsystemContext<AvailabilityDistributionMessage>> + Send,
569
		BS: Subsystem<OverseerSubsystemContext<BitfieldSigningMessage>> + Send,
570
571
572
573
574
575
		BD: Subsystem<OverseerSubsystemContext<BitfieldDistributionMessage>> + Send,
		P: Subsystem<OverseerSubsystemContext<ProvisionerMessage>> + Send,
		PoVD: Subsystem<OverseerSubsystemContext<PoVDistributionMessage>> + Send,
		RA: Subsystem<OverseerSubsystemContext<RuntimeApiMessage>> + Send,
		AS: Subsystem<OverseerSubsystemContext<AvailabilityStoreMessage>> + Send,
		NB: Subsystem<OverseerSubsystemContext<NetworkBridgeMessage>> + Send,
576
		CA: Subsystem<OverseerSubsystemContext<ChainApiMessage>> + Send,
577
578
		CG: Subsystem<OverseerSubsystemContext<CollationGenerationMessage>> + Send,
		CP: Subsystem<OverseerSubsystemContext<CollatorProtocolMessage>> + Send,
579
	{
Fedor Sakharov's avatar
Fedor Sakharov committed
580
581
582
583
584
585
586
587
588
		let (events_tx, events_rx) = mpsc::channel(CHANNEL_CAPACITY);

		let handler = OverseerHandler {
			events_tx: events_tx.clone(),
		};

		let mut running_subsystems_rx = StreamUnordered::new();
		let mut running_subsystems = FuturesUnordered::new();

589
		let candidate_validation_subsystem = spawn(
Fedor Sakharov's avatar
Fedor Sakharov committed
590
591
592
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
593
			all_subsystems.candidate_validation,
Fedor Sakharov's avatar
Fedor Sakharov committed
594
595
596
597
598
599
		)?;

		let candidate_backing_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
			all_subsystems.candidate_backing,
		)?;

		let candidate_selection_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.candidate_selection,
		)?;

		let statement_distribution_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.statement_distribution,
		)?;

		let availability_distribution_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.availability_distribution,
		)?;

624
625
626
627
628
629
630
		let bitfield_signing_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.bitfield_signing,
		)?;

631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
		let bitfield_distribution_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.bitfield_distribution,
		)?;

		let provisioner_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.provisioner,
		)?;

		let pov_distribution_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.pov_distribution,
		)?;

		let runtime_api_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.runtime_api,
		)?;

		let availability_store_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.availability_store,
		)?;

		let network_bridge_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.network_bridge,
Fedor Sakharov's avatar
Fedor Sakharov committed
671
672
		)?;

673
674
675
676
677
678
679
		let chain_api_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.chain_api,
		)?;

680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
		let collation_generation_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.collation_generation,
		)?;


		let collator_protocol_subsystem = spawn(
			&mut s,
			&mut running_subsystems,
			&mut running_subsystems_rx,
			all_subsystems.collator_protocol,
		)?;

695
696
697
698
699
700
701
		let active_leaves = HashSet::new();

		let leaves = leaves
			.into_iter()
			.map(|BlockInfo { hash, parent_hash: _, number }| (hash, number))
			.collect();

Fedor Sakharov's avatar
Fedor Sakharov committed
702
		let this = Self {
703
			candidate_validation_subsystem,
Fedor Sakharov's avatar
Fedor Sakharov committed
704
			candidate_backing_subsystem,
705
706
707
			candidate_selection_subsystem,
			statement_distribution_subsystem,
			availability_distribution_subsystem,
708
			bitfield_signing_subsystem,
709
710
711
712
713
714
			bitfield_distribution_subsystem,
			provisioner_subsystem,
			pov_distribution_subsystem,
			runtime_api_subsystem,
			availability_store_subsystem,
			network_bridge_subsystem,
715
			chain_api_subsystem,
716
717
			collation_generation_subsystem,
			collator_protocol_subsystem,
Fedor Sakharov's avatar
Fedor Sakharov committed
718
719
720
721
			s,
			running_subsystems,
			running_subsystems_rx,
			events_rx,
722
723
			leaves,
			active_leaves,
Fedor Sakharov's avatar
Fedor Sakharov committed
724
725
726
727
728
729
730
		};

		Ok((this, handler))
	}

	// Stop the overseer.
	async fn stop(mut self) {
731
		if let Some(ref mut s) = self.candidate_validation_subsystem.instance {
Fedor Sakharov's avatar
Fedor Sakharov committed
732
733
734
735
736
737
738
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.candidate_backing_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

739
740
741
742
743
744
745
746
747
748
749
750
		if let Some(ref mut s) = self.candidate_selection_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.statement_distribution_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.availability_distribution_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

751
752
753
754
		if let Some(ref mut s) = self.bitfield_signing_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
		if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.provisioner_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.pov_distribution_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.runtime_api_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

771
		if let Some(ref mut s) = self.availability_store_subsystem.instance {
772
773
774
775
776
777
778
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.network_bridge_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

779
780
781
782
		if let Some(ref mut s) = self.chain_api_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

783
784
785
786
787
788
789
790
		if let Some(ref mut s) = self.collator_protocol_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

		if let Some(ref mut s) = self.collation_generation_subsystem.instance {
			let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await;
		}

Fedor Sakharov's avatar
Fedor Sakharov committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
		let mut stop_delay = Delay::new(Duration::from_secs(STOP_DELAY)).fuse();

		loop {
			select! {
				_ = self.running_subsystems.next() => {
					if self.running_subsystems.is_empty() {
						break;
					}
				},
				_ = stop_delay => break,
				complete => break,
			}
		}
	}

	/// Run the `Overseer`.
	pub async fn run(mut self) -> SubsystemResult<()> {
808
		let leaves = std::mem::take(&mut self.leaves);
809
		let mut update = ActiveLeavesUpdate::default();
810
811

		for leaf in leaves.into_iter() {
812
			update.activated.push(leaf.0);
813
814
815
			self.active_leaves.insert(leaf);
		}

816
817
		self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?;

Fedor Sakharov's avatar
Fedor Sakharov committed
818
819
820
821
822
823
824
825
826
827
		loop {
			while let Poll::Ready(Some(msg)) = poll!(&mut self.events_rx.next()) {
				match msg {
					Event::MsgToSubsystem(msg) => {
						self.route_message(msg).await;
					}
					Event::Stop => {
						self.stop().await;
						return Ok(());
					}
828
829
830
831
832
833
					Event::BlockImported(block) => {
						self.block_imported(block).await?;
					}
					Event::BlockFinalized(block) => {
						self.block_finalized(block).await?;
					}
Fedor Sakharov's avatar
Fedor Sakharov committed
834
835
836
837
838
839
840
841
				}
			}

			while let Poll::Ready(Some((StreamYield::Item(msg), _))) = poll!(
				&mut self.running_subsystems_rx.next()
			) {
				match msg {
					ToOverseer::SubsystemMessage(msg) => self.route_message(msg).await,
842
843
					ToOverseer::SpawnJob { name, s } => {
						self.spawn_job(name, s);
Fedor Sakharov's avatar
Fedor Sakharov committed
844
					}
845
846
847
					ToOverseer::SpawnBlockingJob { name, s } => {
						self.spawn_blocking_job(name, s);
					}
Fedor Sakharov's avatar
Fedor Sakharov committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
				}
			}

			// Some subsystem exited? It's time to panic.
			if let Poll::Ready(Some(finished)) = poll!(self.running_subsystems.next()) {
				log::error!("Subsystem finished unexpectedly {:?}", finished);
				self.stop().await;
				return Err(SubsystemError);
			}

			// Looks like nothing is left to be polled, let's take a break.
			pending!();
		}
	}

863
	async fn block_imported(&mut self, block: BlockInfo) -> SubsystemResult<()> {
864
865
		let mut update = ActiveLeavesUpdate::default();

866
		if let Some(parent) = block.number.checked_sub(1).and_then(|number| self.active_leaves.take(&(block.parent_hash, number))) {
867
			update.deactivated.push(parent.0);
868
869
870
		}

		if !self.active_leaves.contains(&(block.hash, block.number)) {
871
			update.activated.push(block.hash);
872
873
874
			self.active_leaves.insert((block.hash, block.number));
		}

875
876
		self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?;

877
878
879
880
		Ok(())
	}

	async fn block_finalized(&mut self, block: BlockInfo) -> SubsystemResult<()> {
881
		let mut update = ActiveLeavesUpdate::default();
882
883
884

		self.active_leaves.retain(|(h, n)| {
			if *n <= block.number {
885
				update.deactivated.push(*h);
886
887
888
889
890
891
				false
			} else {
				true
			}
		});

892
		self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?;
893

894
895
		self.broadcast_signal(OverseerSignal::BlockFinalized(block.hash)).await?;

896
897
898
899
		Ok(())
	}

	async fn broadcast_signal(&mut self, signal: OverseerSignal) -> SubsystemResult<()> {
900
		if let Some(ref mut s) = self.candidate_validation_subsystem.instance {
901
902
903
904
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.candidate_backing_subsystem.instance {
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.candidate_selection_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.statement_distribution_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.availability_distribution_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

924
925
926
927
		if let Some(ref mut s) = self.bitfield_signing_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
		if let Some(ref mut s) = self.provisioner_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.pov_distribution_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.runtime_api_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.availability_store_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.network_bridge_subsystem.instance {
945
946
947
948
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.chain_api_subsystem.instance {
949
950
951
952
953
954
955
956
957
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.collator_protocol_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
		}

		if let Some(ref mut s) = self.collation_generation_subsystem.instance {
			s.tx.send(FromOverseer::Signal(signal.clone())).await?;
958
959
960
961
962
		}

		Ok(())
	}

Fedor Sakharov's avatar
Fedor Sakharov committed
963
964
	async fn route_message(&mut self, msg: AllMessages) {
		match msg {
965
			AllMessages::CandidateValidation(msg) => {
966
				if let Some(ref mut s) = self.candidate_validation_subsystem.instance {
Fedor Sakharov's avatar
Fedor Sakharov committed
967
968
969
970
971
972
973
974
					let _= s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
			AllMessages::CandidateBacking(msg) => {
				if let Some(ref mut s) = self.candidate_backing_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
			AllMessages::CandidateSelection(msg) => {
				if let Some(ref mut s) = self.candidate_selection_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
			AllMessages::StatementDistribution(msg) => {
				if let Some(ref mut s) = self.statement_distribution_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
			AllMessages::AvailabilityDistribution(msg) => {
				if let Some(ref mut s) = self.availability_distribution_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
			AllMessages::BitfieldDistribution(msg) => {
				if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication { msg }).await;
				}
			}
995
996
997
998
999
			AllMessages::BitfieldSigning(msg) => {
				if let Some(ref mut s) = self.bitfield_signing_subsystem.instance {
					let _ = s.tx.send(FromOverseer::Communication{ msg }).await;
				}
			}
1000
			AllMessages::Provisioner(msg) => {
For faster browsing, not all history is shown. View entire blame