Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: get client version from crate and git #1309

Merged
merged 1 commit into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
38 changes: 23 additions & 15 deletions Cargo.lock

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

12 changes: 11 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ version = "0.1.0-beta.5"
authors = ["Nervos Dev <[email protected]>"]
edition = "2021"
repository = "https://github.com/axonweb3/axon"
build = "build.rs"

[dependencies]
clap = { version = "4.2", features = ["cargo"] }
clap = { version = "4.3", features = ["cargo"] }

# byzantine = { path = "./byzantine" }
common-version = { path = "./common/version" }
core-api = { path = "./core/api" }
core-cli = { path = "./core/cli" }
core-consensus = { path = "./core/consensus" }
Expand All @@ -28,6 +30,7 @@ members = [
"common/memory-tracker",
"common/merkle",
"common/pubsub",
"common/version",
"core/api",
"core/cli",
"core/consensus",
Expand Down Expand Up @@ -61,6 +64,13 @@ debug = true
overflow-checks = true
opt-level = 3

[lib]
path = "src/lib.rs"

[[bin]]
name = "axon"
path = "src/main.rs"

[[example]]
name = "custom_chain"
crate-type = ["bin"]
8 changes: 4 additions & 4 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
fn main() {
let desc = std::process::Command::new("git")
if let Some(commit_id) = std::process::Command::new("git")
.args(["describe", "--always", "--dirty", "--exclude", "*"])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
.map(|d| format!(" {d}"))
.unwrap_or_default();
println!("cargo:rustc-env=AXON_GIT_DESCRIPTION={desc}");
{
println!("cargo:rustc-env=AXON_COMMIT_ID={}", commit_id);
}
}
2 changes: 0 additions & 2 deletions common/config-parser/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@ pub struct ConfigApi {
pub maxconn: u32,
pub max_payload_size: u32,
pub enable_dump_profile: Option<bool>,
#[serde(default)]
pub client_version: String,
}

#[derive(Clone, Debug, Deserialize)]
Expand Down
8 changes: 8 additions & 0 deletions common/version/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "common-version"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
semver = "1.0"
60 changes: 60 additions & 0 deletions common/version/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use std::fmt::{Display, Formatter};
use std::str::FromStr;

pub const DEFAULT_COMMIT_ID: &str = "unknown";

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
inner: semver::Version,
}
KaoImin marked this conversation as resolved.
Show resolved Hide resolved

impl FromStr for Version {
type Err = semver::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
semver::Version::from_str(s).map(|inner| Version { inner })
}
}

impl Display for Version {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}

impl Version {
pub fn new(ver: &str) -> Self {
Version::from_str(ver)
.unwrap_or_else(|e| panic!("Parse version error {:?}", e))
.set_commit_id(DEFAULT_COMMIT_ID)
}

pub fn new_with_commit_id(ver: &str, commit_id: &str) -> Self {
Version::new(ver).set_commit_id(commit_id)
}

pub fn commit_id(&self) -> String {
self.inner.build.to_ascii_lowercase()
}

fn set_commit_id(mut self, commit_id: &str) -> Self {
self.inner.build = semver::BuildMetadata::new(commit_id)
.unwrap_or_else(|e| panic!("Parse commit id error {:?}", e));

self
}
}

#[cfg(test)]
mod tests {
use semver::BuildMetadata;
use std::str::FromStr;

use crate::DEFAULT_COMMIT_ID;

#[test]
fn test_parse_default_commit_id() {
let build = BuildMetadata::from_str(DEFAULT_COMMIT_ID);
assert_eq!(build.unwrap().as_str(), DEFAULT_COMMIT_ID);
}
}
6 changes: 3 additions & 3 deletions core/api/src/jsonrpc/impl/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ pub struct NodeRpcImpl {
}

impl NodeRpcImpl {
pub fn new(version: &str, path: PathBuf) -> Self {
pub fn new(ver: String, path: PathBuf) -> Self {
NodeRpcImpl {
version: version.to_string(),
pprof: Arc::new(AtomicBool::default()),
version: ver,
pprof: Arc::new(AtomicBool::new(false)),
_path: path.join("api"),
}
}
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/jsonrpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ pub trait CkbLightClientRpc {
}

pub async fn run_jsonrpc_server<Adapter: APIAdapter + 'static>(
version: String,
config: Config,
adapter: Arc<Adapter>,
) -> ProtocolResult<(Option<ServerHandle>, Option<ServerHandle>)> {
Expand All @@ -253,8 +254,7 @@ pub async fn run_jsonrpc_server<Adapter: APIAdapter + 'static>(
)
.into_rpc();

let node_rpc =
r#impl::NodeRpcImpl::new(&config.rpc.client_version, config.data_path).into_rpc();
let node_rpc = r#impl::NodeRpcImpl::new(version, config.data_path).into_rpc();
let axon_rpc = r#impl::AxonRpcImpl::new(Arc::clone(&adapter)).into_rpc();
let filter =
r#impl::filter_module(Arc::clone(&adapter), config.web3.log_filter_max_block_range)
Expand Down
3 changes: 2 additions & 1 deletion core/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = "4.2"
clap = { version = "4.3", features = ["cargo", "string"] }
semver = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand All @@ -14,5 +14,6 @@ thiserror = "1.0"

common-config-parser = { path = "../../common/config-parser" }
common-logger = { path = "../../common/logger" }
common-version = { path = "../../common/version" }
core-run = { path = "../../core/run" }
protocol = { path = "../../protocol", package = "axon-protocol" }
34 changes: 20 additions & 14 deletions core/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use std::path::Path;

use clap::{Arg, ArgMatches, Command};
use protocol::ProtocolError;
use semver::Version;
use thiserror::Error;

use common_config_parser::{parse_file, types::Config, ParseError};
use common_version::Version;
use core_run::{Axon, KeyProvider, SecioKeyPair};
use protocol::types::RichBlock;

Expand Down Expand Up @@ -47,14 +47,20 @@ pub struct CheckingVersionError {
pub type Result<T, E = Error> = std::result::Result<T, E>;

pub struct AxonCli {
version: Version,
matches: ArgMatches,
kernel_version: Version,
application_version: Version,
matches: ArgMatches,
}

impl AxonCli {
pub fn init(axon_version: Version, cli_version: &'static str) -> Self {
pub fn init(application_version: Version, kernel_version: Version) -> Self {
let mix_version = format!(
"{}-with-axon-kernel-{}",
application_version, kernel_version
);

let matches = Command::new("axon")
.version(cli_version)
.version(mix_version)
.subcommand_required(true)
.subcommand(
Command::new("run")
Expand All @@ -78,7 +84,8 @@ impl AxonCli {
);

AxonCli {
version: axon_version,
kernel_version,
application_version,
matches: matches.get_matches(),
}
}
Expand Down Expand Up @@ -112,7 +119,7 @@ impl AxonCli {

register_log(&config);

Axon::new(config, genesis)
Axon::new(self.application_version.to_string(), config, genesis)
.run(key_provider)
.map_err(Error::Running)
}
Expand All @@ -128,7 +135,7 @@ impl AxonCli {
// Won't panic because parent of data_path_for_version() is data_path.
check_version(
&config.data_path_for_version(),
&self.version,
&self.kernel_version,
latest_compatible_version(),
)
}
Expand All @@ -149,7 +156,7 @@ fn check_version(p: &Path, current: &Version, least_compatible: Version) -> Resu
return Ok(());
}

let prev_version = Version::parse(&ver_str).unwrap();
let prev_version = Version::new(&ver_str);
if prev_version < least_compatible {
return Err(Error::CheckingVersion(Box::new(CheckingVersionError {
least_compatible,
Expand Down Expand Up @@ -184,7 +191,7 @@ fn atomic_write(p: &Path, content: &[u8]) -> io::Result<()> {
}

fn latest_compatible_version() -> Version {
Version::parse("0.1.0-alpha.9").unwrap()
Version::new("0.1.0-beta.1")
}

fn register_log(config: &Config) {
Expand Down Expand Up @@ -226,20 +233,19 @@ mod tests {
}

#[test]
fn test_check_version_failure() -> Result<()> {
fn test_check_version_failure() {
let tmp = NamedTempFile::new().unwrap();
let p = tmp.path();
check_version(p, &"0.1.0".parse().unwrap(), "0.1.0".parse().unwrap())?;
check_version(p, &"0.1.0".parse().unwrap(), "0.1.0".parse().unwrap()).unwrap();
let err =
check_version(p, &"0.2.2".parse().unwrap(), "0.2.0".parse().unwrap()).unwrap_err();
match err {
Error::CheckingVersion(e) => assert_eq!(*e, CheckingVersionError {
current: "0.2.2".parse().unwrap(),
least_compatible: "0.2.0".parse().unwrap(),
data: "0.1.0".parse().unwrap(),
data: "0.1.0+unknown".parse().unwrap(),
}),
e => panic!("unexpected error {e}"),
}
Ok(())
}
}
Loading