From 2dd4f9a4daacd236830ad5f0b26dd058ea600f94 Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Thu, 18 Jun 2020 10:36:10 +0200 Subject: [PATCH 1/7] Initial commit Forked at: d735e4d0b5378c227f81a5127a1d4544de112fd8 No parent branch. From fb314206ec5768c36ba3d0ee9645aba93a689b88 Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Thu, 18 Jun 2020 10:37:43 +0200 Subject: [PATCH 2/7] Make sc_service::Configuration derive Debug --- client/chain-spec/src/lib.rs | 6 +++++ client/cli/src/config.rs | 2 +- client/db/src/lib.rs | 2 +- client/service/src/config.rs | 43 +++++++++++++++++++++++++++--- client/service/src/task_manager.rs | 13 ++++----- client/service/test/src/lib.rs | 2 +- primitives/database/src/lib.rs | 6 +++++ utils/browser/src/lib.rs | 5 ++-- 8 files changed, 61 insertions(+), 18 deletions(-) diff --git a/client/chain-spec/src/lib.rs b/client/chain-spec/src/lib.rs index 6fb26942612d3..66bce2b1363c2 100644 --- a/client/chain-spec/src/lib.rs +++ b/client/chain-spec/src/lib.rs @@ -158,3 +158,9 @@ pub trait ChainSpec: BuildStorage + Send { /// This will be used as storage at genesis. fn set_storage(&mut self, storage: Storage); } + +impl std::fmt::Debug for dyn ChainSpec { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "ChainSpec(name = {:?}, id = {:?})", self.name(), self.id()) + } +} diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index d121546c193a0..a1ef65b10b939 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -432,7 +432,7 @@ pub trait CliConfiguration: Sized { Ok(Configuration { impl_name: C::impl_name(), impl_version: C::impl_version(), - task_executor, + task_executor: task_executor.into(), transaction_pool: self.transaction_pool()?, network: self.network_config( &chain_spec, diff --git a/client/db/src/lib.rs b/client/db/src/lib.rs index f75693ec9f00e..55c726ba06eed 100644 --- a/client/db/src/lib.rs +++ b/client/db/src/lib.rs @@ -271,7 +271,7 @@ pub struct DatabaseSettings { } /// Where to find the database.. -#[derive(Clone)] +#[derive(Debug, Clone)] pub enum DatabaseSettingsSrc { /// Load a RocksDB database from a given path. Recommended for most uses. RocksDb { diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 2d4dc9dc2e90a..db17980042586 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -34,6 +34,7 @@ use prometheus_endpoint::Registry; use tempfile::TempDir; /// Service configuration. +#[derive(Debug)] pub struct Configuration { /// Implementation name pub impl_name: &'static str, @@ -42,7 +43,7 @@ pub struct Configuration { /// Node role. pub role: Role, /// How to spawn background tasks. Mandatory, otherwise creating a `Service` will error. - pub task_executor: Arc + Send>>, TaskType) + Send + Sync>, + pub task_executor: TaskExecutor, /// Extrinsic pool configuration. pub transaction_pool: TransactionPoolOptions, /// Network configuration. @@ -118,7 +119,7 @@ pub enum TaskType { } /// Configuration of the client keystore. -#[derive(Clone)] +#[derive(Debug, Clone)] pub enum KeystoreConfig { /// Keystore at a path on-disk. Recommended for native nodes. Path { @@ -141,7 +142,7 @@ impl KeystoreConfig { } } /// Configuration of the database of the client. -#[derive(Clone, Default)] +#[derive(Debug, Clone, Default)] pub struct OffchainWorkerConfig { /// If this is allowed. pub enabled: bool, @@ -150,7 +151,7 @@ pub struct OffchainWorkerConfig { } /// Configuration of the Prometheus endpoint. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct PrometheusConfig { /// Port to use. pub port: SocketAddr, @@ -197,6 +198,7 @@ impl Default for RpcMethods { } /// The base path that is used for everything that needs to be write on disk to run a node. +#[derive(Debug)] pub enum BasePath { /// A temporary directory is used as base path and will be deleted when dropped. #[cfg(not(target_os = "unknown"))] @@ -251,3 +253,36 @@ impl std::convert::From for BasePath { BasePath::new(path) } } + +/// Callable object that execute tasks. +#[derive(Clone)] +pub struct TaskExecutor(Arc + Send>>, TaskType) + Send + Sync>); + +impl std::fmt::Debug for TaskExecutor { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "TaskExecutor") + } +} + +impl std::convert::From + Send>>, TaskType) + Send + Sync>> +for TaskExecutor { + fn from(x: Arc + Send>>, TaskType) + Send + Sync>) + -> Self { + Self(x) + } +} + +impl std::ops::Deref for TaskExecutor { + type Target = Arc + Send>>, TaskType) + Send + Sync>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl TaskExecutor { + /// Create a `TaskExecutor` from a function + pub fn from_fn(f: impl Fn(Pin + Send>>, TaskType) + Send + Sync + 'static) -> Self { + Self(Arc::new(f)) + } +} diff --git a/client/service/src/task_manager.rs b/client/service/src/task_manager.rs index 553ca9c326d8b..3ea1689ac2e19 100644 --- a/client/service/src/task_manager.rs +++ b/client/service/src/task_manager.rs @@ -13,7 +13,7 @@ //! Substrate service tasks management module. -use std::{panic, pin::Pin, result::Result, sync::Arc}; +use std::{panic, result::Result}; use exit_future::Signal; use log::debug; use futures::{ @@ -28,18 +28,15 @@ use prometheus_endpoint::{ CounterVec, HistogramOpts, HistogramVec, Opts, Registry, U64 }; use sc_client_api::CloneableSpawn; -use crate::config::TaskType; +use crate::config::{TaskExecutor, TaskType}; mod prometheus_future; -/// Type alias for service task executor (usually runtime). -pub type ServiceTaskExecutor = Arc + Send>>, TaskType) + Send + Sync>; - /// An handle for spawning tasks in the service. #[derive(Clone)] pub struct SpawnTaskHandle { on_exit: exit_future::Exit, - executor: ServiceTaskExecutor, + executor: TaskExecutor, metrics: Option, } @@ -153,7 +150,7 @@ pub struct TaskManager { /// A signal that makes the exit future above resolve, fired on service drop. signal: Option, /// How to spawn background tasks. - executor: ServiceTaskExecutor, + executor: TaskExecutor, /// Prometheus metric where to report the polling times. metrics: Option, } @@ -162,7 +159,7 @@ impl TaskManager { /// If a Prometheus registry is passed, it will be used to report statistics about the /// service tasks. pub(super) fn new( - executor: ServiceTaskExecutor, + executor: TaskExecutor, prometheus_registry: Option<&Registry> ) -> Result { let (signal, on_exit) = exit_future::signal(); diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 613b0d71ce933..94fbea60b2663 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -176,7 +176,7 @@ fn node_config: Send + Sync { } } +impl std::fmt::Debug for dyn Database { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "Database") + } +} + /// Call `f` with the value previously stored against `key` and return the result, or `None` if /// `key` is not currently in the database. /// diff --git a/utils/browser/src/lib.rs b/utils/browser/src/lib.rs index 04af2ceb58136..8776033acacd9 100644 --- a/utils/browser/src/lib.rs +++ b/utils/browser/src/lib.rs @@ -17,11 +17,10 @@ use futures01::sync::mpsc as mpsc01; use log::{debug, info}; -use std::sync::Arc; use sc_network::config::TransportConfig; use sc_service::{ AbstractService, RpcSession, Role, Configuration, - config::{DatabaseConfig, KeystoreConfig, NetworkConfiguration}, + config::{DatabaseConfig, KeystoreConfig, NetworkConfiguration, TaskExecutor}, GenericChainSpec, RuntimeGenesis }; use wasm_bindgen::prelude::*; @@ -64,7 +63,7 @@ where network, telemetry_endpoints: chain_spec.telemetry_endpoints().clone(), chain_spec: Box::new(chain_spec), - task_executor: Arc::new(move |fut, _| wasm_bindgen_futures::spawn_local(fut)), + task_executor: TaskExecutor::from_fn(|fut, _| wasm_bindgen_futures::spawn_local(fut)), telemetry_external_transport: Some(transport), role: Role::Light, database: { From 563da0ad79e4e42634550a1266781a049170a947 Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Thu, 18 Jun 2020 11:52:13 +0200 Subject: [PATCH 3/7] Replace task_executor fn's input by proper TaskExecutor type (cleaner) --- client/cli/src/config.rs | 11 +++----- client/cli/src/lib.rs | 7 ++--- client/cli/src/runner.rs | 8 +++--- client/service/src/config.rs | 17 +++++++----- client/service/src/lib.rs | 4 ++- client/service/test/src/lib.rs | 48 +++++++++++++++++++++------------- 6 files changed, 55 insertions(+), 40 deletions(-) diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index a1ef65b10b939..b86e24c1ba2f7 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -28,15 +28,12 @@ use names::{Generator, Name}; use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::config::{ BasePath, Configuration, DatabaseConfig, ExtTransport, KeystoreConfig, NetworkConfiguration, - NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode, Role, RpcMethods, TaskType, - TelemetryEndpoints, TransactionPoolOptions, WasmExecutionMethod, + NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode, Role, RpcMethods, + TaskExecutor, TelemetryEndpoints, TransactionPoolOptions, WasmExecutionMethod, }; use sc_service::{ChainSpec, TracingReceiver}; -use std::future::Future; use std::net::SocketAddr; use std::path::PathBuf; -use std::pin::Pin; -use std::sync::Arc; /// The maximum number of characters for a node name. pub(crate) const NODE_NAME_MAX_LENGTH: usize = 32; @@ -402,7 +399,7 @@ pub trait CliConfiguration: Sized { fn create_configuration( &self, cli: &C, - task_executor: Arc + Send>>, TaskType) + Send + Sync>, + task_executor: TaskExecutor, ) -> Result { let is_dev = self.is_dev()?; let chain_id = self.chain_id(is_dev)?; @@ -432,7 +429,7 @@ pub trait CliConfiguration: Sized { Ok(Configuration { impl_name: C::impl_name(), impl_version: C::impl_version(), - task_executor: task_executor.into(), + task_executor, transaction_pool: self.transaction_pool()?, network: self.network_config( &chain_spec, diff --git a/client/cli/src/lib.rs b/client/cli/src/lib.rs index 1acd5ee60474a..9623b08bfbb7f 100644 --- a/client/cli/src/lib.rs +++ b/client/cli/src/lib.rs @@ -37,11 +37,8 @@ use log::info; pub use params::*; use regex::Regex; pub use runner::*; -use sc_service::{ChainSpec, Configuration, TaskType}; -use std::future::Future; +use sc_service::{ChainSpec, Configuration, TaskExecutor}; use std::io::Write; -use std::pin::Pin; -use std::sync::Arc; pub use structopt; use structopt::{ clap::{self, AppSettings}, @@ -199,7 +196,7 @@ pub trait SubstrateCli: Sized { fn create_configuration( &self, command: &T, - task_executor: Arc + Send>>, TaskType) + Send + Sync>, + task_executor: TaskExecutor, ) -> error::Result { command.create_configuration(self, task_executor) } diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index b068af0166817..7aa5a99a7bb42 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -25,11 +25,13 @@ use futures::pin_mut; use futures::select; use futures::{future, future::FutureExt, Future}; use log::info; -use sc_service::{AbstractService, Configuration, Role, ServiceBuilderCommand, TaskType}; +use sc_service::{ + AbstractService, Configuration, Role, ServiceBuilderCommand, TaskType, config::TaskExecutor, +}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_utils::metrics::{TOKIO_THREADS_ALIVE, TOKIO_THREADS_TOTAL}; use sp_version::RuntimeVersion; -use std::{fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc}; +use std::{fmt::Debug, marker::PhantomData, str::FromStr}; #[cfg(target_family = "unix")] async fn main(func: F) -> std::result::Result<(), Box> @@ -119,7 +121,7 @@ impl Runner { let tokio_runtime = build_runtime()?; let runtime_handle = tokio_runtime.handle().clone(); - let task_executor = Arc::new( + let task_executor = TaskExecutor::from_fn( move |fut, task_type| { match task_type { TaskType::Async => { runtime_handle.spawn(fut); } diff --git a/client/service/src/config.rs b/client/service/src/config.rs index db17980042586..0eb62c55a3e74 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -254,9 +254,11 @@ impl std::convert::From for BasePath { } } +type TaskExecutorInner = Arc + Send>>, TaskType) + Send + Sync>; + /// Callable object that execute tasks. #[derive(Clone)] -pub struct TaskExecutor(Arc + Send>>, TaskType) + Send + Sync>); +pub struct TaskExecutor(TaskExecutorInner); impl std::fmt::Debug for TaskExecutor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { @@ -264,16 +266,17 @@ impl std::fmt::Debug for TaskExecutor { } } -impl std::convert::From + Send>>, TaskType) + Send + Sync>> -for TaskExecutor { - fn from(x: Arc + Send>>, TaskType) + Send + Sync>) +/* +impl std::convert::From for TaskExecutor { + fn from(x: TaskExecutorInner) -> Self { Self(x) } } +*/ impl std::ops::Deref for TaskExecutor { - type Target = Arc + Send>>, TaskType) + Send + Sync>; + type Target = TaskExecutorInner; fn deref(&self) -> &Self::Target { &self.0 @@ -282,7 +285,9 @@ impl std::ops::Deref for TaskExecutor { impl TaskExecutor { /// Create a `TaskExecutor` from a function - pub fn from_fn(f: impl Fn(Pin + Send>>, TaskType) + Send + Sync + 'static) -> Self { + pub fn from_fn( + f: impl Fn(Pin + Send>>, TaskType) + Send + Sync + 'static, + ) -> Self { Self(Arc::new(f)) } } diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index fc0567e268260..c7419838c8930 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -66,7 +66,9 @@ pub use self::builder::{ ServiceBuilder, ServiceBuilderCommand, TFullClient, TLightClient, TFullBackend, TLightBackend, TFullCallExecutor, TLightCallExecutor, RpcExtensionBuilder, }; -pub use config::{BasePath, Configuration, DatabaseConfig, PruningMode, Role, RpcMethods, TaskType}; +pub use config::{ + BasePath, Configuration, DatabaseConfig, PruningMode, Role, RpcMethods, TaskExecutor, TaskType, +}; pub use sc_chain_spec::{ ChainSpec, GenericChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension, NoExtension, ChainType, diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 94fbea60b2663..0f1dd0f2d64de 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -38,7 +38,7 @@ use sc_service::{ RuntimeGenesis, Role, Error, - TaskType, + TaskExecutor, }; use sp_blockchain::HeaderBackend; use sc_network::{multiaddr, Multiaddr}; @@ -142,7 +142,7 @@ fn node_config, role: Role, - task_executor: Arc + Send>>, TaskType) + Send + Sync>, + task_executor: TaskExecutor, key_seed: Option, base_port: u16, root: &TempDir, @@ -176,7 +176,7 @@ fn node_config TestNet where authorities: impl Iterator Result<(F, U), Error>)> ) { let executor = self.runtime.executor(); + let task_executor = { + let executor = executor.clone(); + TaskExecutor::from_fn( + move |fut: Pin + Send>>, _| { + executor.spawn(fut.unit_error().compat()); + }, + ) + }; for (key, authority) in authorities { - let task_executor = { - let executor = executor.clone(); - Arc::new(move |fut: Pin + Send>>, _| executor.spawn(fut.unit_error().compat())) - }; let node_config = node_config( self.nodes, &self.chain_spec, Role::Authority { sentry_nodes: Vec::new() }, - task_executor, + task_executor.clone(), Some(key), self.base_port, &temp, @@ -281,11 +285,15 @@ impl TestNet where } for full in full { - let task_executor = { - let executor = executor.clone(); - Arc::new(move |fut: Pin + Send>>, _| executor.spawn(fut.unit_error().compat())) - }; - let node_config = node_config(self.nodes, &self.chain_spec, Role::Full, task_executor, None, self.base_port, &temp); + let node_config = node_config( + self.nodes, + &self.chain_spec, + Role::Full, + task_executor.clone(), + None, + self.base_port, + &temp, + ); let addr = node_config.network.listen_addresses.iter().next().unwrap().clone(); let (service, user_data) = full(node_config).expect("Error creating test node service"); let service = SyncService::from(service); @@ -297,11 +305,15 @@ impl TestNet where } for light in light { - let task_executor = { - let executor = executor.clone(); - Arc::new(move |fut: Pin + Send>>, _| executor.spawn(fut.unit_error().compat())) - }; - let node_config = node_config(self.nodes, &self.chain_spec, Role::Light, task_executor, None, self.base_port, &temp); + let node_config = node_config( + self.nodes, + &self.chain_spec, + Role::Light, + task_executor.clone(), + None, + self.base_port, + &temp, + ); let addr = node_config.network.listen_addresses.iter().next().unwrap().clone(); let service = SyncService::from(light(node_config).expect("Error creating test node service")); From 7b0590e4308c3072b96a82ad47504af0ba326e0c Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Thu, 18 Jun 2020 12:08:26 +0200 Subject: [PATCH 4/7] impl From for TaskExecutor --- client/cli/src/runner.rs | 28 ++++++++++++---------------- client/service/src/config.rs | 21 ++++++--------------- client/service/test/src/lib.rs | 10 ++++------ utils/browser/src/lib.rs | 4 ++-- 4 files changed, 24 insertions(+), 39 deletions(-) diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index 7aa5a99a7bb42..2aa649ff9746a 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -25,9 +25,7 @@ use futures::pin_mut; use futures::select; use futures::{future, future::FutureExt, Future}; use log::info; -use sc_service::{ - AbstractService, Configuration, Role, ServiceBuilderCommand, TaskType, config::TaskExecutor, -}; +use sc_service::{AbstractService, Configuration, Role, ServiceBuilderCommand, TaskType}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_utils::metrics::{TOKIO_THREADS_ALIVE, TOKIO_THREADS_TOTAL}; use sp_version::RuntimeVersion; @@ -121,23 +119,21 @@ impl Runner { let tokio_runtime = build_runtime()?; let runtime_handle = tokio_runtime.handle().clone(); - let task_executor = TaskExecutor::from_fn( - move |fut, task_type| { - match task_type { - TaskType::Async => { runtime_handle.spawn(fut); } - TaskType::Blocking => { - runtime_handle.spawn( async move { - // `spawn_blocking` is looking for the current runtime, and as such has to be called - // from within `spawn`. - tokio::task::spawn_blocking(move || futures::executor::block_on(fut)) - }); - } + let task_executor = move |fut, task_type| { + match task_type { + TaskType::Async => { runtime_handle.spawn(fut); } + TaskType::Blocking => { + runtime_handle.spawn( async move { + // `spawn_blocking` is looking for the current runtime, and as such has to + // be called from within `spawn`. + tokio::task::spawn_blocking(move || futures::executor::block_on(fut)) + }); } } - ); + }; Ok(Runner { - config: command.create_configuration(cli, task_executor)?, + config: command.create_configuration(cli, task_executor.into())?, tokio_runtime, phantom: PhantomData, }) diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 0eb62c55a3e74..2f54f84f717d4 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -266,14 +266,14 @@ impl std::fmt::Debug for TaskExecutor { } } -/* -impl std::convert::From for TaskExecutor { - fn from(x: TaskExecutorInner) - -> Self { - Self(x) +impl std::convert::From for TaskExecutor +where + F: Fn(Pin + Send>>, TaskType) + Send + Sync + 'static, +{ + fn from(x: F) -> Self { + Self(Arc::new(x)) } } -*/ impl std::ops::Deref for TaskExecutor { type Target = TaskExecutorInner; @@ -282,12 +282,3 @@ impl std::ops::Deref for TaskExecutor { &self.0 } } - -impl TaskExecutor { - /// Create a `TaskExecutor` from a function - pub fn from_fn( - f: impl Fn(Pin + Send>>, TaskType) + Send + Sync + 'static, - ) -> Self { - Self(Arc::new(f)) - } -} diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 0f1dd0f2d64de..932de27c0ed15 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -255,13 +255,11 @@ impl TestNet where authorities: impl Iterator Result<(F, U), Error>)> ) { let executor = self.runtime.executor(); - let task_executor = { + let task_executor: TaskExecutor = { let executor = executor.clone(); - TaskExecutor::from_fn( - move |fut: Pin + Send>>, _| { - executor.spawn(fut.unit_error().compat()); - }, - ) + (move |fut: Pin + Send>>, _| { + executor.spawn(fut.unit_error().compat()); + }).into() }; for (key, authority) in authorities { diff --git a/utils/browser/src/lib.rs b/utils/browser/src/lib.rs index 8776033acacd9..3e66321a22c76 100644 --- a/utils/browser/src/lib.rs +++ b/utils/browser/src/lib.rs @@ -20,7 +20,7 @@ use log::{debug, info}; use sc_network::config::TransportConfig; use sc_service::{ AbstractService, RpcSession, Role, Configuration, - config::{DatabaseConfig, KeystoreConfig, NetworkConfiguration, TaskExecutor}, + config::{DatabaseConfig, KeystoreConfig, NetworkConfiguration}, GenericChainSpec, RuntimeGenesis }; use wasm_bindgen::prelude::*; @@ -63,7 +63,7 @@ where network, telemetry_endpoints: chain_spec.telemetry_endpoints().clone(), chain_spec: Box::new(chain_spec), - task_executor: TaskExecutor::from_fn(|fut, _| wasm_bindgen_futures::spawn_local(fut)), + task_executor: (|fut, _| wasm_bindgen_futures::spawn_local(fut)).into(), telemetry_external_transport: Some(transport), role: Role::Light, database: { From d9e6275da97f670ef4eab09d5de2e09714ad341b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Fri, 19 Jun 2020 09:23:00 +0200 Subject: [PATCH 5/7] Update client/cli/src/runner.rs --- client/cli/src/runner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index 2aa649ff9746a..51ea2d21862ef 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -123,7 +123,7 @@ impl Runner { match task_type { TaskType::Async => { runtime_handle.spawn(fut); } TaskType::Blocking => { - runtime_handle.spawn( async move { + runtime_handle.spawn(async move { // `spawn_blocking` is looking for the current runtime, and as such has to // be called from within `spawn`. tokio::task::spawn_blocking(move || futures::executor::block_on(fut)) From d53a1c22ed8422d1090667b954dd102d5b1f1bec Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Fri, 19 Jun 2020 13:31:51 +0200 Subject: [PATCH 6/7] Add some doc, examples and tests --- client/service/src/config.rs | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 2f54f84f717d4..56b28efd578b1 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -257,6 +257,44 @@ impl std::convert::From for BasePath { type TaskExecutorInner = Arc + Send>>, TaskType) + Send + Sync>; /// Callable object that execute tasks. +/// +/// This struct can be created easily using `Into`. +/// +/// # Examples +/// +/// ## Using tokio +/// +/// ``` +/// # use sc_service::TaskExecutor; +/// # mod tokio { pub mod runtime { +/// # #[derive(Clone)] +/// # pub struct Runtime; +/// # impl Runtime { +/// # pub fn new() -> Result { Ok(Runtime) } +/// # pub fn handle(&self) -> &Self { &self } +/// # pub fn spawn(&self, _: std::pin::Pin + Send>>) {} +/// # } +/// # } } +/// use tokio::runtime::Runtime; +/// +/// let runtime = Runtime::new().unwrap(); +/// let handle = runtime.handle().clone(); +/// let task_executor: TaskExecutor = (move |future, _task_type| { +/// handle.spawn(future); +/// }).into(); +/// ``` +/// +/// ## Using async-std +/// +/// ``` +/// # use sc_service::TaskExecutor; +/// # mod async_std { pub mod task { +/// # pub fn spawn(_: std::pin::Pin + Send>>) {} +/// # } } +/// let task_executor: TaskExecutor = (|future, _task_type| { +/// async_std::task::spawn(future); +/// }).into(); +/// ``` #[derive(Clone)] pub struct TaskExecutor(TaskExecutorInner); From 5cb14a0d6024b3a11ea9a3aad170cae4557ec93c Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Fri, 19 Jun 2020 13:40:03 +0200 Subject: [PATCH 7/7] Replace Deref by fn spawn as suggested --- client/service/src/config.rs | 9 ++++----- client/service/src/task_manager.rs | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/client/service/src/config.rs b/client/service/src/config.rs index 56b28efd578b1..dc37fba1cec60 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -313,10 +313,9 @@ where } } -impl std::ops::Deref for TaskExecutor { - type Target = TaskExecutorInner; - - fn deref(&self) -> &Self::Target { - &self.0 +impl TaskExecutor { + /// Spawns a new asynchronous task. + pub fn spawn(&self, future: Pin + Send>>, task_type: TaskType) { + self.0(future, task_type) } } diff --git a/client/service/src/task_manager.rs b/client/service/src/task_manager.rs index 3ea1689ac2e19..bb03bed70ac18 100644 --- a/client/service/src/task_manager.rs +++ b/client/service/src/task_manager.rs @@ -109,7 +109,7 @@ impl SpawnTaskHandle { } }; - (self.executor)(Box::pin(future), task_type); + self.executor.spawn(Box::pin(future), task_type); } }