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

Commit ff3be27

Browse files
Move type Migrations to Config (#14309)
* move migrate sequence to config * remove commented out code * Update frame/contracts/src/lib.rs Co-authored-by: PG Herveou <[email protected]> * remove Migrations generic * make runtime use noop migrations * restrict is_upgrade_supported * undo is_upgrade_supported change * Update bin/node/runtime/src/lib.rs Co-authored-by: PG Herveou <[email protected]> * add rust doc example for `Migrations` * feature gate NoopMigration * fix example code * improve example --------- Co-authored-by: PG Herveou <[email protected]>
1 parent e434882 commit ff3be27

File tree

4 files changed

+81
-76
lines changed

4 files changed

+81
-76
lines changed

bin/node/runtime/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ use frame_system::{
5555
pub use node_primitives::{AccountId, Signature};
5656
use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment};
5757
use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter};
58+
#[cfg(feature = "runtime-benchmarks")]
59+
use pallet_contracts::NoopMigration;
5860
use pallet_election_provider_multi_phase::SolutionAccuracyOf;
5961
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
6062
use pallet_nfts::PalletFeatures;
@@ -1240,6 +1242,10 @@ impl pallet_contracts::Config for Runtime {
12401242
type MaxStorageKeyLen = ConstU32<128>;
12411243
type UnsafeUnstableInterface = ConstBool<false>;
12421244
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
1245+
#[cfg(not(feature = "runtime-benchmarks"))]
1246+
type Migrations = ();
1247+
#[cfg(feature = "runtime-benchmarks")]
1248+
type Migrations = (NoopMigration<1>, NoopMigration<2>);
12431249
}
12441250

12451251
impl pallet_sudo::Config for Runtime {

frame/contracts/src/lib.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,12 @@ mod address;
8787
mod benchmarking;
8888
mod exec;
8989
mod gas;
90-
mod migration;
9190
mod schedule;
9291
mod storage;
9392
mod wasm;
9493

9594
pub mod chain_extension;
95+
pub mod migration;
9696
pub mod weights;
9797

9898
#[cfg(test)]
@@ -319,6 +319,16 @@ pub mod pallet {
319319
/// The maximum length of the debug buffer in bytes.
320320
#[pallet::constant]
321321
type MaxDebugBufferLen: Get<u32>;
322+
323+
/// The sequence of migration steps that will be applied during a migration.
324+
///
325+
/// # Examples
326+
/// ```
327+
/// use pallet_contracts::migration::{v9, v10, v11};
328+
/// # struct Runtime {};
329+
/// type Migrations = (v9::Migration<Runtime>, v10::Migration<Runtime>, v11::Migration<Runtime>);
330+
/// ```
331+
type Migrations: MigrateSequence;
322332
}
323333

324334
#[pallet::hooks]

frame/contracts/src/migration.rs

Lines changed: 61 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,10 @@
1717

1818
//! Migration framework for pallets.
1919
20-
/// Macro to include all migration modules.
21-
/// We only want to make these modules public when `runtime-benchmarks` is
22-
/// enabled, so we can access migration code in benchmarks.
23-
macro_rules! use_modules {
24-
($($module:ident),*) => {
25-
$(
26-
#[cfg(feature = "runtime-benchmarks")]
27-
pub mod $module;
28-
#[cfg(not(feature = "runtime-benchmarks"))]
29-
mod $module;
30-
)*
31-
};
32-
}
20+
pub mod v10;
21+
pub mod v11;
22+
pub mod v9;
3323

34-
use_modules!(v9, v10, v11);
3524
use crate::{weights::WeightInfo, Config, Error, MigrationInProgress, Pallet, Weight, LOG_TARGET};
3625
use codec::{Codec, Decode};
3726
use frame_support::{
@@ -58,10 +47,6 @@ fn invalid_version(version: StorageVersion) -> ! {
5847
/// The cursor used to store the state of the current migration step.
5948
pub type Cursor = BoundedVec<u8, ConstU32<1024>>;
6049

61-
// In benchmark and tests we use noop migrations, to test and bench the migration framework itself.
62-
#[cfg(not(any(feature = "runtime-benchmarks", test)))]
63-
type Migrations<T> = (v9::Migration<T>, v10::Migration<T>, v11::Migration<T>);
64-
6550
/// IsFinished describes whether a migration is finished or not.
6651
pub enum IsFinished {
6752
Yes,
@@ -206,23 +191,16 @@ pub trait MigrateSequence: private::Sealed {
206191
}
207192

208193
/// Performs all necessary migrations based on `StorageVersion`.
209-
#[cfg(not(any(feature = "runtime-benchmarks", test)))]
210-
pub struct Migration<T: Config, M: MigrateSequence = Migrations<T>>(PhantomData<(T, M)>);
211-
212-
/// Custom migration for running runtime-benchmarks and tests.
213-
#[cfg(any(feature = "runtime-benchmarks", test))]
214-
pub struct Migration<T: Config, M: MigrateSequence = (NoopMigration<1>, NoopMigration<2>)>(
215-
PhantomData<(T, M)>,
216-
);
194+
pub struct Migration<T: Config>(PhantomData<T>);
217195

218196
#[cfg(feature = "try-runtime")]
219-
impl<T: Config, M: MigrateSequence> Migration<T, M> {
197+
impl<T: Config> Migration<T> {
220198
fn run_all_steps() -> Result<(), TryRuntimeError> {
221199
let mut weight = Weight::zero();
222200
let name = <Pallet<T>>::name();
223201
loop {
224202
let in_progress_version = <Pallet<T>>::on_chain_storage_version() + 1;
225-
let state = M::pre_upgrade_step(in_progress_version)?;
203+
let state = T::Migrations::pre_upgrade_step(in_progress_version)?;
226204
let (status, w) = Self::migrate(Weight::MAX);
227205
weight.saturating_accrue(w);
228206
log::info!(
@@ -231,7 +209,7 @@ impl<T: Config, M: MigrateSequence> Migration<T, M> {
231209
in_progress_version,
232210
weight
233211
);
234-
M::post_upgrade_step(in_progress_version, state)?;
212+
T::Migrations::post_upgrade_step(in_progress_version, state)?;
235213
if matches!(status, MigrateResult::Completed) {
236214
break
237215
}
@@ -243,7 +221,7 @@ impl<T: Config, M: MigrateSequence> Migration<T, M> {
243221
}
244222
}
245223

246-
impl<T: Config, M: MigrateSequence> OnRuntimeUpgrade for Migration<T, M> {
224+
impl<T: Config> OnRuntimeUpgrade for Migration<T> {
247225
fn on_runtime_upgrade() -> Weight {
248226
let name = <Pallet<T>>::name();
249227
let latest_version = <Pallet<T>>::current_storage_version();
@@ -274,7 +252,7 @@ impl<T: Config, M: MigrateSequence> OnRuntimeUpgrade for Migration<T, M> {
274252
"{name}: Upgrading storage from {storage_version:?} to {latest_version:?}.",
275253
);
276254

277-
let cursor = M::new(storage_version + 1);
255+
let cursor = T::Migrations::new(storage_version + 1);
278256
MigrationInProgress::<T>::set(Some(cursor));
279257

280258
#[cfg(feature = "try-runtime")]
@@ -295,11 +273,14 @@ impl<T: Config, M: MigrateSequence> OnRuntimeUpgrade for Migration<T, M> {
295273
target: LOG_TARGET,
296274
"{}: Range supported {:?}, range requested {:?}",
297275
<Pallet<T>>::name(),
298-
M::VERSION_RANGE,
276+
T::Migrations::VERSION_RANGE,
299277
(storage_version, target_version)
300278
);
301279

302-
ensure!(M::is_upgrade_supported(storage_version, target_version), "Unsupported upgrade");
280+
ensure!(
281+
T::Migrations::is_upgrade_supported(storage_version, target_version),
282+
"Unsupported upgrade"
283+
);
303284
Ok(Default::default())
304285
}
305286
}
@@ -324,11 +305,11 @@ pub enum StepResult {
324305
Completed { steps_done: u32 },
325306
}
326307

327-
impl<T: Config, M: MigrateSequence> Migration<T, M> {
328-
/// Verify that each migration's step of the MigrateSequence fits into `Cursor`.
308+
impl<T: Config> Migration<T> {
309+
/// Verify that each migration's step of the [`T::Migrations`] sequence fits into `Cursor`.
329310
pub(crate) fn integrity_test() {
330311
let max_weight = <T as frame_system::Config>::BlockWeights::get().max_block;
331-
M::integrity_test(max_weight)
312+
T::Migrations::integrity_test(max_weight)
332313
}
333314

334315
/// Migrate
@@ -357,33 +338,36 @@ impl<T: Config, M: MigrateSequence> Migration<T, M> {
357338
in_progress_version,
358339
);
359340

360-
let result =
361-
match M::steps(in_progress_version, cursor_before.as_ref(), &mut weight_left) {
362-
StepResult::InProgress { cursor, steps_done } => {
363-
*progress = Some(cursor);
341+
let result = match T::Migrations::steps(
342+
in_progress_version,
343+
cursor_before.as_ref(),
344+
&mut weight_left,
345+
) {
346+
StepResult::InProgress { cursor, steps_done } => {
347+
*progress = Some(cursor);
348+
MigrateResult::InProgress { steps_done }
349+
},
350+
StepResult::Completed { steps_done } => {
351+
in_progress_version.put::<Pallet<T>>();
352+
if <Pallet<T>>::current_storage_version() != in_progress_version {
353+
log::info!(
354+
target: LOG_TARGET,
355+
"{name}: Next migration is {:?},",
356+
in_progress_version + 1
357+
);
358+
*progress = Some(T::Migrations::new(in_progress_version + 1));
364359
MigrateResult::InProgress { steps_done }
365-
},
366-
StepResult::Completed { steps_done } => {
367-
in_progress_version.put::<Pallet<T>>();
368-
if <Pallet<T>>::current_storage_version() != in_progress_version {
369-
log::info!(
370-
target: LOG_TARGET,
371-
"{name}: Next migration is {:?},",
372-
in_progress_version + 1
373-
);
374-
*progress = Some(M::new(in_progress_version + 1));
375-
MigrateResult::InProgress { steps_done }
376-
} else {
377-
log::info!(
378-
target: LOG_TARGET,
379-
"{name}: All migrations done. At version {:?},",
380-
in_progress_version
381-
);
382-
*progress = None;
383-
MigrateResult::Completed
384-
}
385-
},
386-
};
360+
} else {
361+
log::info!(
362+
target: LOG_TARGET,
363+
"{name}: All migrations done. At version {:?},",
364+
in_progress_version
365+
);
366+
*progress = None;
367+
MigrateResult::Completed
368+
}
369+
},
370+
};
387371

388372
(result, weight_limit.saturating_sub(weight_left))
389373
})
@@ -527,11 +511,14 @@ mod test {
527511

528512
#[test]
529513
fn is_upgrade_supported_works() {
530-
type M = (MockMigration<9>, MockMigration<10>, MockMigration<11>);
514+
type Migrations = (MockMigration<9>, MockMigration<10>, MockMigration<11>);
531515

532516
[(1, 1), (8, 11), (9, 11)].into_iter().for_each(|(from, to)| {
533517
assert!(
534-
M::is_upgrade_supported(StorageVersion::new(from), StorageVersion::new(to)),
518+
Migrations::is_upgrade_supported(
519+
StorageVersion::new(from),
520+
StorageVersion::new(to)
521+
),
535522
"{} -> {} is supported",
536523
from,
537524
to
@@ -540,7 +527,10 @@ mod test {
540527

541528
[(1, 0), (0, 3), (7, 11), (8, 10)].into_iter().for_each(|(from, to)| {
542529
assert!(
543-
!M::is_upgrade_supported(StorageVersion::new(from), StorageVersion::new(to)),
530+
!Migrations::is_upgrade_supported(
531+
StorageVersion::new(from),
532+
StorageVersion::new(to)
533+
),
544534
"{} -> {} is not supported",
545535
from,
546536
to
@@ -550,27 +540,26 @@ mod test {
550540

551541
#[test]
552542
fn steps_works() {
553-
type M = (MockMigration<2>, MockMigration<3>);
543+
type Migrations = (MockMigration<2>, MockMigration<3>);
554544
let version = StorageVersion::new(2);
555-
let mut cursor = M::new(version);
545+
let mut cursor = Migrations::new(version);
556546

557547
let mut weight = Weight::from_all(2);
558-
let result = M::steps(version, &cursor, &mut weight);
548+
let result = Migrations::steps(version, &cursor, &mut weight);
559549
cursor = vec![1u8, 0].try_into().unwrap();
560550
assert_eq!(result, StepResult::InProgress { cursor: cursor.clone(), steps_done: 1 });
561551
assert_eq!(weight, Weight::from_all(1));
562552

563553
let mut weight = Weight::from_all(2);
564554
assert_eq!(
565-
M::steps(version, &cursor, &mut weight),
555+
Migrations::steps(version, &cursor, &mut weight),
566556
StepResult::Completed { steps_done: 1 }
567557
);
568558
}
569559

570560
#[test]
571561
fn no_migration_in_progress_works() {
572-
type M = (MockMigration<1>, MockMigration<2>);
573-
type TestMigration = Migration<Test, M>;
562+
type TestMigration = Migration<Test>;
574563

575564
ExtBuilder::default().build().execute_with(|| {
576565
assert_eq!(StorageVersion::get::<Pallet<Test>>(), 2);
@@ -580,8 +569,7 @@ mod test {
580569

581570
#[test]
582571
fn migration_works() {
583-
type M = (MockMigration<1>, MockMigration<2>);
584-
type TestMigration = Migration<Test, M>;
572+
type TestMigration = Migration<Test>;
585573

586574
ExtBuilder::default().set_storage_version(0).build().execute_with(|| {
587575
assert_eq!(StorageVersion::get::<Pallet<Test>>(), 0);

frame/contracts/src/tests.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ use crate::{
2828
wasm::{Determinism, PrefabWasmModule, ReturnCode as RuntimeReturnCode},
2929
weights::WeightInfo,
3030
BalanceOf, Code, CodeStorage, CollectEvents, Config, ContractInfo, ContractInfoOf, DebugInfo,
31-
DefaultAddressGenerator, DeletionQueueCounter, Error, MigrationInProgress, Origin, Pallet,
32-
Schedule,
31+
DefaultAddressGenerator, DeletionQueueCounter, Error, MigrationInProgress, NoopMigration,
32+
Origin, Pallet, Schedule,
3333
};
3434
use assert_matches::assert_matches;
3535
use codec::Encode;
@@ -428,6 +428,7 @@ impl Config for Test {
428428
type MaxStorageKeyLen = ConstU32<128>;
429429
type UnsafeUnstableInterface = UnstableInterface;
430430
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
431+
type Migrations = (NoopMigration<1>, NoopMigration<2>);
431432
}
432433

433434
pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]);

0 commit comments

Comments
 (0)