Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Reduce parachain template cognitive complexity #1777

Merged
merged 4 commits into from
Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 9 additions & 17 deletions parachain-template/node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use cumulus_client_cli::generate_genesis_block;
use cumulus_primitives_core::ParaId;
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use log::{info, warn};
use parachain_template_runtime::{Block, RuntimeApi};
use parachain_template_runtime::Block;
use sc_cli::{
ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,
Expand All @@ -20,7 +20,7 @@ use sp_runtime::traits::{AccountIdConversion, Block as BlockT};
use crate::{
chain_spec,
cli::{Cli, RelayChainCli, Subcommand},
service::{new_partial, TemplateRuntimeExecutor},
service::{new_partial, ParachainNativeExecutor},
};

fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
Expand Down Expand Up @@ -116,11 +116,7 @@ macro_rules! construct_async_run {
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
let runner = $cli.create_runner($cmd)?;
runner.async_run(|$config| {
let $components = new_partial::<
RuntimeApi,
TemplateRuntimeExecutor,
_
>(
let $components = new_partial::<_>(
&$config,
crate::service::parachain_build_import_queue,
)?;
Expand Down Expand Up @@ -204,17 +200,15 @@ pub fn run() -> Result<()> {
match cmd {
BenchmarkCmd::Pallet(cmd) =>
if cfg!(feature = "runtime-benchmarks") {
runner.sync_run(|config| cmd.run::<Block, TemplateRuntimeExecutor>(config))
runner.sync_run(|config| cmd.run::<Block, ParachainNativeExecutor>(config))
} else {
Err("Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
.into())
},
BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {
let partials = new_partial::<RuntimeApi, TemplateRuntimeExecutor, _>(
&config,
crate::service::parachain_build_import_queue,
)?;
let partials =
new_partial::<_>(&config, crate::service::parachain_build_import_queue)?;
cmd.run(partials.client)
}),
#[cfg(not(feature = "runtime-benchmarks"))]
Expand All @@ -227,10 +221,8 @@ pub fn run() -> Result<()> {
.into()),
#[cfg(feature = "runtime-benchmarks")]
BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {
let partials = new_partial::<RuntimeApi, TemplateRuntimeExecutor, _>(
&config,
crate::service::parachain_build_import_queue,
)?;
let partials =
new_partial::<_>(&config, crate::service::parachain_build_import_queue)?;
let db = partials.backend.expose_db();
let storage = partials.backend.expose_storage();

Expand All @@ -255,7 +247,7 @@ pub fn run() -> Result<()> {
.map_err(|e| format!("Error: {:?}", e))?;

runner.async_run(|config| {
Ok((cmd.run::<Block, TemplateRuntimeExecutor>(config), task_manager))
Ok((cmd.run::<Block, ParachainNativeExecutor>(config), task_manager))
})
} else {
Err("Try-runtime must be enabled by `--features try-runtime`.".into())
Expand Down
122 changes: 30 additions & 92 deletions parachain-template/node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ use jsonrpsee::RpcModule;

use cumulus_client_cli::CollatorOptions;
// Local Runtime Types
use parachain_template_runtime::{
opaque::Block, AccountId, Balance, Hash, Index as Nonce, RuntimeApi,
};
use parachain_template_runtime::{opaque::Block, Hash, RuntimeApi};

// Cumulus Imports
use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};
Expand All @@ -30,17 +28,15 @@ use sc_network::NetworkService;
use sc_network_common::service::NetworkBlock;
use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
use sp_api::ConstructRuntimeApi;
use sp_keystore::SyncCryptoStorePtr;
use sp_runtime::traits::BlakeTwo256;
use substrate_prometheus_endpoint::Registry;

use polkadot_service::CollatorPair;

/// Native executor instance.
pub struct TemplateRuntimeExecutor;
/// Native executor type.
pub struct ParachainNativeExecutor;

impl sc_executor::NativeExecutionDispatch for TemplateRuntimeExecutor {
impl sc_executor::NativeExecutionDispatch for ParachainNativeExecutor {
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;

fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
Expand All @@ -52,56 +48,39 @@ impl sc_executor::NativeExecutionDispatch for TemplateRuntimeExecutor {
}
}

type ParachainExecutor = NativeElseWasmExecutor<ParachainNativeExecutor>;

type ParachainClient = TFullClient<Block, RuntimeApi, ParachainExecutor>;

type ParachainBackend = TFullBackend<Block>;

/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
#[allow(clippy::type_complexity)]
pub fn new_partial<RuntimeApi, Executor, BIQ>(
pub fn new_partial<BIQ>(
config: &Configuration,
build_import_queue: BIQ,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to be configurable, whoever copied the code didn't know this. So, if you remove this, the code will get even less complicated :D

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed. I'll do it before merge. Ty

) -> Result<
PartialComponents<
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
TFullBackend<Block>,
ParachainClient,
ParachainBackend,
(),
sc_consensus::DefaultImportQueue<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
>,
sc_transaction_pool::FullPool<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
>,
sc_consensus::DefaultImportQueue<Block, ParachainClient>,
sc_transaction_pool::FullPool<Block, ParachainClient>,
(Option<Telemetry>, Option<TelemetryWorkerHandle>),
>,
sc_service::Error,
>
where
RuntimeApi: ConstructRuntimeApi<Block, TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>
+ Send
+ Sync
+ 'static,
RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+ sp_api::Metadata<Block>
+ sp_session::SessionKeys<Block>
+ sp_api::ApiExt<
Block,
StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>,
> + sp_offchain::OffchainWorkerApi<Block>
+ sp_block_builder::BlockBuilder<Block>,
sc_client_api::StateBackendFor<TFullBackend<Block>, Block>: sp_api::StateBackend<BlakeTwo256>,
Executor: sc_executor::NativeExecutionDispatch + 'static,
BIQ: FnOnce(
Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>,
Arc<ParachainClient>,
&Configuration,
Option<TelemetryHandle>,
&TaskManager,
) -> Result<
sc_consensus::DefaultImportQueue<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
>,
sc_consensus::DefaultImportQueue<Block, ParachainClient>,
sc_service::Error,
>,
{
Expand All @@ -116,7 +95,7 @@ where
})
.transpose()?;

let executor = sc_executor::NativeElseWasmExecutor::<Executor>::new(
let executor = ParachainExecutor::new(
config.wasm_method,
config.default_heap_pages,
config.max_runtime_instances,
Expand Down Expand Up @@ -192,7 +171,7 @@ async fn build_relay_chain_interface(
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[sc_tracing::logging::prefix_logs_with("Parachain")]
async fn start_node_impl<RuntimeApi, Executor, RB, BIQ, BIC>(
async fn start_node_impl<RB, BIQ, BIC>(
parachain_config: Configuration,
polkadot_config: Configuration,
collator_options: CollatorOptions,
Expand All @@ -201,65 +180,33 @@ async fn start_node_impl<RuntimeApi, Executor, RB, BIQ, BIC>(
build_import_queue: BIQ,
build_consensus: BIC,
hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(
TaskManager,
Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>,
)>
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)>
where
RuntimeApi: ConstructRuntimeApi<Block, TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>
+ Send
+ Sync
+ 'static,
RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+ sp_api::Metadata<Block>
+ sp_session::SessionKeys<Block>
+ sp_api::ApiExt<
Block,
StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>,
> + sp_offchain::OffchainWorkerApi<Block>
+ sp_block_builder::BlockBuilder<Block>
+ cumulus_primitives_core::CollectCollationInfo<Block>
+ pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>
+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
sc_client_api::StateBackendFor<TFullBackend<Block>, Block>: sp_api::StateBackend<BlakeTwo256>,
Executor: sc_executor::NativeExecutionDispatch + 'static,
RB: Fn(
Arc<TFullClient<Block, RuntimeApi, Executor>>,
) -> Result<RpcModule<()>, sc_service::Error>
+ Send
+ 'static,
RB: Fn(Arc<ParachainClient>) -> Result<RpcModule<()>, sc_service::Error> + Send + 'static,
BIQ: FnOnce(
Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>,
Arc<ParachainClient>,
&Configuration,
Option<TelemetryHandle>,
&TaskManager,
) -> Result<
sc_consensus::DefaultImportQueue<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
>,
sc_consensus::DefaultImportQueue<Block, ParachainClient>,
sc_service::Error,
> + 'static,
BIC: FnOnce(
Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>>,
Arc<ParachainClient>,
Option<&Registry>,
Option<TelemetryHandle>,
&TaskManager,
Arc<dyn RelayChainInterface>,
Arc<
sc_transaction_pool::FullPool<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>,
>,
>,
Arc<sc_transaction_pool::FullPool<Block, ParachainClient>>,
Arc<NetworkService<Block, Hash>>,
SyncCryptoStorePtr,
bool,
) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,
{
let parachain_config = prepare_node_config(parachain_config);

let params = new_partial::<RuntimeApi, Executor, BIQ>(&parachain_config, build_import_queue)?;
let params = new_partial::<BIQ>(&parachain_config, build_import_queue)?;
let (mut telemetry, telemetry_worker_handle) = params.other;

let client = params.client.clone();
Expand Down Expand Up @@ -400,17 +347,11 @@ where
/// Build the import queue for the parachain runtime.
#[allow(clippy::type_complexity)]
pub fn parachain_build_import_queue(
client: Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<TemplateRuntimeExecutor>>>,
client: Arc<ParachainClient>,
config: &Configuration,
telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager,
) -> Result<
sc_consensus::DefaultImportQueue<
Block,
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<TemplateRuntimeExecutor>>,
>,
sc_service::Error,
> {
) -> Result<sc_consensus::DefaultImportQueue<Block, ParachainClient>, sc_service::Error> {
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;

cumulus_client_consensus_aura::import_queue::<
Expand Down Expand Up @@ -448,11 +389,8 @@ pub async fn start_parachain_node(
collator_options: CollatorOptions,
id: ParaId,
hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(
TaskManager,
Arc<TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<TemplateRuntimeExecutor>>>,
)> {
start_node_impl::<RuntimeApi, TemplateRuntimeExecutor, _, _, _>(
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient>)> {
start_node_impl::<_, _, _>(
parachain_config,
polkadot_config,
collator_options,
Expand Down
Loading