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

jsonrpc-feature returned #417

Merged
merged 42 commits into from
Nov 29, 2023
Merged
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
27257ce
feat: go from websocket-server to json rpc websocket/http server
zeeshanlakhani Oct 31, 2023
16392e7
refactor: cleanup settings
zeeshanlakhani Oct 31, 2023
234621d
refactor: testing around e2e websocket/jsonrpc, feature-fl
zeeshanlakhani Nov 2, 2023
ed774e4
chore: return of the retry
zeeshanlakhani Nov 3, 2023
708369e
chore: test setup
zeeshanlakhani Nov 3, 2023
6da6e71
fix: subscription map, checks, multiple broadcasts
zeeshanlakhani Nov 6, 2023
3af2ff1
fix: move to sub id as lookup key
zeeshanlakhani Nov 6, 2023
5659f06
chore: cleanup
zeeshanlakhani Nov 6, 2023
049a4ba
chore: fix warning
zeeshanlakhani Nov 6, 2023
44b8485
chore: comment
zeeshanlakhani Nov 6, 2023
64bfe77
chore: websocket->webserver
zeeshanlakhani Nov 7, 2023
058deef
feat: Add event notifications (#410)
bgins Nov 7, 2023
713718e
fix: p2p timeout, ipfs settings, more
zeeshanlakhani Nov 8, 2023
ff4ebc8
chore: updates, new wasms
zeeshanlakhani Nov 8, 2023
aa1d673
chore: add one cleanup
zeeshanlakhani Nov 8, 2023
14d7dc2
chore: wasms update is life
zeeshanlakhani Nov 8, 2023
20694da
chore: test fixins
zeeshanlakhani Nov 8, 2023
f6a3b4f
chore: minor updates
zeeshanlakhani Nov 9, 2023
b7ae3f9
chore: updates
zeeshanlakhani Nov 9, 2023
0aac079
chore: updates
zeeshanlakhani Nov 9, 2023
b88d113
chore: updates
zeeshanlakhani Nov 9, 2023
b233e1c
chore: updates
zeeshanlakhani Nov 9, 2023
522b42a
chore: testing
zeeshanlakhani Nov 9, 2023
476c47f
feat: Add pubsub receipt sharing notifications (#418)
bgins Nov 10, 2023
7ad88b5
refactor: Fix connection notification test (#424)
bgins Nov 11, 2023
b9cfa50
chore: additional test
zeeshanlakhani Nov 11, 2023
82f3348
fix: better usage, bin docs
zeeshanlakhani Nov 11, 2023
0616a33
chore: builds on for pr
zeeshanlakhani Nov 13, 2023
951abe6
refactor: (#429)
bgins Nov 13, 2023
9f817f2
chore: update debs for targets
zeeshanlakhani Nov 13, 2023
da344c1
chore: builds trial1
zeeshanlakhani Nov 13, 2023
11a8f88
fix: make configuration run without -c (all defaults) (#433)
Nov 14, 2023
0cd381d
refactor: static/dynamic nodeinfo and recv deadlines (#435)
Nov 14, 2023
59383e5
refactor: Add Gossipsub Message wrapper (#436)
bgins Nov 15, 2023
ce0c49f
fix: schedule + db conflict (#437)
Nov 15, 2023
0b37875
fix: remove unnecessary decode (#438)
Nov 16, 2023
032427e
chore: Remove databases after test runs (#444)
bgins Nov 17, 2023
c858c68
chore: send_async where possible (#445)
Nov 17, 2023
3168793
refactor: Refactor and split-up settings (#451)
bgins Nov 28, 2023
7c45cf5
Update websocket relay example app (#448)
bgins Nov 28, 2023
0aa6e3a
feat: add npm package to homestar runtime (#434)
hugomrdias Nov 29, 2023
f794950
chore: comments, logs, & cleanup (#456)
Nov 29, 2023
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
Prev Previous commit
Next Next commit
fix: make configuration run without -c (all defaults) (#433)
Includes:

- also, add starter functions for default .pem/settings initialization
- error handling around retry, wasms
- ups the transport timeout
Zeeshan Lakhani authored and zeeshanlakhani committed Nov 29, 2023

Verified

This commit was signed with the committer’s verified signature.
zeeshanlakhani Zeeshan Lakhani
commit 11a8f88b5a6f4ce83377ed60034357bb39c41257
10 changes: 9 additions & 1 deletion Cross.toml
Original file line number Diff line number Diff line change
@@ -6,11 +6,19 @@ passthrough = [
"RUSTFLAGS",
]

# When running `cross` with nix, do this within `nix-shell -p gcc rustup`.
#
# Then, run
#
# `cross build -p homestar-runtime --target x86_64-unknown-linux-musl`
# or
# `cross build -p homestar-runtime --target aarch64-unknown-linux-musl`

[target.x86_64-unknown-linux-musl]
image = "burntsushi/cross:x86_64-unknown-linux-musl"

[target.aarch64-unknown-linux-musl]
image = "burntsushi/cross:aarch64-unknown-linux-gnu"
image = "burntsushi/cross:aarch64-unknown-linux-musl"

[target.x86_64-apple-darwin]
image = "freeznet/x86_64-apple-darwin-cross:11.3"
4 changes: 1 addition & 3 deletions homestar-runtime/src/cli.rs
Original file line number Diff line number Diff line change
@@ -19,7 +19,6 @@ pub use error::Error;
pub(crate) mod show;
pub(crate) use show::ConsoleTable;

const DEFAULT_SETTINGS_FILE: &str = "./config/settings.toml";
const DEFAULT_DB_PATH: &str = "homestar.db";
const TMP_DIR: &str = "/tmp";
const HELP_TEMPLATE: &str = "{name} {version}
@@ -87,13 +86,12 @@ pub enum Command {
help = "Database path (SQLite) [optional]"
)]
database_url: Option<String>,
/// Runtime configuration file (.toml), defaults to ./config/settings.toml.
/// Runtime configuration file (.toml).
#[arg(
short = 'c',
long = "config",
value_hint = clap::ValueHint::FilePath,
value_name = "CONFIG",
default_value = DEFAULT_SETTINGS_FILE,
help = "Runtime configuration file (.toml) [optional]"
)]
runtime_config: Option<PathBuf>,
1 change: 1 addition & 0 deletions homestar-runtime/src/scheduler.rs
Original file line number Diff line number Diff line change
@@ -171,6 +171,7 @@ impl<'a> TaskScheduler<'a> {
.into_iter()
.map(|(_, rsc)| rsc.to_owned())
.collect();

let fetched = fetch_fn(resources_to_fetch).await?;

match resume {
112 changes: 85 additions & 27 deletions homestar-runtime/src/settings.rs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ use serde_with::{serde_as, DisplayFromStr, DurationMilliSeconds, DurationSeconds
#[cfg(feature = "ipfs")]
use std::net::Ipv4Addr;
use std::{
env,
net::{IpAddr, Ipv6Addr},
path::PathBuf,
time::Duration,
@@ -15,11 +16,17 @@ use std::{
mod pubkey_config;
pub(crate) use pubkey_config::PubkeyConfig;

#[cfg(target_os = "windows")]
const HOME_VAR: &str = "USERPROFILE";
#[cfg(not(target_os = "windows"))]
const HOME_VAR: &str = "HOME";

/// Application settings.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Settings {
#[serde(default)]
pub(crate) monitoring: Monitoring,
#[serde(default)]
pub(crate) node: Node,
}

@@ -38,6 +45,7 @@ impl Settings {
/// Monitoring settings.
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Monitoring {
/// Tokio console port.
pub console_subscriber_port: u16,
@@ -49,7 +57,8 @@ pub struct Monitoring {

/// Server settings.
#[serde_as]
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Node {
/// Network settings.
#[serde(default)]
@@ -59,11 +68,9 @@ pub struct Node {
pub(crate) db: Database,
/// Garbage collection interval.
#[serde_as(as = "DurationSeconds<u64>")]
#[serde(default = "default_gc_interval")]
pub(crate) gc_interval: Duration,
/// Shutdown timeout.
#[serde_as(as = "DurationSeconds<u64>")]
#[serde(default = "default_shutdown_timeout")]
pub(crate) shutdown_timeout: Duration,
}

@@ -246,6 +253,17 @@ impl Default for Database {
}
}

impl Default for Node {
fn default() -> Self {
Self {
gc_interval: Duration::from_secs(1800),
shutdown_timeout: Duration::from_secs(20),
network: Default::default(),
db: Default::default(),
}
}
}

impl Default for Network {
fn default() -> Self {
Self {
@@ -276,7 +294,7 @@ impl Default for Network {
rpc_max_connections: 10,
rpc_port: 3030,
rpc_server_timeout: Duration::new(120, 0),
transport_connection_timeout: Duration::new(20, 0),
transport_connection_timeout: Duration::new(60, 0),
webserver_host: Uri::from_static("127.0.0.1"),
webserver_port: 1337,
webserver_timeout: Duration::new(120, 0),
@@ -314,14 +332,6 @@ impl Network {
}
}

fn default_shutdown_timeout() -> Duration {
Duration::new(20, 0)
}

fn default_gc_interval() -> Duration {
Duration::new(1800, 0)
}

impl Settings {
/// Load settings.
///
@@ -331,34 +341,52 @@ impl Settings {
/// Use two underscores as defined by the separator below
pub fn load() -> Result<Self, ConfigError> {
#[cfg(test)]
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/settings.toml");
{
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/settings.toml");
Self::build(Some(path))
}
#[cfg(not(test))]
let path = PathBuf::from("./config/settings.toml");

Self::build(path)
Self::build(None)
}

/// Load settings from file string that must conform to a [PathBuf].
pub fn load_from_file(file: PathBuf) -> Result<Self, ConfigError> {
Self::build(file)
Self::build(Some(file))
}

fn build(path: PathBuf) -> Result<Self, ConfigError> {
let s = Config::builder()
.add_source(File::with_name(
&path
.canonicalize()
fn build(path: Option<PathBuf>) -> Result<Self, ConfigError> {
let builder = if let Some(p) = path {
Config::builder().add_source(File::with_name(
&p.canonicalize()
.map_err(|e| ConfigError::NotFound(e.to_string()))?
.as_path()
.display()
.to_string(),
))
} else {
Config::builder()
};

let s = builder
.add_source(Environment::with_prefix("HOMESTAR").separator("__"))
.build()?;
s.try_deserialize()
}
}

#[allow(dead_code)]
fn config_dir() -> PathBuf {
let config_dir =
env::var("XDG_CONFIG_HOME").map_or_else(|_| home_dir().join(".config"), PathBuf::from);
config_dir.join("homestar")
}

#[allow(dead_code)]
fn home_dir() -> PathBuf {
let home = env::var(HOME_VAR).unwrap_or_else(|_| panic!("{} not found", HOME_VAR));
PathBuf::from(home)
}

#[cfg(test)]
mod test {
use super::*;
@@ -380,7 +408,7 @@ mod test {

#[test]
fn defaults_with_modification() {
let settings = Settings::build("fixtures/settings.toml".into()).unwrap();
let settings = Settings::build(Some("fixtures/settings.toml".into())).unwrap();

let mut default_modded_settings = Node::default();
default_modded_settings.network.events_buffer_len = 1000;
@@ -396,14 +424,14 @@ mod test {
fn overriding_env() {
std::env::set_var("HOMESTAR__NODE__NETWORK__RPC_PORT", "2046");
std::env::set_var("HOMESTAR__NODE__DB__MAX_POOL_SIZE", "1");
let settings = Settings::build("fixtures/settings.toml".into()).unwrap();
let settings = Settings::build(Some("fixtures/settings.toml".into())).unwrap();
assert_eq!(settings.node.network.rpc_port, 2046);
assert_eq!(settings.node.db.max_pool_size, 1);
}

#[test]
fn import_existing_key() {
let settings = Settings::build("fixtures/settings-import-ed25519.toml".into())
let settings = Settings::build(Some("fixtures/settings-import-ed25519.toml".into()))
.expect("setting file in test fixtures");

let msg = b"foo bar";
@@ -424,7 +452,7 @@ mod test {

#[test]
fn import_secp256k1_key() {
let settings = Settings::build("fixtures/settings-import-secp256k1.toml".into())
let settings = Settings::build(Some("fixtures/settings-import-secp256k1.toml".into()))
.expect("setting file in test fixtures");

settings
@@ -437,7 +465,7 @@ mod test {

#[test]
fn seeded_secp256k1_key() {
let settings = Settings::build("fixtures/settings-random-secp256k1.toml".into())
let settings = Settings::build(Some("fixtures/settings-random-secp256k1.toml".into()))
.expect("setting file in test fixtures");

settings
@@ -447,4 +475,34 @@ mod test {
.keypair()
.expect("generate a seeded secp256k1 key");
}

#[test]
fn test_config_dir_xdg() {
env::remove_var("HOME");
env::set_var("XDG_CONFIG_HOME", "/home/user/custom_config");
assert_eq!(
config_dir(),
PathBuf::from("/home/user/custom_config/homestar")
);
env::remove_var("XDG_CONFIG_HOME");
}

#[cfg(not(target_os = "windows"))]
#[test]
fn test_config_dir() {
env::set_var("HOME", "/home/user");
env::remove_var("XDG_CONFIG_HOME");
assert_eq!(config_dir(), PathBuf::from("/home/user/.config/homestar"));
env::remove_var("HOME");
}

#[cfg(target_os = "windows")]
#[test]
fn test_config_dir() {
env::remove_var("XDG_CONFIG_HOME");
assert_eq!(
config_dir(),
PathBuf::from(format!(r"{}\.config\homestar", env!("USERPROFILE")))
);
}
}
50 changes: 36 additions & 14 deletions homestar-runtime/src/tasks/fetch.rs
Original file line number Diff line number Diff line change
@@ -29,27 +29,49 @@ impl Fetch {
) -> Result<IndexMap<Resource, Vec<u8>>> {
use futures::{stream::FuturesUnordered, TryStreamExt};
let settings = settings.as_ref();
let retries = settings.retries;
let tasks = FuturesUnordered::new();
for rsc in resources.iter() {
tracing::info!(rsc = rsc.to_string(), "Fetching resource");
let task = tryhard::retry_fn(|| async { Self::fetch(rsc.clone(), ipfs.clone()).await })
.with_config(
tryhard::RetryFutureConfig::new(settings.retries)
.exponential_backoff(settings.retry_initial_delay)
.max_delay(settings.retry_max_delay),
let task = tryhard::retry_fn(|| async {
tracing::info!(
rsc = rsc.to_string(),
"attempting to fetch resource from IPFS"
);
Self::fetch(rsc.clone(), ipfs.clone()).await
})
.retries(retries)
.exponential_backoff(settings.retry_initial_delay)
.max_delay(settings.retry_max_delay)
.on_retry(|attempts, next_delay, error| {
let err = error.to_string();
async move {
if attempts < retries {
tracing::warn!(
err = err,
attempts = attempts,
"retrying fetch after error @ {}ms",
next_delay.map(|d| d.as_millis()).unwrap_or(0)
);
} else {
tracing::warn!(err = err, attempts = attempts, "maxed out # of retries");
}
}
});
tasks.push(task);
}

tasks.try_collect::<Vec<_>>().await?.into_iter().try_fold(
IndexMap::default(),
|mut acc, res| {
let answer = res.1?;
acc.insert(res.0, answer);
tracing::info!("fetching necessary resources from IPFS");
if let Ok(vec) = tasks.try_collect::<Vec<_>>().await {
vec.into_iter()
.try_fold(IndexMap::default(), |mut acc, res| {
let answer = res.1?;
acc.insert(res.0, answer);

Ok::<_, anyhow::Error>(acc)
},
)
Ok::<_, anyhow::Error>(acc)
})
} else {
Err(anyhow::anyhow!("Failed to fetch resources from IPFS"))
}
}

/// Gather resources via URLs, leveraging an exponential backoff.
Loading