From 8b5f77f2646435ef77c32c3d9a0d6ad7e27eadac Mon Sep 17 00:00:00 2001 From: Christien Rioux Date: Tue, 9 Sep 2025 19:29:44 -0500 Subject: [PATCH] immutable config move node id and public key init to routing table --- veilid-core/examples/basic/src/main.rs | 18 +- veilid-core/src/core_context.rs | 7 +- veilid-core/src/crypto/mod.rs | 2 - .../src/network_manager/address_filter.rs | 3 +- .../bootstrap/direct_bootstrap/mod.rs | 8 +- .../bootstrap/txt_bootstrap/mod.rs | 8 +- .../src/network_manager/connection_table.rs | 1 - veilid-core/src/network_manager/mod.rs | 9 +- .../src/network_manager/native/protocol/ws.rs | 5 +- .../src/network_manager/native/tasks/mod.rs | 5 +- veilid-core/src/network_manager/send_data.rs | 17 +- veilid-core/src/network_manager/stats.rs | 2 + veilid-core/src/routing_table/mod.rs | 46 +-- .../src/routing_table/tests/fixtures.rs | 2 +- veilid-core/src/rpc_processor/mod.rs | 3 +- .../rpc_processor/rpc_validate_dial_info.rs | 3 +- .../src/storage_manager/inspect_value.rs | 35 +- veilid-core/src/storage_manager/mod.rs | 6 +- veilid-core/src/table_store/mod.rs | 34 +- veilid-core/src/tests/fixtures.rs | 2 +- veilid-core/src/veilid_api/api.rs | 5 +- veilid-core/src/veilid_api/debug.rs | 29 +- .../src/veilid_api/tests/test_types.rs | 2 + .../src/veilid_api/types/veilid_state.rs | 7 + veilid-core/src/veilid_config.rs | 16 +- .../example/integration_test/test_crypto.dart | 3 +- .../example/integration_test/test_dht.dart | 16 +- .../integration_test/test_table_db.dart | 10 +- veilid-flutter/example/pubspec.lock | 2 +- veilid-flutter/lib/veilid_config.dart | 35 +- veilid-flutter/lib/veilid_config.freezed.dart | 353 ++---------------- veilid-flutter/lib/veilid_config.g.dart | 22 -- veilid-flutter/lib/veilid_state.dart | 61 +-- veilid-flutter/lib/veilid_state.freezed.dart | 56 +-- veilid-flutter/lib/veilid_state.g.dart | 6 +- veilid-python/tests/test_basic.py | 10 +- veilid-python/uv.lock | 2 +- veilid-python/veilid/schema/RecvMessage.json | 10 +- veilid-python/veilid/state.py | 26 +- 39 files changed, 313 insertions(+), 574 deletions(-) diff --git a/veilid-core/examples/basic/src/main.rs b/veilid-core/examples/basic/src/main.rs index 513f4ecb..53297430 100644 --- a/veilid-core/examples/basic/src/main.rs +++ b/veilid-core/examples/basic/src/main.rs @@ -12,7 +12,12 @@ async fn main() { } Network(msg) => { println!( - "Network: Peers {:}, bytes/sec [{} up] [{} down]", + "Network: Node Ids: {}, Peers {}, bytes/sec [{} up] [{} down]", + if msg.node_ids.is_empty() { + "(none assigned)".to_string() + } else { + msg.node_ids.iter().map(|x| x.to_string()).collect::>().join(",") + }, msg.peers.len(), msg.bps_up, msg.bps_down @@ -58,21 +63,12 @@ async fn main() { let veilid = veilid_core::api_startup(update_callback, config) .await .unwrap(); - println!( - "Node ID: {}", - veilid - .config() - .unwrap() - .config() - .network - .routing_table - .public_keys - ); // Attach to the network veilid.attach().await.unwrap(); // Until CTRL+C is pressed, keep running tokio::signal::ctrl_c().await.unwrap(); + veilid.shutdown().await; } diff --git a/veilid-core/src/core_context.rs b/veilid-core/src/core_context.rs index 2c7d1fc9..e99e5457 100644 --- a/veilid-core/src/core_context.rs +++ b/veilid-core/src/core_context.rs @@ -30,12 +30,15 @@ impl VeilidCoreContext { config: VeilidConfig, ) -> VeilidAPIResult { // Set up config from json - let config = VeilidStartupOptions::new_from_config(config, update_callback); + let config = VeilidStartupOptions::try_new(config, update_callback)?; + Self::new_common(config).await } #[instrument(level = "trace", target = "core_context", err, skip_all)] - async fn new_common(startup_options: VeilidStartupOptions) -> VeilidAPIResult { + async fn new_common( + startup_options: VeilidStartupOptions, + ) -> VeilidAPIResult { cfg_if! { if #[cfg(target_os = "android")] { if !crate::intf::android::is_android_ready() { diff --git a/veilid-core/src/crypto/mod.rs b/veilid-core/src/crypto/mod.rs index d4c4c03a..c9dbfd37 100644 --- a/veilid-core/src/crypto/mod.rs +++ b/veilid-core/src/crypto/mod.rs @@ -119,7 +119,6 @@ impl Crypto { // Setup called by table store after it get initialized #[instrument(level = "trace", target = "crypto", skip_all, err)] pub(crate) async fn table_store_setup(&self, table_store: &TableStore) -> EyreResult<()> { - // load caches if they are valid for this node id let caches_valid = { let db = table_store @@ -357,5 +356,4 @@ impl Crypto { } Ok(()) } - } diff --git a/veilid-core/src/network_manager/address_filter.rs b/veilid-core/src/network_manager/address_filter.rs index 79a7ed91..b8baf7e9 100644 --- a/veilid-core/src/network_manager/address_filter.rs +++ b/veilid-core/src/network_manager/address_filter.rs @@ -93,7 +93,8 @@ impl AddressFilter { max_connections_per_ip6_prefix: config.network.max_connections_per_ip6_prefix as usize, max_connections_per_ip6_prefix_size: config.network.max_connections_per_ip6_prefix_size as usize, - max_connection_frequency_per_min: config.network.max_connection_frequency_per_min as usize, + max_connection_frequency_per_min: config.network.max_connection_frequency_per_min + as usize, punishment_duration_min: PUNISHMENT_DURATION_MIN, dial_info_failure_duration_min: DIAL_INFO_FAILURE_DURATION_MIN, } diff --git a/veilid-core/src/network_manager/bootstrap/direct_bootstrap/mod.rs b/veilid-core/src/network_manager/bootstrap/direct_bootstrap/mod.rs index 4471f30c..7f45bde9 100644 --- a/veilid-core/src/network_manager/bootstrap/direct_bootstrap/mod.rs +++ b/veilid-core/src/network_manager/bootstrap/direct_bootstrap/mod.rs @@ -12,7 +12,13 @@ impl NetworkManager { /// If no bootstrap keys are specified, uses the v0 mechanism, otherwise uses the v1 mechanism #[instrument(level = "trace", target = "net", err, skip(self))] pub async fn direct_bootstrap(&self, dial_info: DialInfo) -> EyreResult>> { - let direct_boot_version = if self.config().network.routing_table.bootstrap_keys.is_empty() { + let direct_boot_version = if self + .config() + .network + .routing_table + .bootstrap_keys + .is_empty() + { 0 } else { 1 diff --git a/veilid-core/src/network_manager/bootstrap/txt_bootstrap/mod.rs b/veilid-core/src/network_manager/bootstrap/txt_bootstrap/mod.rs index 8b7faf2d..3d77e2aa 100644 --- a/veilid-core/src/network_manager/bootstrap/txt_bootstrap/mod.rs +++ b/veilid-core/src/network_manager/bootstrap/txt_bootstrap/mod.rs @@ -19,7 +19,13 @@ impl NetworkManager { // Get the minimum bootstrap version we are supporting // If no keys are available, allow v0. // If bootstrap keys are specified, require at least v1. - let min_boot_version = if self.config().network.routing_table.bootstrap_keys.is_empty() { + let min_boot_version = if self + .config() + .network + .routing_table + .bootstrap_keys + .is_empty() + { BOOTSTRAP_TXT_VERSION_0 } else { BOOTSTRAP_TXT_VERSION_1 diff --git a/veilid-core/src/network_manager/connection_table.rs b/veilid-core/src/network_manager/connection_table.rs index d72253c6..a9ccc070 100644 --- a/veilid-core/src/network_manager/connection_table.rs +++ b/veilid-core/src/network_manager/connection_table.rs @@ -61,7 +61,6 @@ impl ConnectionTable { pub fn new(registry: VeilidComponentRegistry) -> Self { let config = registry.config(); let max_connections = { - let mut max_connections = BTreeMap::::new(); max_connections.insert( diff --git a/veilid-core/src/network_manager/mod.rs b/veilid-core/src/network_manager/mod.rs index 389a6bda..8f962376 100644 --- a/veilid-core/src/network_manager/mod.rs +++ b/veilid-core/src/network_manager/mod.rs @@ -1092,12 +1092,14 @@ impl NetworkManager { // Get timestamp range let config = self.config(); - let tsbehind =config.network + let tsbehind = config + .network .rpc .max_timestamp_behind_ms .map(ms_to_us) .map(TimestampDuration::new); - let tsahead = config.network + let tsahead = config + .network .rpc .max_timestamp_ahead_ms .map(ms_to_us) @@ -1170,8 +1172,7 @@ impl NetworkManager { // which only performs a lightweight lookup before passing the packet back out // If our node has the relay capability disabled, we should not be asked to relay - if self.config().capabilities.disable.contains(&CAP_RELAY) - { + if self.config().capabilities.disable.contains(&CAP_RELAY) { veilid_log!(self debug "node has relay capability disabled, dropping relayed envelope from {} to {}", sender_id, recipient_id); return Ok(false); } diff --git a/veilid-core/src/network_manager/native/protocol/ws.rs b/veilid-core/src/network_manager/native/protocol/ws.rs index 62b6d1af..b319993a 100644 --- a/veilid-core/src/network_manager/native/protocol/ws.rs +++ b/veilid-core/src/network_manager/native/protocol/ws.rs @@ -200,7 +200,10 @@ impl WebsocketProtocolHandler { } } } else { - format!("GET /{}", config.network.protocol.ws.path.trim_end_matches('/')) + format!( + "GET /{}", + config.network.protocol.ws.path.trim_end_matches('/') + ) }; let connection_initial_timeout_ms = if tls { config.network.tls.connection_initial_timeout_ms diff --git a/veilid-core/src/network_manager/native/tasks/mod.rs b/veilid-core/src/network_manager/native/tasks/mod.rs index 515e4fcf..43b24222 100644 --- a/veilid-core/src/network_manager/native/tasks/mod.rs +++ b/veilid-core/src/network_manager/native/tasks/mod.rs @@ -101,7 +101,10 @@ impl Network { let (upnp, require_inbound_relay) = { let config = self.config(); - (config.network.upnp, config.network.privacy.require_inbound_relay) + ( + config.network.upnp, + config.network.privacy.require_inbound_relay, + ) }; if require_inbound_relay { diff --git a/veilid-core/src/network_manager/send_data.rs b/veilid-core/src/network_manager/send_data.rs index b58740db..9b7eee31 100644 --- a/veilid-core/src/network_manager/send_data.rs +++ b/veilid-core/src/network_manager/send_data.rs @@ -393,9 +393,10 @@ impl NetworkManager { }; let config = self.config(); - let excessive_reverse_connect_duration_us = (config.network.connection_initial_timeout_ms * 2 - + config.network.reverse_connection_receipt_time_ms) as u64 - * 1000; + let excessive_reverse_connect_duration_us = + (config.network.connection_initial_timeout_ms * 2 + + config.network.reverse_connection_receipt_time_ms) as u64 + * 1000; let unique_flow = network_result_try!( pin_future!(debug_duration( @@ -447,7 +448,8 @@ impl NetworkManager { data }; - let hole_punch_receipt_time_us = self.config().network.hole_punch_receipt_time_ms as u64 * 1000; + let hole_punch_receipt_time_us = + self.config().network.hole_punch_receipt_time_ms as u64 * 1000; let unique_flow = network_result_try!( pin_future!(debug_duration( @@ -808,7 +810,9 @@ impl NetworkManager { }; // Build a return receipt for the signal - let receipt_timeout = TimestampDuration::new_ms(self.config().network.reverse_connection_receipt_time_ms as u64); + let receipt_timeout = TimestampDuration::new_ms( + self.config().network.reverse_connection_receipt_time_ms as u64, + ); let (receipt, eventual_value) = self.generate_single_shot_receipt(receipt_timeout, [])?; // Get target routing domain @@ -920,7 +924,8 @@ impl NetworkManager { ); // Build a return receipt for the signal - let receipt_timeout = TimestampDuration::new_ms(self.config().network.hole_punch_receipt_time_ms as u64); + let receipt_timeout = + TimestampDuration::new_ms(self.config().network.hole_punch_receipt_time_ms as u64); let (receipt, eventual_value) = self.generate_single_shot_receipt(receipt_timeout, [])?; // Get target routing domain diff --git a/veilid-core/src/network_manager/stats.rs b/veilid-core/src/network_manager/stats.rs index 4a36c5f3..ce8c6bb2 100644 --- a/veilid-core/src/network_manager/stats.rs +++ b/veilid-core/src/network_manager/stats.rs @@ -105,6 +105,7 @@ impl NetworkManager { bps_down: 0.into(), bps_up: 0.into(), peers: Vec::new(), + node_ids: Vec::new(), }); } let routing_table = self.routing_table(); @@ -136,6 +137,7 @@ impl NetworkManager { } out }, + node_ids: routing_table.node_ids().to_vec(), }) } diff --git a/veilid-core/src/routing_table/mod.rs b/veilid-core/src/routing_table/mod.rs index 7ac13f2d..0a1f5218 100644 --- a/veilid-core/src/routing_table/mod.rs +++ b/veilid-core/src/routing_table/mod.rs @@ -253,17 +253,8 @@ impl RoutingTable { async fn init_async(&self) -> EyreResult<()> { veilid_log!(self debug "starting routing table init"); - // Set up node ids - { - let mut node_ids = NodeIdGroup::new(); - for pk in self.public_keys().iter() { - let node_id = self - .generate_node_id(pk) - .wrap_err("unable to generate node id for public key")?; - node_ids.add(node_id); - } - *self.node_ids.write() = node_ids; - } + // Set up initial keys and node ids + self.setup_public_keys().await?; // Set up routing buckets { @@ -433,9 +424,9 @@ impl RoutingTable { async fn setup_public_key( &self, vcrypto: AsyncCryptoSystemGuard<'_>, - table_store: &TableStore, ) -> VeilidAPIResult<(PublicKey, SecretKey)> { let config = self.config(); + let table_store = self.table_store(); let ck = vcrypto.kind(); let mut public_key = config.network.routing_table.public_keys.get(ck); let mut secret_key = config.network.routing_table.secret_keys.get(ck); @@ -501,7 +492,7 @@ impl RoutingTable { } } - // If we have a node id from storage, check it + // If we have a public key from storage, check it let (public_key, secret_key) = if let (Some(public_key), Some(secret_key)) = (public_key, secret_key) { // Validate node id @@ -518,9 +509,7 @@ impl RoutingTable { vcrypto.generate_keypair().await.into_split() }; - veilid_log!(self info "Public Key: {}", public_key); - - // Save the node id / secret in storage + // Save the public key + secret in storage config_table .store_json(0, table_key_public_key.as_bytes(), &public_key) .await?; @@ -533,7 +522,7 @@ impl RoutingTable { /// Get the public keys from config if one is specified #[cfg_attr(test, allow(unused_variables))] - async fn setup_public_keys(&self, table_store: &TableStore) -> VeilidAPIResult<()> { + async fn setup_public_keys(&self) -> VeilidAPIResult<()> { let crypto = self.crypto(); let mut out_public_keys = PublicKeyGroup::new(); @@ -547,15 +536,29 @@ impl RoutingTable { #[cfg(test)] let (public_key, secret_key) = vcrypto.generate_keypair().await.into_split(); #[cfg(not(test))] - let (public_key, secret_key) = self.setup_public_key(vcrypto, table_store).await?; + let (public_key, secret_key) = self.setup_public_key(vcrypto).await?; // Save for config out_public_keys.add(public_key); out_secret_keys.add(secret_key); } - *(self.public_keys.write()) = out_public_keys; - *(self.secret_keys.write()) = out_secret_keys; + veilid_log!(self info "Public Keys: {}", out_public_keys); + + *self.public_keys.write() = out_public_keys; + *self.secret_keys.write() = out_secret_keys; + + // Set up node ids + let mut node_ids = NodeIdGroup::new(); + for pk in self.public_keys().iter() { + let node_id = self + .generate_node_id(pk)?; + node_ids.add(node_id); + } + + veilid_log!(self info "Node Ids: {}", node_ids); + + *self.node_ids.write() = node_ids; Ok(()) } @@ -688,7 +691,8 @@ impl RoutingTable { cache_validity_key.extend_from_slice(b.as_bytes()); } cache_validity_key.extend_from_slice( - config.network + config + .network .network_key_password .clone() .unwrap_or_default() diff --git a/veilid-core/src/routing_table/tests/fixtures.rs b/veilid-core/src/routing_table/tests/fixtures.rs index c7ba9074..360160c1 100644 --- a/veilid-core/src/routing_table/tests/fixtures.rs +++ b/veilid-core/src/routing_table/tests/fixtures.rs @@ -11,7 +11,7 @@ pub mod mock_registry { pub async fn init>(namespace: S) -> VeilidComponentRegistry { let (update_callback, config) = setup_veilid_core_with_namespace(namespace); - let startup_options = VeilidStartupOptions::new_from_config(config, update_callback); + let startup_options = VeilidStartupOptions::try_new(config, update_callback).unwrap(); let registry = VeilidComponentRegistry::new(startup_options); registry.enable_mock(); registry.register(ProtectedStore::new); diff --git a/veilid-core/src/rpc_processor/mod.rs b/veilid-core/src/rpc_processor/mod.rs index bbdf9b5e..7eedad24 100644 --- a/veilid-core/src/rpc_processor/mod.rs +++ b/veilid-core/src/rpc_processor/mod.rs @@ -473,7 +473,8 @@ impl RPCProcessor { let node_count = config.network.dht.max_find_node_count as usize; let _consensus_count = config.network.dht.resolve_node_count as usize; let fanout = config.network.dht.resolve_node_fanout as usize; - let timeout = TimestampDuration::from(ms_to_us(config.network.dht.resolve_node_timeout_ms)); + let timeout = + TimestampDuration::from(ms_to_us(config.network.dht.resolve_node_timeout_ms)); // Search routing domains for peer // xxx: Eventually add other routing domains here diff --git a/veilid-core/src/rpc_processor/rpc_validate_dial_info.rs b/veilid-core/src/rpc_processor/rpc_validate_dial_info.rs index 49ad9ce5..8e663ebb 100644 --- a/veilid-core/src/rpc_processor/rpc_validate_dial_info.rs +++ b/veilid-core/src/rpc_processor/rpc_validate_dial_info.rs @@ -25,7 +25,8 @@ impl RPCProcessor { let network_manager = self.network_manager(); - let validate_dial_info_receipt_time_ms = self.config().network.dht.validate_dial_info_receipt_time_ms as u64; + let validate_dial_info_receipt_time_ms = + self.config().network.dht.validate_dial_info_receipt_time_ms as u64; let receipt_time = TimestampDuration::new_ms(validate_dial_info_receipt_time_ms); diff --git a/veilid-core/src/storage_manager/inspect_value.rs b/veilid-core/src/storage_manager/inspect_value.rs index f36cb171..5c5f5ea3 100644 --- a/veilid-core/src/storage_manager/inspect_value.rs +++ b/veilid-core/src/storage_manager/inspect_value.rs @@ -68,24 +68,23 @@ impl StorageManager { // Get the DHT parameters for 'InspectValue' // Can use either 'get scope' or 'set scope' depending on the purpose of the inspection - let (key_count, consensus_count, fanout, timeout_us) = - if use_set_scope { - let config = self.config(); - ( - config.network.dht.max_find_node_count as usize, - config.network.dht.set_value_count as usize, - config.network.dht.set_value_fanout as usize, - TimestampDuration::from(ms_to_us(config.network.dht.set_value_timeout_ms)), - ) - } else { - let config = self.config(); - ( - config.network.dht.max_find_node_count as usize, - config.network.dht.get_value_count as usize, - config.network.dht.get_value_fanout as usize, - TimestampDuration::from(ms_to_us(config.network.dht.get_value_timeout_ms)), - ) - }; + let (key_count, consensus_count, fanout, timeout_us) = if use_set_scope { + let config = self.config(); + ( + config.network.dht.max_find_node_count as usize, + config.network.dht.set_value_count as usize, + config.network.dht.set_value_fanout as usize, + TimestampDuration::from(ms_to_us(config.network.dht.set_value_timeout_ms)), + ) + } else { + let config = self.config(); + ( + config.network.dht.max_find_node_count as usize, + config.network.dht.get_value_count as usize, + config.network.dht.get_value_fanout as usize, + TimestampDuration::from(ms_to_us(config.network.dht.get_value_timeout_ms)), + ) + }; // Get the nodes we know are caching this value to seed the fanout let init_fanout_queue = { diff --git a/veilid-core/src/storage_manager/mod.rs b/veilid-core/src/storage_manager/mod.rs index e08d2cc1..151fbb7d 100644 --- a/veilid-core/src/storage_manager/mod.rs +++ b/veilid-core/src/storage_manager/mod.rs @@ -1248,7 +1248,8 @@ impl StorageManager { None } else { // Get the minimum expiration timestamp we will accept - let rpc_timeout_us = TimestampDuration::from(ms_to_us(self.config().network.rpc.timeout_ms)); + let rpc_timeout_us = + TimestampDuration::from(ms_to_us(self.config().network.rpc.timeout_ms)); let cur_ts = get_timestamp(); let min_expiration_ts = Timestamp::new(cur_ts + rpc_timeout_us.as_u64()); let expiration_ts = if expiration.as_u64() == 0 { @@ -1563,8 +1564,7 @@ impl StorageManager { } } FanoutResultKind::Exhausted => { - let get_consensus = self - .config().network.dht.get_value_count as usize; + let get_consensus = self.config().network.dht.get_value_count as usize; let value_node_count = fanout_result.consensus_nodes.len(); if value_node_count < get_consensus { veilid_log!(self debug "exhausted with insufficient consensus ({}<{}), adding offline subkey: {}:{}", diff --git a/veilid-core/src/table_store/mod.rs b/veilid-core/src/table_store/mod.rs index 2ca0e6e5..69ac0182 100644 --- a/veilid-core/src/table_store/mod.rs +++ b/veilid-core/src/table_store/mod.rs @@ -97,7 +97,7 @@ pub struct TableStore { registry: VeilidComponentRegistry, inner: Mutex, // Sync mutex here because TableDB drops can happen at any time table_store_driver: TableStoreDriver, - async_lock: Arc>, // Async mutex for operations + async_lock: Arc>, } impl fmt::Debug for TableStore { @@ -373,7 +373,11 @@ impl TableStore { }; // Get device encryption key protection password if we have it - let device_encryption_key_password = self.config().protected_store.device_encryption_key_password.clone(); + let device_encryption_key_password = self + .config() + .protected_store + .device_encryption_key_password + .clone(); Ok(Some( self.maybe_unprotect_device_encryption_key(&dek_bytes, &device_encryption_key_password) @@ -396,23 +400,23 @@ impl TableStore { }; // Get new device encryption key protection password if we are changing it - let new_device_encryption_key_password = self.config().protected_store.new_device_encryption_key_password.clone(); + let new_device_encryption_key_password = self + .config() + .protected_store + .new_device_encryption_key_password + .clone(); let device_encryption_key_password = if let Some(new_device_encryption_key_password) = new_device_encryption_key_password { // Change password veilid_log!(self debug "changing dek password"); - self.config() - .try_with_mut(|c| { - c.protected_store - .device_encryption_key_password - .clone_from(&new_device_encryption_key_password); - Ok(new_device_encryption_key_password) - }) - .unwrap() + new_device_encryption_key_password } else { // Get device encryption key protection password if we have it veilid_log!(self debug "saving with existing dek password"); - self.config().protected_store.device_encryption_key_password.clone() + self.config() + .protected_store + .device_encryption_key_password + .clone() }; let dek_bytes = self @@ -456,7 +460,11 @@ impl TableStore { } // Check for password change - let changing_password = self.config().protected_store.new_device_encryption_key_password.is_some(); + let changing_password = self + .config() + .protected_store + .new_device_encryption_key_password + .is_some(); // Save encryption key if it has changed or if the protecting password wants to change if device_encryption_key_changed || changing_password { diff --git a/veilid-core/src/tests/fixtures.rs b/veilid-core/src/tests/fixtures.rs index 07375396..0d99ef73 100644 --- a/veilid-core/src/tests/fixtures.rs +++ b/veilid-core/src/tests/fixtures.rs @@ -315,7 +315,7 @@ pub fn fix_fake_veilid_config() -> VeilidConfig { } pub fn get_startup_options() -> VeilidStartupOptions { - VeilidStartupOptions::new_from_config(get_config(), Arc::new(update_callback)) + VeilidStartupOptions::try_new(get_config(), Arc::new(update_callback)).unwrap() } pub fn get_config() -> VeilidConfig { diff --git a/veilid-core/src/veilid_api/api.rs b/veilid-core/src/veilid_api/api.rs index 93f25881..5faf91d8 100644 --- a/veilid-core/src/veilid_api/api.rs +++ b/veilid-core/src/veilid_api/api.rs @@ -179,7 +179,7 @@ impl VeilidAPI { network, config: Box::new(VeilidStateConfig { config: config.as_ref().clone(), - }) + }), }) } @@ -280,7 +280,8 @@ impl VeilidAPI { Crypto::validate_crypto_kind(*kind)?; } - let default_route_hop_count: usize = self.config()?.network.rpc.default_route_hop_count.into(); + let default_route_hop_count: usize = + self.config()?.network.rpc.default_route_hop_count.into(); let safety_spec = SafetySpec { preferred_route: None, diff --git a/veilid-core/src/veilid_api/debug.rs b/veilid-core/src/veilid_api/debug.rs index 8a5c0e98..62cdfadd 100644 --- a/veilid-core/src/veilid_api/debug.rs +++ b/veilid-core/src/veilid_api/debug.rs @@ -173,7 +173,8 @@ fn get_safety_selection( registry: VeilidComponentRegistry, ) -> impl Fn(&str) -> Option { move |text| { - let default_route_hop_count = registry.config().network.rpc.default_route_hop_count as usize; + let default_route_hop_count = + registry.config().network.rpc.default_route_hop_count as usize; if !text.is_empty() && &text[0..1] == "-" { // Unsafe @@ -825,6 +826,7 @@ impl VeilidAPI { Ok(nodeid) } + #[expect(clippy::unused_async)] async fn debug_config(&self, args: String) -> VeilidAPIResult { let mut args = args.as_str(); let mut config = self.config()?; @@ -842,25 +844,11 @@ impl VeilidAPI { let rest = rest.trim_start().to_owned(); // One argument is 'config get' - if rest.is_empty() { - return config.get_key_json(arg, true); + if !rest.is_empty() { + apibail_internal!("too many arguments"); } - Ok("xxx: Can not change config".to_owned()) - - // More than one argument is 'config set' - - // // Must be detached - // if !matches!( - // self.get_state().await?.attachment.state, - // AttachmentState::Detached - // ) { - // apibail_internal!("Must be detached to change config"); - // } - - // // Change the config key - // //self.with_edit_config(|c| c.set_key_json(arg, &rest))?; - // Ok("Config value set".to_owned()) + config.get_key_json(arg, true) } async fn debug_network(&self, args: String) -> VeilidAPIResult { @@ -2046,9 +2034,8 @@ impl VeilidAPI { .add_rehydration_request( key.opaque(), subkeys.unwrap_or_default(), - consensus_count.unwrap_or_else(|| - registry.config().network.dht.set_value_count as usize - ), + consensus_count + .unwrap_or_else(|| registry.config().network.dht.set_value_count as usize), ) .await; diff --git a/veilid-core/src/veilid_api/tests/test_types.rs b/veilid-core/src/veilid_api/tests/test_types.rs index e0ce87f6..9b07db3f 100644 --- a/veilid-core/src/veilid_api/tests/test_types.rs +++ b/veilid-core/src/veilid_api/tests/test_types.rs @@ -236,6 +236,7 @@ pub fn test_veilidstatenetwork() { bps_down: ByteCount::from(14_400), bps_up: ByteCount::from(1200), peers: vec![fix_peertabledata()], + node_ids: vec![fix_fake_node_id()], }; let copy = deserialize_json(&serialize_json(&orig)).unwrap(); @@ -289,6 +290,7 @@ pub fn test_veilidstate() { bps_down: ByteCount::from(14_400), bps_up: ByteCount::from(1200), peers: vec![fix_peertabledata()], + node_ids: vec![fix_fake_node_id()], }), config: Box::new(VeilidStateConfig { config: fix_fake_veilid_config(), diff --git a/veilid-core/src/veilid_api/types/veilid_state.rs b/veilid-core/src/veilid_api/types/veilid_state.rs index ae2cb890..350b9f16 100644 --- a/veilid-core/src/veilid_api/types/veilid_state.rs +++ b/veilid-core/src/veilid_api/types/veilid_state.rs @@ -128,6 +128,13 @@ pub struct VeilidStateNetwork { /// The list of most recently accessed peers. /// This is not an active connection table, nor is representative of the entire routing table. pub peers: Vec, + /// The list of node ids for this node + #[schemars(with = "Vec")] + #[cfg_attr( + all(target_arch = "wasm32", target_os = "unknown"), + tsify(type = "string[]") + )] + pub node_ids: Vec, } /// Describe a private route change that has happened diff --git a/veilid-core/src/veilid_config.rs b/veilid-core/src/veilid_config.rs index 8ddeabfb..7e4b04ce 100644 --- a/veilid-core/src/veilid_config.rs +++ b/veilid-core/src/veilid_config.rs @@ -955,6 +955,7 @@ impl VeilidConfig { out } + #[must_use] pub fn safe(&self) -> Arc { let mut safe_cfg = self.clone(); @@ -967,7 +968,6 @@ impl VeilidConfig { } pub fn get_key_json(&self, key: &str, pretty: bool) -> VeilidAPIResult { - // Generate json from whole config let jc = serde_json::to_string(self).map_err(VeilidAPIError::generic)?; let jvc = json::parse(&jc).map_err(VeilidAPIError::generic)?; @@ -1030,7 +1030,7 @@ impl VeilidConfig { Ok(()) } - fn validate(&self) -> VeilidAPIResult<()> { + pub fn validate(&self) -> VeilidAPIResult<()> { Self::validate_program_name(&self.program_name)?; Self::validate_namespace(&self.namespace)?; @@ -1137,11 +1137,16 @@ impl fmt::Debug for VeilidStartupOptions { } impl VeilidStartupOptions { - pub(crate) fn new_from_config(config: VeilidConfig, update_cb: UpdateCallback) -> Self { - Self { + pub(crate) fn try_new( + config: VeilidConfig, + update_cb: UpdateCallback, + ) -> VeilidAPIResult { + config.validate()?; + + Ok(Self { update_cb, config: Arc::new(config), - } + }) } #[must_use] @@ -1149,6 +1154,7 @@ impl VeilidStartupOptions { self.update_cb.clone() } + #[must_use] pub fn config(&self) -> Arc { self.config.clone() } diff --git a/veilid-flutter/example/integration_test/test_crypto.dart b/veilid-flutter/example/integration_test/test_crypto.dart index 96bf6cd1..86aed32a 100644 --- a/veilid-flutter/example/integration_test/test_crypto.dart +++ b/veilid-flutter/example/integration_test/test_crypto.dart @@ -16,8 +16,7 @@ Future testGetCryptoSystems() async { const CryptoKind invalidCryptoKind = cryptoKindNONE + 1; Future testGetCryptoSystemInvalid() async { - await expectLater( - () async => Veilid.instance.getCryptoSystem(invalidCryptoKind), + await expectLater(() => Veilid.instance.getCryptoSystem(invalidCryptoKind), throwsA(isA())); } diff --git a/veilid-flutter/example/integration_test/test_dht.dart b/veilid-flutter/example/integration_test/test_dht.dart index 70a3d548..be8746fc 100644 --- a/veilid-flutter/example/integration_test/test_dht.dart +++ b/veilid-flutter/example/integration_test/test_dht.dart @@ -10,8 +10,8 @@ final bogusKey = Future testGetDHTValueUnopened() async { final rc = await Veilid.instance.routingContext(); try { - await expectLater(() async => rc.getDHTValue(bogusKey, 0), - throwsA(isA())); + await expectLater( + () => rc.getDHTValue(bogusKey, 0), throwsA(isA())); } finally { rc.close(); } @@ -20,8 +20,8 @@ Future testGetDHTValueUnopened() async { Future testOpenDHTRecordNonexistentNoWriter() async { final rc = await Veilid.instance.routingContext(); try { - await expectLater(() async => rc.openDHTRecord(bogusKey), - throwsA(isA())); + await expectLater( + () => rc.openDHTRecord(bogusKey), throwsA(isA())); } finally { rc.close(); } @@ -30,8 +30,8 @@ Future testOpenDHTRecordNonexistentNoWriter() async { Future testCloseDHTRecordNonexistent() async { final rc = await Veilid.instance.routingContext(); try { - await expectLater(() async => rc.closeDHTRecord(bogusKey), - throwsA(isA())); + await expectLater( + () => rc.closeDHTRecord(bogusKey), throwsA(isA())); } finally { rc.close(); } @@ -40,8 +40,8 @@ Future testCloseDHTRecordNonexistent() async { Future testDeleteDHTRecordNonexistent() async { final rc = await Veilid.instance.routingContext(); try { - await expectLater(() async => rc.deleteDHTRecord(bogusKey), - throwsA(isA())); + await expectLater( + () => rc.deleteDHTRecord(bogusKey), throwsA(isA())); } finally { rc.close(); } diff --git a/veilid-flutter/example/integration_test/test_table_db.dart b/veilid-flutter/example/integration_test/test_table_db.dart index 674a7b9a..879f0a20 100644 --- a/veilid-flutter/example/integration_test/test_table_db.dart +++ b/veilid-flutter/example/integration_test/test_table_db.dart @@ -16,7 +16,7 @@ Future testOpenDeleteTableDb() async { final tdb = await Veilid.instance.openTableDB(testDb, 1); try { - await expectLater(() async => Veilid.instance.deleteTableDB(testDb), + await expectLater(() => Veilid.instance.deleteTableDB(testDb), throwsA(isA())); } finally { tdb.close(); @@ -32,11 +32,11 @@ Future testOpenTwiceTableDb() async { final tdb2 = await Veilid.instance.openTableDB(testDb, 1); // delete should fail because open - await expectLater(() async => Veilid.instance.deleteTableDB(testDb), + await expectLater(() => Veilid.instance.deleteTableDB(testDb), throwsA(isA())); tdb.close(); // delete should fail because open - await expectLater(() async => Veilid.instance.deleteTableDB(testDb), + await expectLater(() => Veilid.instance.deleteTableDB(testDb), throwsA(isA())); tdb2.close(); @@ -100,7 +100,7 @@ Future testResizeTableDb() async { final tdb = await Veilid.instance.openTableDB(testDb, 1); try { // reopen the db with more columns should fail if it is already open - await expectLater(() async => Veilid.instance.openTableDB(testDb, 2), + await expectLater(() => Veilid.instance.openTableDB(testDb, 2), throwsA(isA())); } finally { tdb.close(); @@ -115,7 +115,7 @@ Future testResizeTableDb() async { final tdb3 = await Veilid.instance.openTableDB(testDb, 1); try { // Should fail access to second column - await expectLater(() async => tdb3.load(1, utf8.encode('qwer')), + await expectLater(() => tdb3.load(1, utf8.encode('qwer')), throwsA(isA())); // Should succeed with access to second column diff --git a/veilid-flutter/example/pubspec.lock b/veilid-flutter/example/pubspec.lock index 593c06fc..9d5bff03 100644 --- a/veilid-flutter/example/pubspec.lock +++ b/veilid-flutter/example/pubspec.lock @@ -634,7 +634,7 @@ packages: path: ".." relative: true source: path - version: "0.4.7" + version: "0.4.8" veilid_test: dependency: "direct dev" description: diff --git a/veilid-flutter/lib/veilid_config.dart b/veilid-flutter/lib/veilid_config.dart index 05672888..82117951 100644 --- a/veilid-flutter/lib/veilid_config.dart +++ b/veilid-flutter/lib/veilid_config.dart @@ -195,23 +195,23 @@ sealed class VeilidConfigWS with _$VeilidConfigWS { } //////////// -@Deprecated('WSS is disabled by default in veilid-flutter') -@freezed -sealed class VeilidConfigWSS with _$VeilidConfigWSS { - @Deprecated('WSS is disabled by default in veilid-flutter') - const factory VeilidConfigWSS({ - required bool connect, - required bool listen, - required int maxConnections, - required String listenAddress, - required String path, - String? url, - }) = _VeilidConfigWSS; +// @Deprecated('WSS is disabled by default in veilid-flutter') +// @freezed +// sealed class VeilidConfigWSS with _$VeilidConfigWSS { +// @Deprecated('WSS is disabled by default in veilid-flutter') +// const factory VeilidConfigWSS({ +// required bool connect, +// required bool listen, +// required int maxConnections, +// required String listenAddress, +// required String path, +// String? url, +// }) = _VeilidConfigWSS; - @Deprecated('WSS is disabled by default in veilid-flutter') - factory VeilidConfigWSS.fromJson(dynamic json) => - _$VeilidConfigWSSFromJson(json as Map); -} +// @Deprecated('WSS is disabled by default in veilid-flutter') +// factory VeilidConfigWSS.fromJson(dynamic json) => +// _$VeilidConfigWSSFromJson(json as Map); +// } //////////// @@ -221,8 +221,7 @@ sealed class VeilidConfigProtocol with _$VeilidConfigProtocol { required VeilidConfigUDP udp, required VeilidConfigTCP tcp, required VeilidConfigWS ws, - @Deprecated('WSS is disabled by default in veilid-flutter') - required VeilidConfigWSS wss, + // required VeilidConfigWSS wss, }) = _VeilidConfigProtocol; factory VeilidConfigProtocol.fromJson(dynamic json) => diff --git a/veilid-flutter/lib/veilid_config.freezed.dart b/veilid-flutter/lib/veilid_config.freezed.dart index 6e710a7f..f9b736d9 100644 --- a/veilid-flutter/lib/veilid_config.freezed.dart +++ b/veilid-flutter/lib/veilid_config.freezed.dart @@ -3776,294 +3776,10 @@ as String?, } -/// @nodoc -mixin _$VeilidConfigWSS implements DiagnosticableTreeMixin { - - bool get connect; bool get listen; int get maxConnections; String get listenAddress; String get path; String? get url; -/// Create a copy of VeilidConfigWSS -/// with the given fields replaced by the non-null parameter values. -@JsonKey(includeFromJson: false, includeToJson: false) -@pragma('vm:prefer-inline') -$VeilidConfigWSSCopyWith get copyWith => _$VeilidConfigWSSCopyWithImpl(this as VeilidConfigWSS, _$identity); - - /// Serializes this VeilidConfigWSS to a JSON map. - Map toJson(); - -@override -void debugFillProperties(DiagnosticPropertiesBuilder properties) { - properties - ..add(DiagnosticsProperty('type', 'VeilidConfigWSS')) - ..add(DiagnosticsProperty('connect', connect))..add(DiagnosticsProperty('listen', listen))..add(DiagnosticsProperty('maxConnections', maxConnections))..add(DiagnosticsProperty('listenAddress', listenAddress))..add(DiagnosticsProperty('path', path))..add(DiagnosticsProperty('url', url)); -} - -@override -bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is VeilidConfigWSS&&(identical(other.connect, connect) || other.connect == connect)&&(identical(other.listen, listen) || other.listen == listen)&&(identical(other.maxConnections, maxConnections) || other.maxConnections == maxConnections)&&(identical(other.listenAddress, listenAddress) || other.listenAddress == listenAddress)&&(identical(other.path, path) || other.path == path)&&(identical(other.url, url) || other.url == url)); -} - -@JsonKey(includeFromJson: false, includeToJson: false) -@override -int get hashCode => Object.hash(runtimeType,connect,listen,maxConnections,listenAddress,path,url); - -@override -String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { - return 'VeilidConfigWSS(connect: $connect, listen: $listen, maxConnections: $maxConnections, listenAddress: $listenAddress, path: $path, url: $url)'; -} - - -} - -/// @nodoc -abstract mixin class $VeilidConfigWSSCopyWith<$Res> { - factory $VeilidConfigWSSCopyWith(VeilidConfigWSS value, $Res Function(VeilidConfigWSS) _then) = _$VeilidConfigWSSCopyWithImpl; -@useResult -$Res call({ - bool connect, bool listen, int maxConnections, String listenAddress, String path, String? url -}); - - - - -} -/// @nodoc -class _$VeilidConfigWSSCopyWithImpl<$Res> - implements $VeilidConfigWSSCopyWith<$Res> { - _$VeilidConfigWSSCopyWithImpl(this._self, this._then); - - final VeilidConfigWSS _self; - final $Res Function(VeilidConfigWSS) _then; - -/// Create a copy of VeilidConfigWSS -/// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? connect = null,Object? listen = null,Object? maxConnections = null,Object? listenAddress = null,Object? path = null,Object? url = freezed,}) { - return _then(_self.copyWith( -connect: null == connect ? _self.connect : connect // ignore: cast_nullable_to_non_nullable -as bool,listen: null == listen ? _self.listen : listen // ignore: cast_nullable_to_non_nullable -as bool,maxConnections: null == maxConnections ? _self.maxConnections : maxConnections // ignore: cast_nullable_to_non_nullable -as int,listenAddress: null == listenAddress ? _self.listenAddress : listenAddress // ignore: cast_nullable_to_non_nullable -as String,path: null == path ? _self.path : path // ignore: cast_nullable_to_non_nullable -as String,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable -as String?, - )); -} - -} - - -/// Adds pattern-matching-related methods to [VeilidConfigWSS]. -extension VeilidConfigWSSPatterns on VeilidConfigWSS { -/// A variant of `map` that fallback to returning `orElse`. -/// -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case final Subclass value: -/// return ...; -/// case _: -/// return orElse(); -/// } -/// ``` - -@optionalTypeArgs TResult maybeMap(TResult Function( _VeilidConfigWSS value)? $default,{required TResult orElse(),}){ -final _that = this; -switch (_that) { -case _VeilidConfigWSS() when $default != null: -return $default(_that);case _: - return orElse(); - -} -} -/// A `switch`-like method, using callbacks. -/// -/// Callbacks receives the raw object, upcasted. -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case final Subclass value: -/// return ...; -/// case final Subclass2 value: -/// return ...; -/// } -/// ``` - -@optionalTypeArgs TResult map(TResult Function( _VeilidConfigWSS value) $default,){ -final _that = this; -switch (_that) { -case _VeilidConfigWSS(): -return $default(_that);} -} -/// A variant of `map` that fallback to returning `null`. -/// -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case final Subclass value: -/// return ...; -/// case _: -/// return null; -/// } -/// ``` - -@optionalTypeArgs TResult? mapOrNull(TResult? Function( _VeilidConfigWSS value)? $default,){ -final _that = this; -switch (_that) { -case _VeilidConfigWSS() when $default != null: -return $default(_that);case _: - return null; - -} -} -/// A variant of `when` that fallback to an `orElse` callback. -/// -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case Subclass(:final field): -/// return ...; -/// case _: -/// return orElse(); -/// } -/// ``` - -@optionalTypeArgs TResult maybeWhen(TResult Function( bool connect, bool listen, int maxConnections, String listenAddress, String path, String? url)? $default,{required TResult orElse(),}) {final _that = this; -switch (_that) { -case _VeilidConfigWSS() when $default != null: -return $default(_that.connect,_that.listen,_that.maxConnections,_that.listenAddress,_that.path,_that.url);case _: - return orElse(); - -} -} -/// A `switch`-like method, using callbacks. -/// -/// As opposed to `map`, this offers destructuring. -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case Subclass(:final field): -/// return ...; -/// case Subclass2(:final field2): -/// return ...; -/// } -/// ``` - -@optionalTypeArgs TResult when(TResult Function( bool connect, bool listen, int maxConnections, String listenAddress, String path, String? url) $default,) {final _that = this; -switch (_that) { -case _VeilidConfigWSS(): -return $default(_that.connect,_that.listen,_that.maxConnections,_that.listenAddress,_that.path,_that.url);} -} -/// A variant of `when` that fallback to returning `null` -/// -/// It is equivalent to doing: -/// ```dart -/// switch (sealedClass) { -/// case Subclass(:final field): -/// return ...; -/// case _: -/// return null; -/// } -/// ``` - -@optionalTypeArgs TResult? whenOrNull(TResult? Function( bool connect, bool listen, int maxConnections, String listenAddress, String path, String? url)? $default,) {final _that = this; -switch (_that) { -case _VeilidConfigWSS() when $default != null: -return $default(_that.connect,_that.listen,_that.maxConnections,_that.listenAddress,_that.path,_that.url);case _: - return null; - -} -} - -} - -/// @nodoc -@JsonSerializable() -@Deprecated('WSS is disabled by default in veilid-flutter') -class _VeilidConfigWSS with DiagnosticableTreeMixin implements VeilidConfigWSS { - const _VeilidConfigWSS({required this.connect, required this.listen, required this.maxConnections, required this.listenAddress, required this.path, this.url}); - factory _VeilidConfigWSS.fromJson(Map json) => _$VeilidConfigWSSFromJson(json); - -@override final bool connect; -@override final bool listen; -@override final int maxConnections; -@override final String listenAddress; -@override final String path; -@override final String? url; - -/// Create a copy of VeilidConfigWSS -/// with the given fields replaced by the non-null parameter values. -@override @JsonKey(includeFromJson: false, includeToJson: false) -@pragma('vm:prefer-inline') -_$VeilidConfigWSSCopyWith<_VeilidConfigWSS> get copyWith => __$VeilidConfigWSSCopyWithImpl<_VeilidConfigWSS>(this, _$identity); - -@override -Map toJson() { - return _$VeilidConfigWSSToJson(this, ); -} -@override -void debugFillProperties(DiagnosticPropertiesBuilder properties) { - properties - ..add(DiagnosticsProperty('type', 'VeilidConfigWSS')) - ..add(DiagnosticsProperty('connect', connect))..add(DiagnosticsProperty('listen', listen))..add(DiagnosticsProperty('maxConnections', maxConnections))..add(DiagnosticsProperty('listenAddress', listenAddress))..add(DiagnosticsProperty('path', path))..add(DiagnosticsProperty('url', url)); -} - -@override -bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _VeilidConfigWSS&&(identical(other.connect, connect) || other.connect == connect)&&(identical(other.listen, listen) || other.listen == listen)&&(identical(other.maxConnections, maxConnections) || other.maxConnections == maxConnections)&&(identical(other.listenAddress, listenAddress) || other.listenAddress == listenAddress)&&(identical(other.path, path) || other.path == path)&&(identical(other.url, url) || other.url == url)); -} - -@JsonKey(includeFromJson: false, includeToJson: false) -@override -int get hashCode => Object.hash(runtimeType,connect,listen,maxConnections,listenAddress,path,url); - -@override -String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { - return 'VeilidConfigWSS(connect: $connect, listen: $listen, maxConnections: $maxConnections, listenAddress: $listenAddress, path: $path, url: $url)'; -} - - -} - -/// @nodoc -abstract mixin class _$VeilidConfigWSSCopyWith<$Res> implements $VeilidConfigWSSCopyWith<$Res> { - factory _$VeilidConfigWSSCopyWith(_VeilidConfigWSS value, $Res Function(_VeilidConfigWSS) _then) = __$VeilidConfigWSSCopyWithImpl; -@override @useResult -$Res call({ - bool connect, bool listen, int maxConnections, String listenAddress, String path, String? url -}); - - - - -} -/// @nodoc -class __$VeilidConfigWSSCopyWithImpl<$Res> - implements _$VeilidConfigWSSCopyWith<$Res> { - __$VeilidConfigWSSCopyWithImpl(this._self, this._then); - - final _VeilidConfigWSS _self; - final $Res Function(_VeilidConfigWSS) _then; - -/// Create a copy of VeilidConfigWSS -/// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? connect = null,Object? listen = null,Object? maxConnections = null,Object? listenAddress = null,Object? path = null,Object? url = freezed,}) { - return _then(_VeilidConfigWSS( -connect: null == connect ? _self.connect : connect // ignore: cast_nullable_to_non_nullable -as bool,listen: null == listen ? _self.listen : listen // ignore: cast_nullable_to_non_nullable -as bool,maxConnections: null == maxConnections ? _self.maxConnections : maxConnections // ignore: cast_nullable_to_non_nullable -as int,listenAddress: null == listenAddress ? _self.listenAddress : listenAddress // ignore: cast_nullable_to_non_nullable -as String,path: null == path ? _self.path : path // ignore: cast_nullable_to_non_nullable -as String,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable -as String?, - )); -} - - -} - - /// @nodoc mixin _$VeilidConfigProtocol implements DiagnosticableTreeMixin { - VeilidConfigUDP get udp; VeilidConfigTCP get tcp; VeilidConfigWS get ws;@Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS get wss; + VeilidConfigUDP get udp; VeilidConfigTCP get tcp; VeilidConfigWS get ws; /// Create a copy of VeilidConfigProtocol /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -4077,21 +3793,21 @@ $VeilidConfigProtocolCopyWith get copyWith => _$VeilidConf void debugFillProperties(DiagnosticPropertiesBuilder properties) { properties ..add(DiagnosticsProperty('type', 'VeilidConfigProtocol')) - ..add(DiagnosticsProperty('udp', udp))..add(DiagnosticsProperty('tcp', tcp))..add(DiagnosticsProperty('ws', ws))..add(DiagnosticsProperty('wss', wss)); + ..add(DiagnosticsProperty('udp', udp))..add(DiagnosticsProperty('tcp', tcp))..add(DiagnosticsProperty('ws', ws)); } @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is VeilidConfigProtocol&&(identical(other.udp, udp) || other.udp == udp)&&(identical(other.tcp, tcp) || other.tcp == tcp)&&(identical(other.ws, ws) || other.ws == ws)&&(identical(other.wss, wss) || other.wss == wss)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is VeilidConfigProtocol&&(identical(other.udp, udp) || other.udp == udp)&&(identical(other.tcp, tcp) || other.tcp == tcp)&&(identical(other.ws, ws) || other.ws == ws)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,udp,tcp,ws,wss); +int get hashCode => Object.hash(runtimeType,udp,tcp,ws); @override String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { - return 'VeilidConfigProtocol(udp: $udp, tcp: $tcp, ws: $ws, wss: $wss)'; + return 'VeilidConfigProtocol(udp: $udp, tcp: $tcp, ws: $ws)'; } @@ -4102,11 +3818,11 @@ abstract mixin class $VeilidConfigProtocolCopyWith<$Res> { factory $VeilidConfigProtocolCopyWith(VeilidConfigProtocol value, $Res Function(VeilidConfigProtocol) _then) = _$VeilidConfigProtocolCopyWithImpl; @useResult $Res call({ - VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws,@Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS wss + VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws }); -$VeilidConfigUDPCopyWith<$Res> get udp;$VeilidConfigTCPCopyWith<$Res> get tcp;$VeilidConfigWSCopyWith<$Res> get ws;$VeilidConfigWSSCopyWith<$Res> get wss; +$VeilidConfigUDPCopyWith<$Res> get udp;$VeilidConfigTCPCopyWith<$Res> get tcp;$VeilidConfigWSCopyWith<$Res> get ws; } /// @nodoc @@ -4119,13 +3835,12 @@ class _$VeilidConfigProtocolCopyWithImpl<$Res> /// Create a copy of VeilidConfigProtocol /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? udp = null,Object? tcp = null,Object? ws = null,Object? wss = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? udp = null,Object? tcp = null,Object? ws = null,}) { return _then(_self.copyWith( udp: null == udp ? _self.udp : udp // ignore: cast_nullable_to_non_nullable as VeilidConfigUDP,tcp: null == tcp ? _self.tcp : tcp // ignore: cast_nullable_to_non_nullable as VeilidConfigTCP,ws: null == ws ? _self.ws : ws // ignore: cast_nullable_to_non_nullable -as VeilidConfigWS,wss: null == wss ? _self.wss : wss // ignore: cast_nullable_to_non_nullable -as VeilidConfigWSS, +as VeilidConfigWS, )); } /// Create a copy of VeilidConfigProtocol @@ -4155,15 +3870,6 @@ $VeilidConfigWSCopyWith<$Res> get ws { return $VeilidConfigWSCopyWith<$Res>(_self.ws, (value) { return _then(_self.copyWith(ws: value)); }); -}/// Create a copy of VeilidConfigProtocol -/// with the given fields replaced by the non-null parameter values. -@override -@pragma('vm:prefer-inline') -$VeilidConfigWSSCopyWith<$Res> get wss { - - return $VeilidConfigWSSCopyWith<$Res>(_self.wss, (value) { - return _then(_self.copyWith(wss: value)); - }); } } @@ -4243,10 +3949,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws, @Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS wss)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _VeilidConfigProtocol() when $default != null: -return $default(_that.udp,_that.tcp,_that.ws,_that.wss);case _: +return $default(_that.udp,_that.tcp,_that.ws);case _: return orElse(); } @@ -4264,10 +3970,10 @@ return $default(_that.udp,_that.tcp,_that.ws,_that.wss);case _: /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws, @Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS wss) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws) $default,) {final _that = this; switch (_that) { case _VeilidConfigProtocol(): -return $default(_that.udp,_that.tcp,_that.ws,_that.wss);} +return $default(_that.udp,_that.tcp,_that.ws);} } /// A variant of `when` that fallback to returning `null` /// @@ -4281,10 +3987,10 @@ return $default(_that.udp,_that.tcp,_that.ws,_that.wss);} /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws, @Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS wss)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws)? $default,) {final _that = this; switch (_that) { case _VeilidConfigProtocol() when $default != null: -return $default(_that.udp,_that.tcp,_that.ws,_that.wss);case _: +return $default(_that.udp,_that.tcp,_that.ws);case _: return null; } @@ -4296,13 +4002,12 @@ return $default(_that.udp,_that.tcp,_that.ws,_that.wss);case _: @JsonSerializable() class _VeilidConfigProtocol with DiagnosticableTreeMixin implements VeilidConfigProtocol { - const _VeilidConfigProtocol({required this.udp, required this.tcp, required this.ws, @Deprecated('WSS is disabled by default in veilid-flutter') required this.wss}); + const _VeilidConfigProtocol({required this.udp, required this.tcp, required this.ws}); factory _VeilidConfigProtocol.fromJson(Map json) => _$VeilidConfigProtocolFromJson(json); @override final VeilidConfigUDP udp; @override final VeilidConfigTCP tcp; @override final VeilidConfigWS ws; -@override@Deprecated('WSS is disabled by default in veilid-flutter') final VeilidConfigWSS wss; /// Create a copy of VeilidConfigProtocol /// with the given fields replaced by the non-null parameter values. @@ -4318,21 +4023,21 @@ Map toJson() { void debugFillProperties(DiagnosticPropertiesBuilder properties) { properties ..add(DiagnosticsProperty('type', 'VeilidConfigProtocol')) - ..add(DiagnosticsProperty('udp', udp))..add(DiagnosticsProperty('tcp', tcp))..add(DiagnosticsProperty('ws', ws))..add(DiagnosticsProperty('wss', wss)); + ..add(DiagnosticsProperty('udp', udp))..add(DiagnosticsProperty('tcp', tcp))..add(DiagnosticsProperty('ws', ws)); } @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _VeilidConfigProtocol&&(identical(other.udp, udp) || other.udp == udp)&&(identical(other.tcp, tcp) || other.tcp == tcp)&&(identical(other.ws, ws) || other.ws == ws)&&(identical(other.wss, wss) || other.wss == wss)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _VeilidConfigProtocol&&(identical(other.udp, udp) || other.udp == udp)&&(identical(other.tcp, tcp) || other.tcp == tcp)&&(identical(other.ws, ws) || other.ws == ws)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,udp,tcp,ws,wss); +int get hashCode => Object.hash(runtimeType,udp,tcp,ws); @override String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { - return 'VeilidConfigProtocol(udp: $udp, tcp: $tcp, ws: $ws, wss: $wss)'; + return 'VeilidConfigProtocol(udp: $udp, tcp: $tcp, ws: $ws)'; } @@ -4343,11 +4048,11 @@ abstract mixin class _$VeilidConfigProtocolCopyWith<$Res> implements $VeilidConf factory _$VeilidConfigProtocolCopyWith(_VeilidConfigProtocol value, $Res Function(_VeilidConfigProtocol) _then) = __$VeilidConfigProtocolCopyWithImpl; @override @useResult $Res call({ - VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws,@Deprecated('WSS is disabled by default in veilid-flutter') VeilidConfigWSS wss + VeilidConfigUDP udp, VeilidConfigTCP tcp, VeilidConfigWS ws }); -@override $VeilidConfigUDPCopyWith<$Res> get udp;@override $VeilidConfigTCPCopyWith<$Res> get tcp;@override $VeilidConfigWSCopyWith<$Res> get ws;@override $VeilidConfigWSSCopyWith<$Res> get wss; +@override $VeilidConfigUDPCopyWith<$Res> get udp;@override $VeilidConfigTCPCopyWith<$Res> get tcp;@override $VeilidConfigWSCopyWith<$Res> get ws; } /// @nodoc @@ -4360,13 +4065,12 @@ class __$VeilidConfigProtocolCopyWithImpl<$Res> /// Create a copy of VeilidConfigProtocol /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? udp = null,Object? tcp = null,Object? ws = null,Object? wss = null,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? udp = null,Object? tcp = null,Object? ws = null,}) { return _then(_VeilidConfigProtocol( udp: null == udp ? _self.udp : udp // ignore: cast_nullable_to_non_nullable as VeilidConfigUDP,tcp: null == tcp ? _self.tcp : tcp // ignore: cast_nullable_to_non_nullable as VeilidConfigTCP,ws: null == ws ? _self.ws : ws // ignore: cast_nullable_to_non_nullable -as VeilidConfigWS,wss: null == wss ? _self.wss : wss // ignore: cast_nullable_to_non_nullable -as VeilidConfigWSS, +as VeilidConfigWS, )); } @@ -4397,15 +4101,6 @@ $VeilidConfigWSCopyWith<$Res> get ws { return $VeilidConfigWSCopyWith<$Res>(_self.ws, (value) { return _then(_self.copyWith(ws: value)); }); -}/// Create a copy of VeilidConfigProtocol -/// with the given fields replaced by the non-null parameter values. -@override -@pragma('vm:prefer-inline') -$VeilidConfigWSSCopyWith<$Res> get wss { - - return $VeilidConfigWSSCopyWith<$Res>(_self.wss, (value) { - return _then(_self.copyWith(wss: value)); - }); } } diff --git a/veilid-flutter/lib/veilid_config.g.dart b/veilid-flutter/lib/veilid_config.g.dart index 823b16ba..19d12c30 100644 --- a/veilid-flutter/lib/veilid_config.g.dart +++ b/veilid-flutter/lib/veilid_config.g.dart @@ -225,33 +225,12 @@ Map _$VeilidConfigWSToJson(_VeilidConfigWS instance) => 'url': instance.url, }; -_VeilidConfigWSS _$VeilidConfigWSSFromJson(Map json) => - _VeilidConfigWSS( - connect: json['connect'] as bool, - listen: json['listen'] as bool, - maxConnections: (json['max_connections'] as num).toInt(), - listenAddress: json['listen_address'] as String, - path: json['path'] as String, - url: json['url'] as String?, - ); - -Map _$VeilidConfigWSSToJson(_VeilidConfigWSS instance) => - { - 'connect': instance.connect, - 'listen': instance.listen, - 'max_connections': instance.maxConnections, - 'listen_address': instance.listenAddress, - 'path': instance.path, - 'url': instance.url, - }; - _VeilidConfigProtocol _$VeilidConfigProtocolFromJson( Map json, ) => _VeilidConfigProtocol( udp: VeilidConfigUDP.fromJson(json['udp']), tcp: VeilidConfigTCP.fromJson(json['tcp']), ws: VeilidConfigWS.fromJson(json['ws']), - wss: VeilidConfigWSS.fromJson(json['wss']), ); Map _$VeilidConfigProtocolToJson( @@ -260,7 +239,6 @@ Map _$VeilidConfigProtocolToJson( 'udp': instance.udp.toJson(), 'tcp': instance.tcp.toJson(), 'ws': instance.ws.toJson(), - 'wss': instance.wss.toJson(), }; _VeilidConfigPrivacy _$VeilidConfigPrivacyFromJson(Map json) => diff --git a/veilid-flutter/lib/veilid_state.dart b/veilid-flutter/lib/veilid_state.dart index a8f8ea9c..98bd6a96 100644 --- a/veilid-flutter/lib/veilid_state.dart +++ b/veilid-flutter/lib/veilid_state.dart @@ -188,7 +188,7 @@ sealed class PeerStats with _$PeerStats { @freezed sealed class PeerTableData with _$PeerTableData { const factory PeerTableData({ - required List nodeIds, + required List nodeIds, required String peerAddress, required PeerStats peerStats, }) = _PeerTableData; @@ -218,20 +218,22 @@ sealed class VeilidUpdate with _$VeilidUpdate { PublicKey? sender, String? routeId, }) = VeilidAppCall; - const factory VeilidUpdate.attachment( - {required AttachmentState state, - required bool publicInternetReady, - required bool localNetworkReady, - required TimestampDuration uptime, - required TimestampDuration? attachedUptime}) = VeilidUpdateAttachment; - const factory VeilidUpdate.network( - {required bool started, - required BigInt bpsDown, - required BigInt bpsUp, - required List peers}) = VeilidUpdateNetwork; - const factory VeilidUpdate.config({ - required VeilidConfig config, - }) = VeilidUpdateConfig; + const factory VeilidUpdate.attachment({ + required AttachmentState state, + required bool publicInternetReady, + required bool localNetworkReady, + required TimestampDuration uptime, + required TimestampDuration? attachedUptime, + }) = VeilidUpdateAttachment; + const factory VeilidUpdate.network({ + required bool started, + required BigInt bpsDown, + required BigInt bpsUp, + required List peers, + required List nodeIds, + }) = VeilidUpdateNetwork; + const factory VeilidUpdate.config({required VeilidConfig config}) = + VeilidUpdateConfig; const factory VeilidUpdate.routeChange({ required List deadRoutes, required List deadRemoteRoutes, @@ -252,12 +254,13 @@ sealed class VeilidUpdate with _$VeilidUpdate { @freezed sealed class VeilidStateAttachment with _$VeilidStateAttachment { - const factory VeilidStateAttachment( - {required AttachmentState state, - required bool publicInternetReady, - required bool localNetworkReady, - required TimestampDuration uptime, - required TimestampDuration? attachedUptime}) = _VeilidStateAttachment; + const factory VeilidStateAttachment({ + required AttachmentState state, + required bool publicInternetReady, + required bool localNetworkReady, + required TimestampDuration uptime, + required TimestampDuration? attachedUptime, + }) = _VeilidStateAttachment; factory VeilidStateAttachment.fromJson(dynamic json) => _$VeilidStateAttachmentFromJson(json as Map); @@ -268,11 +271,12 @@ sealed class VeilidStateAttachment with _$VeilidStateAttachment { @freezed sealed class VeilidStateNetwork with _$VeilidStateNetwork { - const factory VeilidStateNetwork( - {required bool started, - required BigInt bpsDown, - required BigInt bpsUp, - required List peers}) = _VeilidStateNetwork; + const factory VeilidStateNetwork({ + required bool started, + required BigInt bpsDown, + required BigInt bpsUp, + required List peers, + }) = _VeilidStateNetwork; factory VeilidStateNetwork.fromJson(dynamic json) => _$VeilidStateNetworkFromJson(json as Map); @@ -283,9 +287,8 @@ sealed class VeilidStateNetwork with _$VeilidStateNetwork { @freezed sealed class VeilidStateConfig with _$VeilidStateConfig { - const factory VeilidStateConfig({ - required VeilidConfig config, - }) = _VeilidStateConfig; + const factory VeilidStateConfig({required VeilidConfig config}) = + _VeilidStateConfig; factory VeilidStateConfig.fromJson(dynamic json) => _$VeilidStateConfigFromJson(json as Map); diff --git a/veilid-flutter/lib/veilid_state.freezed.dart b/veilid-flutter/lib/veilid_state.freezed.dart index bc49c892..b5505dec 100644 --- a/veilid-flutter/lib/veilid_state.freezed.dart +++ b/veilid-flutter/lib/veilid_state.freezed.dart @@ -2371,7 +2371,7 @@ $LatencyStatsCopyWith<$Res>? get latency { /// @nodoc mixin _$PeerTableData { - List get nodeIds; String get peerAddress; PeerStats get peerStats; + List get nodeIds; String get peerAddress; PeerStats get peerStats; /// Create a copy of PeerTableData /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -2404,7 +2404,7 @@ abstract mixin class $PeerTableDataCopyWith<$Res> { factory $PeerTableDataCopyWith(PeerTableData value, $Res Function(PeerTableData) _then) = _$PeerTableDataCopyWithImpl; @useResult $Res call({ - List nodeIds, String peerAddress, PeerStats peerStats + List nodeIds, String peerAddress, PeerStats peerStats }); @@ -2424,7 +2424,7 @@ class _$PeerTableDataCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({Object? nodeIds = null,Object? peerAddress = null,Object? peerStats = null,}) { return _then(_self.copyWith( nodeIds: null == nodeIds ? _self.nodeIds : nodeIds // ignore: cast_nullable_to_non_nullable -as List,peerAddress: null == peerAddress ? _self.peerAddress : peerAddress // ignore: cast_nullable_to_non_nullable +as List,peerAddress: null == peerAddress ? _self.peerAddress : peerAddress // ignore: cast_nullable_to_non_nullable as String,peerStats: null == peerStats ? _self.peerStats : peerStats // ignore: cast_nullable_to_non_nullable as PeerStats, )); @@ -2517,7 +2517,7 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( List nodeIds, String peerAddress, PeerStats peerStats)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( List nodeIds, String peerAddress, PeerStats peerStats)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _PeerTableData() when $default != null: return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);case _: @@ -2538,7 +2538,7 @@ return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);case _: /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( List nodeIds, String peerAddress, PeerStats peerStats) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( List nodeIds, String peerAddress, PeerStats peerStats) $default,) {final _that = this; switch (_that) { case _PeerTableData(): return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);} @@ -2555,7 +2555,7 @@ return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);} /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( List nodeIds, String peerAddress, PeerStats peerStats)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( List nodeIds, String peerAddress, PeerStats peerStats)? $default,) {final _that = this; switch (_that) { case _PeerTableData() when $default != null: return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);case _: @@ -2570,11 +2570,11 @@ return $default(_that.nodeIds,_that.peerAddress,_that.peerStats);case _: @JsonSerializable() class _PeerTableData implements PeerTableData { - const _PeerTableData({required final List nodeIds, required this.peerAddress, required this.peerStats}): _nodeIds = nodeIds; + const _PeerTableData({required final List nodeIds, required this.peerAddress, required this.peerStats}): _nodeIds = nodeIds; factory _PeerTableData.fromJson(Map json) => _$PeerTableDataFromJson(json); - final List _nodeIds; -@override List get nodeIds { + final List _nodeIds; +@override List get nodeIds { if (_nodeIds is EqualUnmodifiableListView) return _nodeIds; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_nodeIds); @@ -2616,7 +2616,7 @@ abstract mixin class _$PeerTableDataCopyWith<$Res> implements $PeerTableDataCopy factory _$PeerTableDataCopyWith(_PeerTableData value, $Res Function(_PeerTableData) _then) = __$PeerTableDataCopyWithImpl; @override @useResult $Res call({ - List nodeIds, String peerAddress, PeerStats peerStats + List nodeIds, String peerAddress, PeerStats peerStats }); @@ -2636,7 +2636,7 @@ class __$PeerTableDataCopyWithImpl<$Res> @override @pragma('vm:prefer-inline') $Res call({Object? nodeIds = null,Object? peerAddress = null,Object? peerStats = null,}) { return _then(_PeerTableData( nodeIds: null == nodeIds ? _self._nodeIds : nodeIds // ignore: cast_nullable_to_non_nullable -as List,peerAddress: null == peerAddress ? _self.peerAddress : peerAddress // ignore: cast_nullable_to_non_nullable +as List,peerAddress: null == peerAddress ? _self.peerAddress : peerAddress // ignore: cast_nullable_to_non_nullable as String,peerStats: null == peerStats ? _self.peerStats : peerStats // ignore: cast_nullable_to_non_nullable as PeerStats, )); @@ -2830,14 +2830,14 @@ return valueChange(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen({TResult Function( VeilidLogLevel logLevel, String message, String? backtrace)? log,TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId)? appMessage,TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId)? appCall,TResult Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime)? attachment,TResult Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers)? network,TResult Function( VeilidConfig config)? config,TResult Function( List deadRoutes, List deadRemoteRoutes)? routeChange,TResult Function( RecordKey key, List subkeys, int count, ValueData? value)? valueChange,required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen({TResult Function( VeilidLogLevel logLevel, String message, String? backtrace)? log,TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId)? appMessage,TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId)? appCall,TResult Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime)? attachment,TResult Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers, List nodeIds)? network,TResult Function( VeilidConfig config)? config,TResult Function( List deadRoutes, List deadRemoteRoutes)? routeChange,TResult Function( RecordKey key, List subkeys, int count, ValueData? value)? valueChange,required TResult orElse(),}) {final _that = this; switch (_that) { case VeilidLog() when log != null: return log(_that.logLevel,_that.message,_that.backtrace);case VeilidAppMessage() when appMessage != null: return appMessage(_that.message,_that.sender,_that.routeId);case VeilidAppCall() when appCall != null: return appCall(_that.message,_that.callId,_that.sender,_that.routeId);case VeilidUpdateAttachment() when attachment != null: return attachment(_that.state,_that.publicInternetReady,_that.localNetworkReady,_that.uptime,_that.attachedUptime);case VeilidUpdateNetwork() when network != null: -return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers);case VeilidUpdateConfig() when config != null: +return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers,_that.nodeIds);case VeilidUpdateConfig() when config != null: return config(_that.config);case VeilidUpdateRouteChange() when routeChange != null: return routeChange(_that.deadRoutes,_that.deadRemoteRoutes);case VeilidUpdateValueChange() when valueChange != null: return valueChange(_that.key,_that.subkeys,_that.count,_that.value);case _: @@ -2858,14 +2858,14 @@ return valueChange(_that.key,_that.subkeys,_that.count,_that.value);case _: /// } /// ``` -@optionalTypeArgs TResult when({required TResult Function( VeilidLogLevel logLevel, String message, String? backtrace) log,required TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId) appMessage,required TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId) appCall,required TResult Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime) attachment,required TResult Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers) network,required TResult Function( VeilidConfig config) config,required TResult Function( List deadRoutes, List deadRemoteRoutes) routeChange,required TResult Function( RecordKey key, List subkeys, int count, ValueData? value) valueChange,}) {final _that = this; +@optionalTypeArgs TResult when({required TResult Function( VeilidLogLevel logLevel, String message, String? backtrace) log,required TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId) appMessage,required TResult Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId) appCall,required TResult Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime) attachment,required TResult Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers, List nodeIds) network,required TResult Function( VeilidConfig config) config,required TResult Function( List deadRoutes, List deadRemoteRoutes) routeChange,required TResult Function( RecordKey key, List subkeys, int count, ValueData? value) valueChange,}) {final _that = this; switch (_that) { case VeilidLog(): return log(_that.logLevel,_that.message,_that.backtrace);case VeilidAppMessage(): return appMessage(_that.message,_that.sender,_that.routeId);case VeilidAppCall(): return appCall(_that.message,_that.callId,_that.sender,_that.routeId);case VeilidUpdateAttachment(): return attachment(_that.state,_that.publicInternetReady,_that.localNetworkReady,_that.uptime,_that.attachedUptime);case VeilidUpdateNetwork(): -return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers);case VeilidUpdateConfig(): +return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers,_that.nodeIds);case VeilidUpdateConfig(): return config(_that.config);case VeilidUpdateRouteChange(): return routeChange(_that.deadRoutes,_that.deadRemoteRoutes);case VeilidUpdateValueChange(): return valueChange(_that.key,_that.subkeys,_that.count,_that.value);} @@ -2882,14 +2882,14 @@ return valueChange(_that.key,_that.subkeys,_that.count,_that.value);} /// } /// ``` -@optionalTypeArgs TResult? whenOrNull({TResult? Function( VeilidLogLevel logLevel, String message, String? backtrace)? log,TResult? Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId)? appMessage,TResult? Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId)? appCall,TResult? Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime)? attachment,TResult? Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers)? network,TResult? Function( VeilidConfig config)? config,TResult? Function( List deadRoutes, List deadRemoteRoutes)? routeChange,TResult? Function( RecordKey key, List subkeys, int count, ValueData? value)? valueChange,}) {final _that = this; +@optionalTypeArgs TResult? whenOrNull({TResult? Function( VeilidLogLevel logLevel, String message, String? backtrace)? log,TResult? Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, PublicKey? sender, String? routeId)? appMessage,TResult? Function(@Uint8ListJsonConverter.jsIsArray() Uint8List message, String callId, PublicKey? sender, String? routeId)? appCall,TResult? Function( AttachmentState state, bool publicInternetReady, bool localNetworkReady, TimestampDuration uptime, TimestampDuration? attachedUptime)? attachment,TResult? Function( bool started, BigInt bpsDown, BigInt bpsUp, List peers, List nodeIds)? network,TResult? Function( VeilidConfig config)? config,TResult? Function( List deadRoutes, List deadRemoteRoutes)? routeChange,TResult? Function( RecordKey key, List subkeys, int count, ValueData? value)? valueChange,}) {final _that = this; switch (_that) { case VeilidLog() when log != null: return log(_that.logLevel,_that.message,_that.backtrace);case VeilidAppMessage() when appMessage != null: return appMessage(_that.message,_that.sender,_that.routeId);case VeilidAppCall() when appCall != null: return appCall(_that.message,_that.callId,_that.sender,_that.routeId);case VeilidUpdateAttachment() when attachment != null: return attachment(_that.state,_that.publicInternetReady,_that.localNetworkReady,_that.uptime,_that.attachedUptime);case VeilidUpdateNetwork() when network != null: -return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers);case VeilidUpdateConfig() when config != null: +return network(_that.started,_that.bpsDown,_that.bpsUp,_that.peers,_that.nodeIds);case VeilidUpdateConfig() when config != null: return config(_that.config);case VeilidUpdateRouteChange() when routeChange != null: return routeChange(_that.deadRoutes,_that.deadRemoteRoutes);case VeilidUpdateValueChange() when valueChange != null: return valueChange(_that.key,_that.subkeys,_that.count,_that.value);case _: @@ -3218,7 +3218,7 @@ as TimestampDuration?, @JsonSerializable() class VeilidUpdateNetwork implements VeilidUpdate { - const VeilidUpdateNetwork({required this.started, required this.bpsDown, required this.bpsUp, required final List peers, final String? $type}): _peers = peers,$type = $type ?? 'Network'; + const VeilidUpdateNetwork({required this.started, required this.bpsDown, required this.bpsUp, required final List peers, required final List nodeIds, final String? $type}): _peers = peers,_nodeIds = nodeIds,$type = $type ?? 'Network'; factory VeilidUpdateNetwork.fromJson(Map json) => _$VeilidUpdateNetworkFromJson(json); final bool started; @@ -3231,6 +3231,13 @@ class VeilidUpdateNetwork implements VeilidUpdate { return EqualUnmodifiableListView(_peers); } + final List _nodeIds; + List get nodeIds { + if (_nodeIds is EqualUnmodifiableListView) return _nodeIds; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_nodeIds); +} + @JsonKey(name: 'kind') final String $type; @@ -3249,16 +3256,16 @@ Map toJson() { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is VeilidUpdateNetwork&&(identical(other.started, started) || other.started == started)&&(identical(other.bpsDown, bpsDown) || other.bpsDown == bpsDown)&&(identical(other.bpsUp, bpsUp) || other.bpsUp == bpsUp)&&const DeepCollectionEquality().equals(other._peers, _peers)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is VeilidUpdateNetwork&&(identical(other.started, started) || other.started == started)&&(identical(other.bpsDown, bpsDown) || other.bpsDown == bpsDown)&&(identical(other.bpsUp, bpsUp) || other.bpsUp == bpsUp)&&const DeepCollectionEquality().equals(other._peers, _peers)&&const DeepCollectionEquality().equals(other._nodeIds, _nodeIds)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,started,bpsDown,bpsUp,const DeepCollectionEquality().hash(_peers)); +int get hashCode => Object.hash(runtimeType,started,bpsDown,bpsUp,const DeepCollectionEquality().hash(_peers),const DeepCollectionEquality().hash(_nodeIds)); @override String toString() { - return 'VeilidUpdate.network(started: $started, bpsDown: $bpsDown, bpsUp: $bpsUp, peers: $peers)'; + return 'VeilidUpdate.network(started: $started, bpsDown: $bpsDown, bpsUp: $bpsUp, peers: $peers, nodeIds: $nodeIds)'; } @@ -3269,7 +3276,7 @@ abstract mixin class $VeilidUpdateNetworkCopyWith<$Res> implements $VeilidUpdate factory $VeilidUpdateNetworkCopyWith(VeilidUpdateNetwork value, $Res Function(VeilidUpdateNetwork) _then) = _$VeilidUpdateNetworkCopyWithImpl; @useResult $Res call({ - bool started, BigInt bpsDown, BigInt bpsUp, List peers + bool started, BigInt bpsDown, BigInt bpsUp, List peers, List nodeIds }); @@ -3286,13 +3293,14 @@ class _$VeilidUpdateNetworkCopyWithImpl<$Res> /// Create a copy of VeilidUpdate /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') $Res call({Object? started = null,Object? bpsDown = null,Object? bpsUp = null,Object? peers = null,}) { +@pragma('vm:prefer-inline') $Res call({Object? started = null,Object? bpsDown = null,Object? bpsUp = null,Object? peers = null,Object? nodeIds = null,}) { return _then(VeilidUpdateNetwork( started: null == started ? _self.started : started // ignore: cast_nullable_to_non_nullable as bool,bpsDown: null == bpsDown ? _self.bpsDown : bpsDown // ignore: cast_nullable_to_non_nullable as BigInt,bpsUp: null == bpsUp ? _self.bpsUp : bpsUp // ignore: cast_nullable_to_non_nullable as BigInt,peers: null == peers ? _self._peers : peers // ignore: cast_nullable_to_non_nullable -as List, +as List,nodeIds: null == nodeIds ? _self._nodeIds : nodeIds // ignore: cast_nullable_to_non_nullable +as List, )); } diff --git a/veilid-flutter/lib/veilid_state.g.dart b/veilid-flutter/lib/veilid_state.g.dart index 65bd2d6b..537bb0c8 100644 --- a/veilid-flutter/lib/veilid_state.g.dart +++ b/veilid-flutter/lib/veilid_state.g.dart @@ -196,7 +196,7 @@ Map _$PeerStatsToJson(_PeerStats instance) => _PeerTableData _$PeerTableDataFromJson(Map json) => _PeerTableData( nodeIds: (json['node_ids'] as List) - .map(Typed.fromJson) + .map(Typed.fromJson) .toList(), peerAddress: json['peer_address'] as String, peerStats: PeerStats.fromJson(json['peer_stats']), @@ -299,6 +299,9 @@ VeilidUpdateNetwork _$VeilidUpdateNetworkFromJson(Map json) => peers: (json['peers'] as List) .map(PeerTableData.fromJson) .toList(), + nodeIds: (json['node_ids'] as List) + .map(Typed.fromJson) + .toList(), $type: json['kind'] as String?, ); @@ -309,6 +312,7 @@ Map _$VeilidUpdateNetworkToJson( 'bps_down': instance.bpsDown.toString(), 'bps_up': instance.bpsUp.toString(), 'peers': instance.peers.map((e) => e.toJson()).toList(), + 'node_ids': instance.nodeIds.map((e) => e.toJson()).toList(), 'kind': instance.$type, }; diff --git a/veilid-python/tests/test_basic.py b/veilid-python/tests/test_basic.py index 1b676239..7f49b5af 100644 --- a/veilid-python/tests/test_basic.py +++ b/veilid-python/tests/test_basic.py @@ -16,14 +16,14 @@ async def test_connect(api_connection: veilid.VeilidAPI): @pytest.mark.asyncio -async def test_get_public_keys(api_connection: veilid.VeilidAPI): +async def test_get_node_ids(api_connection: veilid.VeilidAPI): state = await api_connection.get_state() - public_keys = state.config.config.network.routing_table.public_keys + node_ids = state.network.node_ids - assert len(public_keys) >= 1 + assert len(node_ids) >= 1 - for public_key in public_keys: - assert public_key[4] == ":" + for node_id in node_ids: + assert node_id[4] == ":" @pytest.mark.asyncio diff --git a/veilid-python/uv.lock b/veilid-python/uv.lock index 412c96f8..fdfcbc11 100644 --- a/veilid-python/uv.lock +++ b/veilid-python/uv.lock @@ -210,7 +210,7 @@ wheels = [ [[package]] name = "veilid" -version = "0.4.7" +version = "0.4.8" source = { editable = "." } dependencies = [ { name = "appdirs" }, diff --git a/veilid-python/veilid/schema/RecvMessage.json b/veilid-python/veilid/schema/RecvMessage.json index da4631cf..9ea1a93d 100644 --- a/veilid-python/veilid/schema/RecvMessage.json +++ b/veilid-python/veilid/schema/RecvMessage.json @@ -4758,6 +4758,13 @@ "description": "The total number of bytes per second used by Veilid currently in the upload direction.", "$ref": "#/$defs/ByteCount" }, + "node_ids": { + "description": "The list of node ids for this node", + "type": "array", + "items": { + "type": "string" + } + }, "peers": { "description": "The list of most recently accessed peers.\nThis is not an active connection table, nor is representative of the entire routing table.", "type": "array", @@ -4774,7 +4781,8 @@ "started", "bps_down", "bps_up", - "peers" + "peers", + "node_ids" ] }, "VeilidUpdate": { diff --git a/veilid-python/veilid/state.py b/veilid-python/veilid/state.py index 20677199..055cac16 100644 --- a/veilid-python/veilid/state.py +++ b/veilid-python/veilid/state.py @@ -7,7 +7,7 @@ from .types import ( BareRouteId, Timestamp, TimestampDuration, - PublicKey, + NodeId, RecordKey, ValueData, ValueSubkey, @@ -382,11 +382,11 @@ class PeerStats: class PeerTableData: - node_ids: list[str] + node_ids: list[NodeId] peer_address: str peer_stats: PeerStats - def __init__(self, node_ids: list[str], peer_address: str, peer_stats: PeerStats): + def __init__(self, node_ids: list[NodeId], peer_address: str, peer_stats: PeerStats): self.node_ids = node_ids self.peer_address = peer_address self.peer_stats = peer_stats @@ -394,7 +394,9 @@ class PeerTableData: @classmethod def from_json(cls, j: dict) -> Self: """JSON object hook""" - return cls(j["node_ids"], j["peer_address"], PeerStats.from_json(j["peer_stats"])) + return cls([NodeId(node_id) for node_id in j["node_ids"]], + j["peer_address"], + PeerStats.from_json(j["peer_stats"])) def to_json(self) -> dict: return self.__dict__ @@ -405,6 +407,7 @@ class VeilidStateNetwork: bps_down: ByteCount bps_up: ByteCount peers: list[PeerTableData] + node_ids: list[NodeId] def __init__( self, @@ -412,11 +415,13 @@ class VeilidStateNetwork: bps_down: ByteCount, bps_up: ByteCount, peers: list[PeerTableData], + node_ids: list[NodeId], ): self.started = started self.bps_down = bps_down self.bps_up = bps_up self.peers = peers + self.node_ids = node_ids @classmethod def from_json(cls, j: dict) -> Self: @@ -426,6 +431,7 @@ class VeilidStateNetwork: ByteCount(j["bps_down"]), ByteCount(j["bps_up"]), [PeerTableData.from_json(peer) for peer in j["peers"]], + [NodeId(node_id) for node_id in j["node_ids"]], ) def to_json(self) -> dict: @@ -495,11 +501,11 @@ class VeilidLog: class VeilidAppMessage: - sender: Optional[PublicKey] + sender: Optional[NodeId] route_id: Optional[BareRouteId] message: bytes - def __init__(self, sender: Optional[PublicKey], route_id: Optional[BareRouteId], message: bytes): + def __init__(self, sender: Optional[NodeId], route_id: Optional[BareRouteId], message: bytes): self.sender = sender self.route_id = route_id self.message = message @@ -508,7 +514,7 @@ class VeilidAppMessage: def from_json(cls, j: dict) -> Self: """JSON object hook""" return cls( - None if j["sender"] is None else PublicKey(j["sender"]), + None if j["sender"] is None else NodeId(j["sender"]), None if j["route_id"] is None else BareRouteId(j["route_id"]), urlsafe_b64decode_no_pad(j["message"]), ) @@ -518,12 +524,12 @@ class VeilidAppMessage: class VeilidAppCall: - sender: Optional[PublicKey] + sender: Optional[NodeId] route_id: Optional[BareRouteId] message: bytes call_id: OperationId - def __init__(self, sender: Optional[PublicKey], route_id: Optional[BareRouteId], message: bytes, call_id: OperationId): + def __init__(self, sender: Optional[NodeId], route_id: Optional[BareRouteId], message: bytes, call_id: OperationId): self.sender = sender self.route_id = route_id self.message = message @@ -533,7 +539,7 @@ class VeilidAppCall: def from_json(cls, j: dict) -> Self: """JSON object hook""" return cls( - None if j["sender"] is None else PublicKey(j["sender"]), + None if j["sender"] is None else NodeId(j["sender"]), None if j["route_id"] is None else BareRouteId(j["route_id"]), urlsafe_b64decode_no_pad(j["message"]), OperationId(j["call_id"]),