Skip to content

Commit

Permalink
chore/error: remove from str conversion and add deprecation notificat… (
Browse files Browse the repository at this point in the history
paritytech#7472)

* chore/error: remove from str conversion and add deprecation notifications

* fixup changes

* fix test looking for gone ::Msg variant

* another test fix

* one is duplicate, the other is not, so duplicates reported are n-1

* darn spaces

Co-authored-by: Andronik Ordian <write@reusable.software>

* remove pointless doc comments of error variants without any value

* low hanging fruits (for a tall person)

* moar error type variants

* avoid the storage modules for now

They are in need of a refactor, and the pain is rather large
removing all String error and DefaultError occurences.

* chore remove pointless error generic

* fix test for mocks, add a bunch of non_exhaustive

* max line width

* test fixes due to error changes

* fin

* error outputs... again

* undo stderr adjustments

* Update client/consensus/slots/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* remove closure clutter

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* more error types

* introduce ApiError

* extract Mock error

* ApiError refactor

* even more error types

* the last for now

* chore unused deps

* another extraction

* reduce should panic, due to extended error messages

* error test happiness

* shift error lines by one

* doc tests

* white space

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Into -> From

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* remove pointless codec

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* avoid pointless self import

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

Co-authored-by: Bernhard Schuster <bernhard@parity.io>
Co-authored-by: Andronik Ordian <write@reusable.software>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
  • Loading branch information
4 people authored and darkfriend77 committed Jan 11, 2021
1 parent 7bef0db commit 39b3132
Show file tree
Hide file tree
Showing 48 changed files with 498 additions and 348 deletions.
16 changes: 12 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,4 @@ prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.
kvdb-memorydb = "0.7.0"
sp-test-primitives = { version = "2.0.0", path = "../../primitives/test-primitives" }
substrate-test-runtime = { version = "2.0.0", path = "../../test-utils/runtime" }
thiserror = "1.0.21"
16 changes: 12 additions & 4 deletions client/api/src/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,13 +312,21 @@ pub mod tests {
use sp_test_primitives::{Block, Header, Extrinsic};
use super::*;

#[derive(Debug, thiserror::Error)]
#[error("Not implemented on test node")]
struct MockError;

impl Into<ClientError> for MockError {
fn into(self) -> ClientError {
ClientError::Application(Box::new(self))
}
}

pub type OkCallFetcher = Mutex<Vec<u8>>;

fn not_implemented_in_tests<T, E>() -> Ready<Result<T, E>>
where
E: std::convert::From<&'static str>,
fn not_implemented_in_tests<T>() -> Ready<Result<T, ClientError>>
{
futures::future::ready(Err("Not implemented on test node".into()))
futures::future::ready(Err(MockError.into()))
}

impl Fetcher<Block> for OkCallFetcher {
Expand Down
5 changes: 1 addition & 4 deletions client/basic-authorship/src/basic_authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,7 @@ impl<A, B, Block, C> sp_consensus::Proposer<Block> for
}));

async move {
match rx.await {
Ok(x) => x,
Err(err) => Err(sp_blockchain::Error::Msg(err.to_string()))
}
rx.await?
}.boxed()
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/block-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ where
&state,
changes_trie_state.as_ref(),
parent_hash,
)?;
).map_err(|e| sp_blockchain::Error::StorageChanges(e))?;

Ok(BuiltBlock {
block: <Block as BlockT>::new(header, self.extrinsics),
Expand Down
45 changes: 21 additions & 24 deletions client/cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,64 +25,61 @@ pub type Result<T> = std::result::Result<T, Error>;

/// Error type for the CLI.
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
/// Io error
#[error(transparent)]
Io(#[from] std::io::Error),
/// Cli error

#[error(transparent)]
Cli(#[from] structopt::clap::Error),
/// Service error

#[error(transparent)]
Service(#[from] sc_service::Error),
/// Client error

#[error(transparent)]
Client(#[from] sp_blockchain::Error),
/// scale codec error

#[error(transparent)]
Codec(#[from] parity_scale_codec::Error),
/// Input error

#[error("Invalid input: {0}")]
Input(String),
/// Invalid listen multiaddress

#[error("Invalid listen multiaddress")]
InvalidListenMultiaddress,
/// Application specific error chain sequence forwarder.
#[error(transparent)]
Application(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
/// URI error.

#[error("Invalid URI; expecting either a secret URI or a public URI.")]
InvalidUri(crypto::PublicError),
/// Signature length mismatch.

#[error("Signature has an invalid length. Read {read} bytes, expected {expected} bytes")]
SignatureInvalidLength {
/// Amount of signature bytes read.
read: usize,
/// Expected number of signature bytes.
expected: usize,
},
/// Missing base path argument.

#[error("The base path is missing, please provide one")]
MissingBasePath,
/// Unknown key type specifier or missing key type specifier.

#[error("Unknown key type, must be a known 4-character sequence")]
KeyTypeInvalid,
/// Signature verification failed.

#[error("Signature verification failed")]
SignatureInvalid,
/// Storing a given key failed.

#[error("Key store operation failed")]
KeyStoreOperation,
/// An issue with the underlying key storage was encountered.

#[error("Key storage issue encountered")]
KeyStorage(#[from] sc_keystore::Error),
/// Bytes are not decodable when interpreted as hexadecimal string.
#[error("Invalid hex base data")]

#[error("Invalid hexadecimal string data")]
HexDataConversion(#[from] hex::FromHexError),
/// Shortcut type to specify types on the fly, discouraged.
#[deprecated = "Use `Forwarded` with an error type instead."]
#[error("Other: {0}")]
Other(String),

/// Application specific error chain sequence forwarder.
#[error(transparent)]
Application(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl std::convert::From<&str> for Error {
Expand All @@ -93,7 +90,7 @@ impl std::convert::From<&str> for Error {

impl std::convert::From<String> for Error {
fn from(s: String) -> Error {
Error::Input(s.to_string())
Error::Input(s)
}
}

Expand Down
3 changes: 2 additions & 1 deletion client/consensus/slots/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ sp-inherents = { version = "2.0.0", path = "../../../primitives/inherents" }
futures = "0.3.4"
futures-timer = "3.0.1"
parking_lot = "0.10.0"
log = "0.4.8"
log = "0.4.11"
thiserror = "1.0.21"

[dev-dependencies]
substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" }
22 changes: 15 additions & 7 deletions client/consensus/slots/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
//! time during which certain events can and/or must occur. This crate
//! provides generic functionality for slots.

#![forbid(unsafe_code, missing_docs)]
#![forbid(unsafe_code)]
#![deny(missing_docs)]

mod slots;
mod aux_schema;
Expand Down Expand Up @@ -470,6 +471,15 @@ pub enum CheckedHeader<H, S> {
Checked(H, S),
}



#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error<T> where T: SlotData + Clone + Debug + Send + Sync + 'static {
#[error("Slot duration is invalid: {0:?}")]
SlotDurationInvalid(SlotDuration<T>),
}

/// A slot duration. Create with `get_or_compute`.
// The internal member should stay private here to maintain invariants of
// `get_or_compute`.
Expand All @@ -494,7 +504,7 @@ impl<T: SlotData + Clone> SlotData for SlotDuration<T> {
const SLOT_KEY: &'static [u8] = T::SLOT_KEY;
}

impl<T: Clone> SlotDuration<T> {
impl<T: Clone + Send + Sync + 'static> SlotDuration<T> {
/// Either fetch the slot duration from disk or compute it from the
/// genesis state.
///
Expand Down Expand Up @@ -532,10 +542,8 @@ impl<T: Clone> SlotDuration<T> {
}
}?;

if slot_duration.slot_duration() == 0 {
return Err(sp_blockchain::Error::Msg(
"Invalid value for slot_duration: the value must be greater than 0.".into(),
))
if slot_duration.slot_duration() == 0u64 {
return Err(sp_blockchain::Error::Application(Box::new(Error::SlotDurationInvalid(slot_duration))))
}

Ok(slot_duration)
Expand Down Expand Up @@ -939,7 +947,7 @@ mod test {
true, true, true, true,
];

assert_eq!(backoff, expected);
assert_eq!(backoff.as_slice(), &expected[..]);
}

#[test]
Expand Down
12 changes: 4 additions & 8 deletions client/db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -891,9 +891,7 @@ impl<Block: BlockT> Backend<Block> {
let is_archive_pruning = config.pruning.is_archive();
let blockchain = BlockchainDb::new(db.clone())?;
let meta = blockchain.meta.clone();
let map_e = |e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(
format!("State database error: {:?}", e)
);
let map_e = |e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e);
let state_db: StateDb<_, _> = StateDb::new(
config.pruning.clone(),
!config.source.supports_ref_counting(),
Expand Down Expand Up @@ -1082,7 +1080,7 @@ impl<Block: BlockT> Backend<Block> {

trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash);
let commit = self.storage.state_db.canonicalize_block(&hash)
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e))?;
apply_state_commit(transaction, commit);
};

Expand Down Expand Up @@ -1212,9 +1210,7 @@ impl<Block: BlockT> Backend<Block> {
number_u64,
&pending_block.header.parent_hash(),
changeset,
).map_err(|e: sc_state_db::Error<io::Error>|
sp_blockchain::Error::from(format!("State database error: {:?}", e))
)?;
).map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e))?;
apply_state_commit(&mut transaction, commit);

// Check if need to finalize. Genesis is always finalized instantly.
Expand Down Expand Up @@ -1379,7 +1375,7 @@ impl<Block: BlockT> Backend<Block> {
transaction.set_from_vec(columns::META, meta_keys::FINALIZED_BLOCK, lookup_key);

let commit = self.storage.state_db.canonicalize_block(&f_hash)
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e))?;
apply_state_commit(transaction, commit);

if !f_num.is_zero() {
Expand Down
3 changes: 1 addition & 2 deletions client/executor/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,15 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
log = "0.4.8"
derive_more = "0.99.2"
parity-wasm = "0.41.0"
codec = { package = "parity-scale-codec", version = "1.3.4" }
wasmi = "0.6.2"
sp-core = { version = "2.0.0", path = "../../../primitives/core" }
sp-allocator = { version = "2.0.0", path = "../../../primitives/allocator" }
sp-wasm-interface = { version = "2.0.0", path = "../../../primitives/wasm-interface" }
sp-runtime-interface = { version = "2.0.0", path = "../../../primitives/runtime-interface" }
sp-serializer = { version = "2.0.0", path = "../../../primitives/serializer" }
thiserror = "1.0.21"

[features]
default = []
Loading

0 comments on commit 39b3132

Please sign in to comment.