Compare commits
No commits in common. "full_refactor" and "main" have entirely different histories.
full_refac
...
main
3141
node/Cargo.lock
generated
@ -20,12 +20,18 @@ once_cell = "1.21.3"
|
|||||||
async-trait = "0.1.89"
|
async-trait = "0.1.89"
|
||||||
anyhow = "1.0.99"
|
anyhow = "1.0.99"
|
||||||
memory-stats = "1.2.0"
|
memory-stats = "1.2.0"
|
||||||
|
# jemalloc = "0.3.0"
|
||||||
|
# jemallocator = "0.5.4"
|
||||||
textwrap = "0.16.2"
|
textwrap = "0.16.2"
|
||||||
sled = "0.34.7"
|
sled = "0.34.7"
|
||||||
bincode = { version = "2.0.1", features = ["derive", "serde"] }
|
bincode = { version = "2.0.1", features = ["derive", "serde"] }
|
||||||
futures = "0.3.31"
|
futures = "0.3.31"
|
||||||
|
secp256k1 = { version = "0.31.1", features = ["hashes", "rand", "recovery", "serde"] }
|
||||||
|
ring = "0.17.14"
|
||||||
shared = { path = "../shared", features = ["node"] }
|
shared = { path = "../shared", features = ["node"] }
|
||||||
watchlet = { path = "../watchlet" }
|
watchlet = { path = "../watchlet" }
|
||||||
cli-renderer = { path = "../cli-renderer" }
|
cli-renderer = { path = "../cli-renderer" }
|
||||||
tiny_http = "0.12.0"
|
tiny_http = "0.12.0"
|
||||||
serde-big-array = "0.5.1"
|
serde-big-array = "0.5.1"
|
||||||
|
rust-ipfs = "0.14.1"
|
||||||
|
libp2p = "0.56.0"
|
||||||
|
|||||||
@ -1,9 +1,11 @@
|
|||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
use shared::blockchain_core::{self, Address, AddressParser};
|
use shared::blockchain_core;
|
||||||
use cli_renderer::RenderLayoutKind;
|
use cli_renderer::RenderLayoutKind;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
|
|
||||||
|
use clap::*;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
@ -12,7 +14,6 @@ pub struct Cli {
|
|||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
pub enum CliCommand {
|
pub enum CliCommand {
|
||||||
/// Ping a node
|
|
||||||
#[command(name = "ping")]
|
#[command(name = "ping")]
|
||||||
Ping {
|
Ping {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
@ -33,12 +34,12 @@ pub enum CliCommand {
|
|||||||
block_cmd: CliBlockCommand,
|
block_cmd: CliBlockCommand,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Award currency to wallet
|
|
||||||
#[command(name = "award")]
|
#[command(name = "award")]
|
||||||
Award {
|
Award {
|
||||||
#[clap(value_parser = AddressParser {})]
|
#[arg(short, long)]
|
||||||
address: Address,
|
|
||||||
amount: u64,
|
amount: u64,
|
||||||
|
#[arg(short, long)]
|
||||||
|
address: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Make a Transaction
|
/// Make a Transaction
|
||||||
@ -119,14 +120,14 @@ pub enum CliPingCommand {
|
|||||||
/// Ping Peer by Id
|
/// Ping Peer by Id
|
||||||
#[command(name = "id", aliases = ["i"])]
|
#[command(name = "id", aliases = ["i"])]
|
||||||
Id {
|
Id {
|
||||||
#[arg()]
|
#[arg(short, long)]
|
||||||
id: String,
|
id: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Ping Peer by Address
|
/// Ping Peer by Address
|
||||||
#[command(name = "addr", aliases = ["a", "ad"])]
|
#[command(name = "addr", aliases = ["a", "ad"])]
|
||||||
Addr {
|
Addr {
|
||||||
#[arg()]
|
#[arg(short, long)]
|
||||||
addr: String,
|
addr: String,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,19 +3,19 @@ use std::sync::Arc;
|
|||||||
use tokio::sync::broadcast;
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
use super::event_bus::EventBus;
|
use super::event_bus::EventBus;
|
||||||
use crate::watcher::WatcherCommand;
|
use crate::executor::ExecutorCommand;
|
||||||
|
|
||||||
pub enum ErrorEvent {
|
pub enum ErrorEvent {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static ERROR_BUS: Lazy<Arc<EventBus<WatcherCommand>>> =
|
static ERROR_BUS: Lazy<Arc<EventBus<ExecutorCommand>>> =
|
||||||
Lazy::new(|| Arc::new(EventBus::new()));
|
Lazy::new(|| Arc::new(EventBus::new()));
|
||||||
|
|
||||||
pub fn publish_error(event: WatcherCommand) {
|
pub fn publish_error(event: ExecutorCommand) {
|
||||||
ERROR_BUS.publish(event);
|
ERROR_BUS.publish(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn subscribe_error_bus() -> broadcast::Receiver<WatcherCommand> {
|
pub fn subscribe_error_bus() -> broadcast::Receiver<ExecutorCommand> {
|
||||||
ERROR_BUS.subscribe()
|
ERROR_BUS.subscribe()
|
||||||
}
|
}
|
||||||
|
|||||||
17
node/src/bus/executor.rs
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
|
use super::event_bus::EventBus;
|
||||||
|
use crate::executor::ExecutorCommand;
|
||||||
|
|
||||||
|
static EXECUTOR_EVENT_BUS: Lazy<Arc<EventBus<ExecutorCommand>>> =
|
||||||
|
Lazy::new(|| Arc::new(EventBus::new()));
|
||||||
|
|
||||||
|
pub fn publish_executor_event(event: ExecutorCommand) {
|
||||||
|
EXECUTOR_EVENT_BUS.publish(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subscribe_executor_event() -> broadcast::Receiver<ExecutorCommand> {
|
||||||
|
EXECUTOR_EVENT_BUS.subscribe()
|
||||||
|
}
|
||||||
@ -2,7 +2,7 @@ use crate::args::*;
|
|||||||
use crate::network::NodeId;
|
use crate::network::NodeId;
|
||||||
use shared::blockchain_core::ChainData;
|
use shared::blockchain_core::ChainData;
|
||||||
use vlogger::*;
|
use vlogger::*;
|
||||||
use crate::watcher::WatcherCommand;
|
use crate::executor::ExecutorCommand;
|
||||||
use crate::node::*;
|
use crate::node::*;
|
||||||
use crate::log;
|
use crate::log;
|
||||||
use cli_renderer::RenderCommand;
|
use cli_renderer::RenderCommand;
|
||||||
@ -46,34 +46,37 @@ fn handle_ping(cmd: CliPingCommand) -> NodeCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cli(input: &str) -> WatcherCommand {
|
pub fn cli(input: &str) -> ExecutorCommand {
|
||||||
let argv: Vec<&str> = std::iter::once(" ")
|
let argv: Vec<&str> = std::iter::once(" ")
|
||||||
.chain(input.split_whitespace())
|
.chain(input.split_whitespace())
|
||||||
.collect();
|
.collect();
|
||||||
match Cli::try_parse_from(argv) {
|
match Cli::try_parse_from(argv) {
|
||||||
Ok(cmd) => match cmd.command {
|
Ok(cmd) => match cmd.command {
|
||||||
CliCommand::Layout { mode } => WatcherCommand::Render(RenderCommand::ChangeLayout(mode)),
|
CliCommand::Layout { mode } => ExecutorCommand::Render(RenderCommand::ChangeLayout(mode)),
|
||||||
CliCommand::Clear => WatcherCommand::Render(RenderCommand::ClearPane),
|
CliCommand::Clear => ExecutorCommand::Render(RenderCommand::ClearPane),
|
||||||
CliCommand::Peer { peer_cmd } => WatcherCommand::Node(handle_peer_command(peer_cmd)),
|
CliCommand::Peer { peer_cmd } => ExecutorCommand::Node(handle_peer_command(peer_cmd)),
|
||||||
CliCommand::Block { block_cmd } => WatcherCommand::Node(handle_block_command(block_cmd)),
|
CliCommand::Block { block_cmd } => ExecutorCommand::Node(handle_block_command(block_cmd)),
|
||||||
CliCommand::Transaction(tx) => {
|
CliCommand::Transaction(tx) => {
|
||||||
WatcherCommand::Node(NodeCommand::ProcessChainData(ChainData::NodeTransaction(tx)))
|
ExecutorCommand::Node(NodeCommand::ProcessChainData(ChainData::NodeTransaction(tx)))
|
||||||
}
|
}
|
||||||
CliCommand::Award { address, amount } => {
|
CliCommand::Award { address, amount } => {
|
||||||
log(msg!(DEBUG, "Received address: {:?}", address));
|
let mut bytes = [0u8; 20];
|
||||||
if address.len() != 20 {
|
if address.len() != 20 {
|
||||||
log(msg!(ERROR, "Invalid address length"))
|
log(msg!(ERROR, "Invalid address length"))
|
||||||
|
} else if !address.is_ascii() {
|
||||||
|
log(msg!(ERROR, "Invalid address content"))
|
||||||
}
|
}
|
||||||
|
|
||||||
WatcherCommand::Node(NodeCommand::AwardCurrency{ address, amount }
|
bytes.copy_from_slice(address.as_bytes());
|
||||||
|
ExecutorCommand::Node(NodeCommand::AwardCurrency{ address: bytes, amount }
|
||||||
)}
|
)}
|
||||||
CliCommand::DebugShowId => WatcherCommand::Node(NodeCommand::ShowId),
|
CliCommand::DebugShowId => ExecutorCommand::Node(NodeCommand::ShowId),
|
||||||
CliCommand::StartListner { addr } => {
|
CliCommand::StartListner { addr } => {
|
||||||
WatcherCommand::Node(NodeCommand::StartListner(addr.parse().unwrap()))
|
ExecutorCommand::Node(NodeCommand::StartListner(addr.parse().unwrap()))
|
||||||
}
|
}
|
||||||
CliCommand::Seeds { seed_cmd } => WatcherCommand::Node(handle_seed_command(seed_cmd)),
|
CliCommand::Seeds { seed_cmd } => ExecutorCommand::Node(handle_seed_command(seed_cmd)),
|
||||||
CliCommand::Ping { ping_cmd } => WatcherCommand::Node(handle_ping(ping_cmd)),
|
CliCommand::Ping { ping_cmd } => ExecutorCommand::Node(handle_ping(ping_cmd)),
|
||||||
},
|
},
|
||||||
Err(e) => WatcherCommand::InvalidCommand(format!("{e}")),
|
Err(e) => ExecutorCommand::InvalidCommand(format!("{e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
15
node/src/executor/command.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
use crate::node::NodeCommand;
|
||||||
|
use cli_renderer::RenderCommand;
|
||||||
|
use crate::watcher::WatcherCommand;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum ExecutorCommand {
|
||||||
|
NodeResponse(String),
|
||||||
|
Echo(Vec<String>),
|
||||||
|
Print(String),
|
||||||
|
InvalidCommand(String),
|
||||||
|
Node(NodeCommand),
|
||||||
|
Render(RenderCommand),
|
||||||
|
Watcher(WatcherCommand),
|
||||||
|
Exit,
|
||||||
|
}
|
||||||
106
node/src/executor/executor.rs
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
use crate::{
|
||||||
|
bus::{publish_system_event, publish_watcher_event, subscribe_system_event, SystemEvent},
|
||||||
|
log,
|
||||||
|
node::NodeCommand,
|
||||||
|
watcher::WatcherCommand,
|
||||||
|
};
|
||||||
|
|
||||||
|
use cli_renderer::pane::RenderTarget;
|
||||||
|
use thiserror::Error;
|
||||||
|
use tokio::{select, sync::mpsc};
|
||||||
|
use vlogger::*;
|
||||||
|
|
||||||
|
use super::ExecutorCommand;
|
||||||
|
use crate::RenderCommand;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum InProcessError {
|
||||||
|
#[error("TODO: {0}")]
|
||||||
|
TODO(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Executor {
|
||||||
|
node_tx: mpsc::Sender<NodeCommand>,
|
||||||
|
rx: mpsc::Receiver<ExecutorCommand>,
|
||||||
|
exit: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Executor {
|
||||||
|
pub fn new(node_tx: mpsc::Sender<NodeCommand>, rx: mpsc::Receiver<ExecutorCommand>) -> Self {
|
||||||
|
Self {
|
||||||
|
node_tx,
|
||||||
|
rx,
|
||||||
|
exit: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(&mut self) {
|
||||||
|
publish_system_event(SystemEvent::ExecutorStarted);
|
||||||
|
let mut sys_rx = subscribe_system_event();
|
||||||
|
while !self.exit {
|
||||||
|
select! {
|
||||||
|
_ = self.listen() => {}
|
||||||
|
event_res = sys_rx.recv() => {
|
||||||
|
if let Ok(event) = event_res {
|
||||||
|
match event {
|
||||||
|
SystemEvent::Shutdown => {
|
||||||
|
self.exit().await;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn exit(&mut self) {
|
||||||
|
log(msg!(DEBUG, "Executor Exit"));
|
||||||
|
self.exit = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn listen(&mut self) {
|
||||||
|
if let Some(cmd) = self.rx.recv().await {
|
||||||
|
let _ = self.execute(cmd).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_node_cmd(&self, cmd: NodeCommand) {
|
||||||
|
self.node_tx.send(cmd).await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_node_cmd(&self, cmd: NodeCommand) {
|
||||||
|
self.send_node_cmd(cmd).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn echo(&self, s: Vec<String>) {
|
||||||
|
let mut str = s.join(" ");
|
||||||
|
str.push_str("\n");
|
||||||
|
let rd_cmd = WatcherCommand::Render(RenderCommand::StringToPaneId {
|
||||||
|
str,
|
||||||
|
pane: RenderTarget::CliOutput,
|
||||||
|
});
|
||||||
|
publish_watcher_event(rd_cmd);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn invalid_command(&self, str: String) {
|
||||||
|
let rd_cmd = WatcherCommand::Render(RenderCommand::StringToPaneId {
|
||||||
|
str,
|
||||||
|
pane: RenderTarget::CliOutput,
|
||||||
|
});
|
||||||
|
publish_watcher_event(rd_cmd);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(&mut self, cmd: ExecutorCommand) {
|
||||||
|
match cmd {
|
||||||
|
ExecutorCommand::NodeResponse(resp) => log(resp),
|
||||||
|
ExecutorCommand::Node(n) => self.handle_node_cmd(n).await,
|
||||||
|
ExecutorCommand::Render(p) => publish_watcher_event(WatcherCommand::Render(p)),
|
||||||
|
ExecutorCommand::Watcher(w) => publish_watcher_event(w),
|
||||||
|
ExecutorCommand::Echo(s) => self.echo(s).await,
|
||||||
|
ExecutorCommand::Print(s) => log(s),
|
||||||
|
ExecutorCommand::InvalidCommand(str) => self.invalid_command(str).await,
|
||||||
|
ExecutorCommand::Exit => self.exit().await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -41,11 +41,20 @@ pub mod bus {
|
|||||||
pub mod system;
|
pub mod system;
|
||||||
|
|
||||||
pub use error::*;
|
pub use error::*;
|
||||||
|
pub mod executor;
|
||||||
pub use network::*;
|
pub use network::*;
|
||||||
pub use watcher::*;
|
pub use watcher::*;
|
||||||
pub use system::*;
|
pub use system::*;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod executor {
|
||||||
|
pub mod executor;
|
||||||
|
pub use executor::*;
|
||||||
|
|
||||||
|
pub mod command;
|
||||||
|
pub use command::*;
|
||||||
|
}
|
||||||
|
|
||||||
pub mod watcher {
|
pub mod watcher {
|
||||||
pub mod builder;
|
pub mod builder;
|
||||||
pub mod watcher;
|
pub mod watcher;
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
use crate::{log, watcher};
|
use crate::executor::ExecutorCommand;
|
||||||
|
use crate::log;
|
||||||
use crate::network::NodeId;
|
use crate::network::NodeId;
|
||||||
use crate::node::node;
|
use crate::node::node;
|
||||||
use super::ProtocolMessage;
|
use super::ProtocolMessage;
|
||||||
use tokio::net;
|
use tokio::net;
|
||||||
use futures::stream::Stream;
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use super::Connector;
|
use super::Connector;
|
||||||
|
|
||||||
@ -14,50 +15,76 @@ use vlogger::*;
|
|||||||
pub struct Connection {
|
pub struct Connection {
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
peer_id: NodeId,
|
peer_id: NodeId,
|
||||||
r_stream: net::tcp::OwnedReadHalf,
|
stream: net::TcpStream,
|
||||||
}
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
|
rx: mpsc::Receiver<ProtocolMessage>,
|
||||||
impl Stream for Connection {
|
|
||||||
type Item = (NodeId, Option<ProtocolMessage>);
|
|
||||||
|
|
||||||
fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
|
|
||||||
todo!("Impl poll next")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Connection {
|
impl Connection {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
peer_id: NodeId,
|
peer_id: NodeId,
|
||||||
r_stream: net::tcp::OwnedReadHalf,
|
stream: net::TcpStream,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
|
rx: mpsc::Receiver<ProtocolMessage>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
node_id,
|
node_id,
|
||||||
peer_id,
|
peer_id,
|
||||||
r_stream,
|
stream,
|
||||||
|
rx,
|
||||||
|
exec_tx,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn poll(mut self) {
|
pub async fn start(mut self) {
|
||||||
|
tokio::spawn(async move {
|
||||||
log(msg!(DEBUG, "Started Message Handler for {}", self.peer_id));
|
log(msg!(DEBUG, "Started Message Handler for {}", self.peer_id));
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
message_result = Connector::receive_message(&mut self.r_stream) => {
|
response_result = self.rx.recv() => {
|
||||||
|
match response_result {
|
||||||
|
Some(response) => {
|
||||||
|
if let Err(e) = Connector::send_message(&mut self.stream, &response).await {
|
||||||
|
log(msg!(ERROR, "Failed to send response to {}: {}", self.peer_id.clone(), e));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
log(msg!(DEBUG, "Response channel closed for {}", self.peer_id));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message_result = Connector::receive_message(&mut self.stream) => {
|
||||||
match message_result {
|
match message_result {
|
||||||
Ok(message) => {
|
Ok(message) => {
|
||||||
todo!("[TODO] Return parsed command to propagate");
|
log(msg!(DEBUG, "Received Message from {}", self.peer_id));
|
||||||
|
|
||||||
|
let command = ExecutorCommand::Node(node::NodeCommand::ProcessMessage {
|
||||||
|
peer_id: self.peer_id.clone(),
|
||||||
|
message: message.clone()
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.exec_tx.send(command).await.is_err() {
|
||||||
|
log(msg!(ERROR, "Failed to send command to main thread from {}", self.peer_id));
|
||||||
|
break;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log(msg!(WARNING, "Connection to {} closed: {}", self.peer_id, e));
|
log(msg!(WARNING, "Connection to {} closed: {}", self.peer_id, e));
|
||||||
let cmd = watcher::WatcherCommand::Node(node::NodeCommand::RemovePeer {
|
let cmd = ExecutorCommand::Node(node::NodeCommand::RemovePeer {
|
||||||
peer_id: self.peer_id
|
peer_id: self.peer_id
|
||||||
});
|
});
|
||||||
todo!("[TODO] Return Error Node Command to propagate");
|
self.exec_tx.send(cmd).await.unwrap();
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,18 +1,20 @@
|
|||||||
use futures::stream::{ StreamExt, SelectAll };
|
use anyhow::Context;
|
||||||
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net;
|
use tokio::net;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
use vlogger::*;
|
use vlogger::*;
|
||||||
use shared::print_error_chain;
|
use shared::print_error_chain;
|
||||||
use thiserror::*;
|
use thiserror::*;
|
||||||
|
|
||||||
use crate::db::BINCODE_CONFIG;
|
use crate::db::BINCODE_CONFIG;
|
||||||
use crate::log;
|
use crate::log;
|
||||||
use crate::network::{NodeId, ProtocolError};
|
use crate::network::NodeId;
|
||||||
use super::Connection;
|
use super::Connection;
|
||||||
use crate::bus::*;
|
use crate::bus::*;
|
||||||
|
use crate::executor::ExecutorCommand;
|
||||||
use crate::node::node;
|
use crate::node::node;
|
||||||
|
use crate::node::{NetworkError, error};
|
||||||
use super::ProtocolMessage;
|
use super::ProtocolMessage;
|
||||||
|
|
||||||
pub enum ConnectorCommand {
|
pub enum ConnectorCommand {
|
||||||
@ -24,27 +26,15 @@ pub enum ConnectorCommand {
|
|||||||
pub struct Connector {
|
pub struct Connector {
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
connections: Vec<Connection>,
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
peer_streams: Vec<(NodeId, OwnedWriteHalf)>,
|
rx: mpsc::Receiver<ConnectorCommand>,
|
||||||
streams: SelectAll<Connection>,
|
|
||||||
listener: Option<tokio::net::TcpListener>,
|
|
||||||
exit: bool,
|
exit: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum ConnectorError {
|
pub enum ConnectorError {
|
||||||
#[error("Connection failed")]
|
#[error("Connection failed")]
|
||||||
IO(#[from] std::io::Error),
|
ConnectionError(#[from] anyhow::Error),
|
||||||
#[error("Decode Error: {0}")]
|
|
||||||
Decode(#[from] bincode::error::DecodeError),
|
|
||||||
#[error("Encode Error: {0}")]
|
|
||||||
Encode(#[from] bincode::error::EncodeError),
|
|
||||||
#[error("Protocol Error: {0}")]
|
|
||||||
Protocol(#[from] crate::network::message::ProtocolError),
|
|
||||||
#[error("Unkown Peer Id: {0}")]
|
|
||||||
UnknownPeerId(NodeId),
|
|
||||||
#[error("Unkown Peer Address: {0}")]
|
|
||||||
UnknownPeerAddr(SocketAddr),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_LISTNER_TRIES: usize = 5;
|
const MAX_LISTNER_TRIES: usize = 5;
|
||||||
@ -53,64 +43,57 @@ impl Connector {
|
|||||||
pub fn new(
|
pub fn new(
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
|
rx: mpsc::Receiver<ConnectorCommand>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
node_id,
|
node_id,
|
||||||
addr,
|
addr,
|
||||||
connections: Vec::new(),
|
exec_tx,
|
||||||
peer_streams: Vec::new(),
|
rx,
|
||||||
streams: SelectAll::new(),
|
|
||||||
listener: None,
|
|
||||||
exit: false,
|
exit: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn init(&mut self) {
|
pub async fn start(&mut self) {
|
||||||
|
let mut listner: Option<tokio::net::TcpListener> = None;
|
||||||
|
let mut listner_err = None;
|
||||||
for _ in 0..MAX_LISTNER_TRIES {
|
for _ in 0..MAX_LISTNER_TRIES {
|
||||||
match tokio::net::TcpListener::bind(self.addr).await {
|
match tokio::net::TcpListener::bind(self.addr).await {
|
||||||
Ok(l) => {
|
Ok(l) => {
|
||||||
log(msg!(DEBUG, "Listening on address: {}", self.addr));
|
log(msg!(DEBUG, "Listening on address: {}", self.addr));
|
||||||
self.listener = Some(l);
|
listner = Some(l);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
self.addr.set_port(self.addr.port() + 1);
|
self.addr.set_port(self.addr.port() + 1);
|
||||||
let listner_err = Some(e);
|
listner_err = Some(e);
|
||||||
println!("{:#?}", listner_err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
if let Some(listener) = listner {
|
||||||
|
while !self.exit {
|
||||||
pub async fn poll(&mut self) -> Result<Option<node::NodeCommand>, ConnectorError> {
|
|
||||||
if let Some(listener) = &mut self.listener {
|
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
protocol_message = self.streams.next() => {
|
cmd_result = self.rx.recv() => {
|
||||||
todo!("Implement protocol message");
|
match cmd_result {
|
||||||
|
Some(cmd) => {
|
||||||
|
self.execute_cmd(cmd).await;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
log(msg!(DEBUG, "Command channel closed"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// cmd_result = self.rx.recv() => {
|
|
||||||
// todo!("Implement Vec Poll for connections");
|
|
||||||
// match cmd_result {
|
|
||||||
// Some(cmd) => {
|
|
||||||
// self.execute_cmd(cmd).await
|
|
||||||
// }
|
|
||||||
// None => {
|
|
||||||
// log(msg!(DEBUG, "Command channel closed"));
|
|
||||||
// todo!("Handle Connector Error");
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
accept_result = listener.accept() => {
|
accept_result = listener.accept() => {
|
||||||
match accept_result {
|
match accept_result {
|
||||||
Ok((stream, addr)) => {
|
Ok((stream, addr)) => {
|
||||||
log(msg!(DEBUG, "Accepted connection from {}", addr));
|
log(msg!(DEBUG, "Accepted connection from {}", addr));
|
||||||
let peer = self.establish_connection_inbound(stream, addr).await?;
|
self.establish_connection_inbound(stream, addr).await;
|
||||||
Ok(Some(node::NodeCommand::AddPeer(peer)))
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log(msg!(ERROR, "Failed to accept connection: {}", e));
|
log(msg!(ERROR, "Failed to accept connection: {}", e));
|
||||||
todo!("Implement Connector TcpListner connection fail");
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -118,178 +101,194 @@ impl Connector {
|
|||||||
} else {
|
} else {
|
||||||
log(msg!(
|
log(msg!(
|
||||||
FATAL,
|
FATAL,
|
||||||
"Failed to start TCP Listener",
|
"Failed to start TCP Listener: {}",
|
||||||
|
listner_err.unwrap()
|
||||||
));
|
));
|
||||||
todo!("Implement Connector TcpListner fail");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn command(&mut self, cmd: ConnectorCommand) -> Result<Option<node::NodeCommand>, ConnectorError> {
|
async fn execute_cmd(&mut self, cmd: ConnectorCommand) {
|
||||||
match cmd {
|
match cmd {
|
||||||
ConnectorCommand::ConnectToTcpPeer(addr) => {
|
ConnectorCommand::ConnectToTcpPeer(addr) => self.connect_to_peer(addr).await,
|
||||||
let peer = self.connect_to_peer(addr).await?;
|
|
||||||
Ok(Some(node::NodeCommand::AddPeer(peer)))
|
|
||||||
},
|
|
||||||
ConnectorCommand::ConnectToTcpSeed(addr) => {
|
ConnectorCommand::ConnectToTcpSeed(addr) => {
|
||||||
let peer = self.connect_to_seed(addr).await?;
|
self.connect_to_seed(addr).await;
|
||||||
Ok(Some(node::NodeCommand::AddPeer(peer)))
|
|
||||||
}
|
}
|
||||||
ConnectorCommand::Shutdown => {
|
ConnectorCommand::Shutdown => {
|
||||||
self.exit = true;
|
self.exit = true;
|
||||||
Ok(None)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn connect_to_seed(&mut self, addr: SocketAddr) -> Result<node::TcpPeer, ConnectorError> {
|
pub async fn connect_to_seed(&self, addr: SocketAddr) {
|
||||||
match net::TcpStream::connect(addr)
|
match net::TcpStream::connect(addr)
|
||||||
.await
|
.await
|
||||||
|
.with_context(|| format!("Connecting to {}", addr))
|
||||||
{
|
{
|
||||||
Ok(stream) => {
|
Ok(stream) => self.establish_connection_to_seed(stream, addr).await,
|
||||||
let peer = self.establish_connection_outbound(stream, addr).await;
|
|
||||||
publish_network_event(NetworkEvent::SeedConnected(addr.to_string()));
|
|
||||||
peer
|
|
||||||
},
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let err = ConnectorError::IO(e);
|
// let err = ConnectorError::ConnectionError(e.into());
|
||||||
Err(err)
|
print_error_chain(&e.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn connect_to_peer_inbound(&mut self, addr: SocketAddr) -> Result<node::TcpPeer, ConnectorError> {
|
pub async fn connect_to_peer(&self, addr: SocketAddr) {
|
||||||
match net::TcpStream::connect(addr).await {
|
|
||||||
Ok(stream) => self.establish_connection_inbound(stream, addr).await,
|
|
||||||
Err(e) => {
|
|
||||||
let err = ConnectorError::IO(e);
|
|
||||||
Err(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn connect_to_peer(&mut self, addr: SocketAddr) -> Result<node::TcpPeer, ConnectorError> {
|
|
||||||
match net::TcpStream::connect(addr).await {
|
match net::TcpStream::connect(addr).await {
|
||||||
Ok(stream) => self.establish_connection_outbound(stream, addr).await,
|
Ok(stream) => self.establish_connection_outbound(stream, addr).await,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let err = ConnectorError::IO(e);
|
let err = ConnectorError::ConnectionError(e.into());
|
||||||
Err(err)
|
print_error_chain(&err.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn establish_connection_outbound(
|
pub async fn establish_connection_to_seed(
|
||||||
&mut self,
|
&self,
|
||||||
stream: tokio::net::TcpStream,
|
mut stream: tokio::net::TcpStream,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
) -> Result<node::TcpPeer, ConnectorError> {
|
) {
|
||||||
let (mut r_stream, mut w_stream) = stream.into_split();
|
|
||||||
let handshake = ProtocolMessage::Handshake {
|
let handshake = ProtocolMessage::Handshake {
|
||||||
peer_id: self.node_id.clone(),
|
peer_id: self.node_id.clone(),
|
||||||
version: "".to_string(),
|
version: "".to_string(),
|
||||||
};
|
};
|
||||||
match Connector::send_message(&mut w_stream, &handshake).await {
|
match Connector::send_message(&mut stream, &handshake).await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
if let Ok(mes) = Connector::receive_message(&mut r_stream).await {
|
if let Ok(mes) = Connector::receive_message(&mut stream).await {
|
||||||
|
let (ch_tx, ch_rx) = mpsc::channel::<ProtocolMessage>(100);
|
||||||
let peer = match mes {
|
let peer = match mes {
|
||||||
ProtocolMessage::HandshakeAck { peer_id, .. } => {
|
ProtocolMessage::HandshakeAck { peer_id, .. } => {
|
||||||
node::TcpPeer::new(peer_id, addr)
|
node::TcpPeer::new(peer_id, addr, ch_tx)
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
log(msg!(
|
log(msg!(
|
||||||
ERROR,
|
ERROR,
|
||||||
"Invalid Message On Connetion Establishment: {mes}"
|
"Invalid Message On Connetion Establishment: {mes}"
|
||||||
));
|
));
|
||||||
todo!("Handle connector receive message fail");
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), r_stream);
|
let cmd = ExecutorCommand::Node(node::NodeCommand::AddPeer(peer.clone()));
|
||||||
self.connections.push(connection);
|
publish_network_event(NetworkEvent::SeedConnected(addr.to_string()));
|
||||||
Ok(peer)
|
let _ = self.exec_tx.send(cmd).await;
|
||||||
} else {
|
Connection::new(self.node_id.clone(), peer.id, stream, self.exec_tx.clone(), ch_rx)
|
||||||
todo!("Handle connector receive message fail");
|
.start()
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => print_error_chain(&e.into()),
|
||||||
print_error_chain(&e.into());
|
}
|
||||||
todo!("Handle Connector Error");
|
}
|
||||||
},
|
|
||||||
|
async fn establish_connection_outbound(
|
||||||
|
&self,
|
||||||
|
mut stream: tokio::net::TcpStream,
|
||||||
|
addr: SocketAddr,
|
||||||
|
) {
|
||||||
|
let handshake = ProtocolMessage::Handshake {
|
||||||
|
peer_id: self.node_id.clone(),
|
||||||
|
version: "".to_string(),
|
||||||
|
};
|
||||||
|
match Connector::send_message(&mut stream, &handshake).await {
|
||||||
|
Ok(()) => {
|
||||||
|
if let Ok(mes) = Connector::receive_message(&mut stream).await {
|
||||||
|
let (ch_tx, ch_rx) = mpsc::channel::<ProtocolMessage>(100);
|
||||||
|
let peer = match mes {
|
||||||
|
ProtocolMessage::HandshakeAck { peer_id, .. } => {
|
||||||
|
node::TcpPeer::new(peer_id, addr, ch_tx)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log(msg!(
|
||||||
|
ERROR,
|
||||||
|
"Invalid Message On Connetion Establishment: {mes}"
|
||||||
|
));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let cmd = ExecutorCommand::Node(node::NodeCommand::AddPeer(peer.clone()));
|
||||||
|
let _ = self.exec_tx.send(cmd).await;
|
||||||
|
Connection::new(self.node_id.clone(), peer.id, stream, self.exec_tx.clone(), ch_rx)
|
||||||
|
.start()
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error_chain(&e.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn establish_connection_inbound(
|
async fn establish_connection_inbound(
|
||||||
&mut self,
|
&self,
|
||||||
stream: tokio::net::TcpStream,
|
mut stream: tokio::net::TcpStream,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
) -> Result<node::TcpPeer, ConnectorError> {
|
) {
|
||||||
let (mut r_stream, mut w_stream) = stream.into_split();
|
if let Ok(mes) = Connector::receive_message(&mut stream).await {
|
||||||
let mes = Connector::receive_message(&mut r_stream).await?;
|
let (ch_tx, ch_rx) = mpsc::channel::<ProtocolMessage>(100);
|
||||||
let peer = match mes {
|
let peer = match mes {
|
||||||
ProtocolMessage::Handshake { peer_id, .. } => {
|
ProtocolMessage::Handshake { peer_id, .. } => {
|
||||||
let ack = ProtocolMessage::HandshakeAck {
|
let ack = ProtocolMessage::HandshakeAck {
|
||||||
peer_id: self.node_id.clone(),
|
peer_id: self.node_id.clone(),
|
||||||
version: "".to_string(),
|
version: "".to_string(),
|
||||||
};
|
};
|
||||||
Connector::send_message(&mut w_stream, &ack).await?;
|
match Connector::send_message(&mut stream, &ack).await {
|
||||||
node::TcpPeer::new(peer_id, addr)
|
Ok(()) => node::TcpPeer::new(peer_id, addr, ch_tx),
|
||||||
|
Err(e) => return print_error_chain(&e.into()),
|
||||||
}
|
}
|
||||||
e => {
|
}
|
||||||
return Err(ConnectorError::Protocol(ProtocolError::Unexpected(e)));
|
_ => {
|
||||||
|
log(msg!(
|
||||||
|
ERROR,
|
||||||
|
"Invalid Message On Connetion Establishment: {mes}"
|
||||||
|
));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), r_stream);
|
let cmd = ExecutorCommand::Node(node::NodeCommand::AddPeer(peer.clone()));
|
||||||
self.connections.push(connection);
|
let _ = self.exec_tx.send(cmd).await;
|
||||||
Ok(peer)
|
Connection::new(self.node_id.clone(), peer.id, stream, self.exec_tx.clone(), ch_rx)
|
||||||
}
|
.start()
|
||||||
|
.await;
|
||||||
pub async fn send_message_to_peer(&mut self, peer_id: NodeId, message: &ProtocolMessage) -> Result<(), ConnectorError> {
|
|
||||||
if let Some((_, w_stream)) = &mut self.peer_streams.iter_mut().find(|p| p.0 == peer_id) {
|
|
||||||
Connector::send_message(w_stream, message).await
|
|
||||||
} else {
|
|
||||||
Err(ConnectorError::UnknownPeerId(peer_id))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_message(
|
pub async fn send_message(
|
||||||
stream: &mut net::tcp::OwnedWriteHalf,
|
stream: &mut net::TcpStream,
|
||||||
message: &ProtocolMessage,
|
message: &ProtocolMessage,
|
||||||
) -> Result<(), ConnectorError> {
|
) -> Result<(), NetworkError> {
|
||||||
let data = bincode::encode_to_vec(message, BINCODE_CONFIG)?;
|
let data = bincode::encode_to_vec(message, BINCODE_CONFIG)?;
|
||||||
|
|
||||||
let len = data.len() as u32;
|
let len = data.len() as u32;
|
||||||
|
|
||||||
stream
|
stream
|
||||||
.write_all(&len.to_be_bytes())
|
.write_all(&len.to_be_bytes())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ConnectorError::IO(e))?;
|
.map_err(|_e| NetworkError::TODO)?;
|
||||||
|
|
||||||
stream
|
stream
|
||||||
.write_all(&data)
|
.write_all(&data)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ConnectorError::IO(e))?;
|
.map_err(|_e| NetworkError::TODO)?;
|
||||||
stream.flush().await.map_err(|e| ConnectorError::IO(e))?;
|
stream.flush().await.map_err(|_e| NetworkError::TODO)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn receive_message(
|
pub async fn receive_message(
|
||||||
stream: &mut OwnedReadHalf,
|
stream: &mut tokio::net::TcpStream,
|
||||||
) -> Result<ProtocolMessage, ConnectorError> {
|
) -> Result<ProtocolMessage, error::NetworkError> {
|
||||||
let mut len_bytes = [0u8; 4];
|
let mut len_bytes = [0u8; 4];
|
||||||
stream
|
stream
|
||||||
.read_exact(&mut len_bytes)
|
.read_exact(&mut len_bytes)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ConnectorError::IO(e))?;
|
.map_err(|_e| NetworkError::TODO)?;
|
||||||
|
|
||||||
let len = u32::from_be_bytes(len_bytes) as usize;
|
let len = u32::from_be_bytes(len_bytes) as usize;
|
||||||
|
|
||||||
if len >= super::message::MAX_MESSAGE_SIZE {
|
if len >= super::message::MAX_MESSAGE_SIZE {
|
||||||
return Err(ConnectorError::Protocol(ProtocolError::MessageTooLong(len)));
|
return Err(NetworkError::TODO);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut data = vec![0u8; len];
|
let mut data = vec![0u8; len];
|
||||||
stream
|
stream
|
||||||
.read_exact(&mut data)
|
.read_exact(&mut data)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ConnectorError::IO(e))?;
|
.map_err(|_e| NetworkError::TODO)?;
|
||||||
|
|
||||||
let (message, _): (ProtocolMessage, usize) = bincode::decode_from_slice(&data, BINCODE_CONFIG)?;
|
let (message, _): (ProtocolMessage, usize) = bincode::decode_from_slice(&data, BINCODE_CONFIG)?;
|
||||||
|
|
||||||
|
|||||||
@ -4,17 +4,9 @@ use std::net::SocketAddr;
|
|||||||
|
|
||||||
pub const MAX_MESSAGE_SIZE: usize = 1_000_000;
|
pub const MAX_MESSAGE_SIZE: usize = 1_000_000;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, bincode::Encode, bincode::Decode, Hash, PartialEq, Eq)]
|
#[derive(Debug, Clone, bincode::Encode, bincode::Decode, Hash, PartialEq, Eq)]
|
||||||
pub struct NodeId(pub [u8; 16]);
|
pub struct NodeId(pub [u8; 16]);
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
pub enum ProtocolError {
|
|
||||||
#[error("Invalid message len: {0}")]
|
|
||||||
MessageTooLong(usize),
|
|
||||||
#[error("Unexpected message: {0}")]
|
|
||||||
Unexpected(ProtocolMessage)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
|
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
|
||||||
pub enum ProtocolMessage {
|
pub enum ProtocolMessage {
|
||||||
BootstrapRequest {
|
BootstrapRequest {
|
||||||
@ -60,7 +52,8 @@ pub enum ProtocolMessage {
|
|||||||
|
|
||||||
impl fmt::Display for NodeId {
|
impl fmt::Display for NodeId {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "{}", hex::encode(self.0))
|
let msg = self.to_string();
|
||||||
|
write!(f, "{}", msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
4
node/src/network/temp/conf
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
segment_size: 1048576
|
||||||
|
use_compression: false
|
||||||
|
version: 0.34
|
||||||
|
l–ø
|
||||||
BIN
node/src/network/temp/db
Normal file
4
node/src/network/temp1/conf
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
segment_size: 1048576
|
||||||
|
use_compression: false
|
||||||
|
version: 0.34
|
||||||
|
l–ø
|
||||||
BIN
node/src/network/temp1/db
Normal file
@ -13,7 +13,7 @@ use shared::ws_protocol::{ WsClientRequest, WsClientResponse };
|
|||||||
use watchlet::WalletError;
|
use watchlet::WalletError;
|
||||||
|
|
||||||
use crate::db::BINCODE_CONFIG;
|
use crate::db::BINCODE_CONFIG;
|
||||||
use crate::watcher::WatcherCommand;
|
use crate::executor::ExecutorCommand;
|
||||||
use crate::log;
|
use crate::log;
|
||||||
use crate::node::NodeCommand;
|
use crate::node::NodeCommand;
|
||||||
use crate::seeds_constants::WS_LISTEN_ADDRESS;
|
use crate::seeds_constants::WS_LISTEN_ADDRESS;
|
||||||
@ -46,13 +46,13 @@ pub enum WsServerError {
|
|||||||
|
|
||||||
pub struct WsServer {
|
pub struct WsServer {
|
||||||
rx: Receiver<WsCommand>,
|
rx: Receiver<WsCommand>,
|
||||||
tx: Sender<WatcherCommand>,
|
tx: Sender<ExecutorCommand>,
|
||||||
clients: HashMap<SocketAddr, Sender<WsClientResponse>>,
|
clients: HashMap<SocketAddr, Sender<WsClientResponse>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_ws_client_request(
|
async fn handle_ws_client_request(
|
||||||
req: WsClientRequest,
|
req: WsClientRequest,
|
||||||
_tx: Sender<WatcherCommand>,
|
_tx: Sender<ExecutorCommand>,
|
||||||
) -> Result<(), WsServerError> {
|
) -> Result<(), WsServerError> {
|
||||||
match req {
|
match req {
|
||||||
WsClientRequest::Ping => {
|
WsClientRequest::Ping => {
|
||||||
@ -61,7 +61,7 @@ async fn handle_ws_client_request(
|
|||||||
}
|
}
|
||||||
WsClientRequest::BroadcastTransaction(sign_tx) => {
|
WsClientRequest::BroadcastTransaction(sign_tx) => {
|
||||||
Validator::verify_signature(&sign_tx)?;
|
Validator::verify_signature(&sign_tx)?;
|
||||||
let _cmd = WatcherCommand::Node(NodeCommand::BroadcastTransaction(sign_tx));
|
let _cmd = ExecutorCommand::Node(NodeCommand::BroadcastTransaction(sign_tx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -70,7 +70,7 @@ async fn handle_ws_client_request(
|
|||||||
async fn ws_connection(
|
async fn ws_connection(
|
||||||
stream: TcpStream,
|
stream: TcpStream,
|
||||||
mut rx: Receiver<WsClientResponse>,
|
mut rx: Receiver<WsClientResponse>,
|
||||||
_tx: Sender<WatcherCommand>,
|
_tx: Sender<ExecutorCommand>,
|
||||||
) -> Result<(), WsServerError> {
|
) -> Result<(), WsServerError> {
|
||||||
let ws_server = tokio_tungstenite::accept_async(stream).await.unwrap();
|
let ws_server = tokio_tungstenite::accept_async(stream).await.unwrap();
|
||||||
let (mut write, mut read) = ws_server.split();
|
let (mut write, mut read) = ws_server.split();
|
||||||
@ -101,7 +101,7 @@ async fn ws_connection(
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WsServer {
|
impl WsServer {
|
||||||
pub fn new(rx: Receiver<WsCommand>, tx: Sender<WatcherCommand>) -> Self {
|
pub fn new(rx: Receiver<WsCommand>, tx: Sender<ExecutorCommand>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
rx,
|
rx,
|
||||||
tx,
|
tx,
|
||||||
|
|||||||
@ -33,9 +33,9 @@ pub struct ChainBootStrap {
|
|||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum BlockchainError {
|
pub enum BlockchainError {
|
||||||
#[error("Failed to serialize data")]
|
#[error("Failed to serialize data: {0}")]
|
||||||
Encode(#[from] bincode::error::EncodeError),
|
Encode(#[from] bincode::error::EncodeError),
|
||||||
#[error("Failed to deserialize data")]
|
#[error("Failed to deserialize data: {0}")]
|
||||||
Decode(#[from] bincode::error::DecodeError),
|
Decode(#[from] bincode::error::DecodeError),
|
||||||
#[error("Database operation failed")]
|
#[error("Database operation failed")]
|
||||||
Database(#[from] DatabaseError),
|
Database(#[from] DatabaseError),
|
||||||
|
|||||||
@ -4,4 +4,8 @@ use thiserror::Error;
|
|||||||
pub enum NetworkError {
|
pub enum NetworkError {
|
||||||
#[error("Implement NetworkError Enum: ({})", file!())]
|
#[error("Implement NetworkError Enum: ({})", file!())]
|
||||||
TODO,
|
TODO,
|
||||||
|
#[error("Decode Error: {0}")]
|
||||||
|
Decode(#[from] bincode::error::DecodeError),
|
||||||
|
#[error("Encode Error: {0}")]
|
||||||
|
Encode(#[from] bincode::error::EncodeError),
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,13 @@
|
|||||||
use crate::network::ConnectorError;
|
use crate::bus::{publish_system_event, publish_watcher_event, subscribe_system_event, SystemEvent};
|
||||||
use shared::blockchain_core::{self, ChainData, SignedTransaction};
|
use shared::blockchain_core::{self, ChainData, SignedTransaction, validator::ValidationError};
|
||||||
|
use crate::print_error_chain;
|
||||||
|
use crate::executor::ExecutorCommand;
|
||||||
use crate::log;
|
use crate::log;
|
||||||
use crate::network::{NodeId, ProtocolMessage};
|
use crate::network::{NodeId, ProtocolMessage};
|
||||||
use crate::network::{Connector, ConnectorCommand};
|
use crate::network::{Connector, ConnectorCommand};
|
||||||
use crate::seeds_constants::SEED_NODES;
|
use crate::seeds_constants::SEED_NODES;
|
||||||
use crate::watcher::{WatcherCommand, WatcherMode};
|
use crate::watcher::{WatcherCommand, WatcherMode};
|
||||||
|
use crate::network::ws_server::{WsCommand, WsServer};
|
||||||
use super::{ Blockchain, BlockchainError };
|
use super::{ Blockchain, BlockchainError };
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@ -12,6 +15,8 @@ use std::net::SocketAddr;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use thiserror::*;
|
use thiserror::*;
|
||||||
|
use tokio::select;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use vlogger::*;
|
use vlogger::*;
|
||||||
|
|
||||||
@ -19,39 +24,36 @@ use vlogger::*;
|
|||||||
pub struct TcpPeer {
|
pub struct TcpPeer {
|
||||||
pub id: NodeId,
|
pub id: NodeId,
|
||||||
pub addr: SocketAddr,
|
pub addr: SocketAddr,
|
||||||
|
pub sender: tokio::sync::mpsc::Sender<ProtocolMessage>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TcpPeer {
|
impl TcpPeer {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
|
sender: tokio::sync::mpsc::Sender<ProtocolMessage>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self { id, addr }
|
Self { id, addr, sender }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct Node {
|
pub struct Node {
|
||||||
pub tcp_connector: Connector,
|
pub tcp_connector: Option<mpsc::Sender<ConnectorCommand>>,
|
||||||
pub id: NodeId,
|
pub id: NodeId,
|
||||||
pub addr: SocketAddr,
|
pub addr: Option<SocketAddr>,
|
||||||
pub tcp_peers: HashMap<NodeId, TcpPeer>,
|
pub tcp_peers: HashMap<NodeId, TcpPeer>,
|
||||||
chain: Blockchain,
|
chain: Blockchain,
|
||||||
listner_handle: Option<tokio::task::JoinHandle<()>>,
|
listner_handle: Option<tokio::task::JoinHandle<()>>,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
|
rx: mpsc::Receiver<NodeCommand>,
|
||||||
|
tx: mpsc::Sender<NodeCommand>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum NodeError {
|
pub enum NodeError {
|
||||||
#[error("Block chain error")]
|
#[error("Block chain error")]
|
||||||
Blockchain(#[from] BlockchainError),
|
ChainError(#[from] BlockchainError),
|
||||||
#[error("Connector Error")]
|
|
||||||
Connector(#[from] ConnectorError),
|
|
||||||
#[error("Unknown peer address")]
|
|
||||||
UnknownPeerAddr(SocketAddr),
|
|
||||||
#[error("Invalid Address:\npeer: {0}\naddr: {1}")]
|
|
||||||
InvalidAddress(String, SocketAddr),
|
|
||||||
#[error("Hex Error")]
|
|
||||||
Hex(#[from] hex::FromHexError),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@ -91,7 +93,9 @@ impl Node {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|p| p.1.addr.to_string().parse::<SocketAddr>().unwrap())
|
.map(|p| p.1.addr.to_string().parse::<SocketAddr>().unwrap())
|
||||||
.collect();
|
.collect();
|
||||||
addr.push(self.addr.clone());
|
if let Some(a) = self.addr {
|
||||||
|
addr.push(a.clone());
|
||||||
|
}
|
||||||
addr
|
addr
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -112,42 +116,57 @@ impl Node {
|
|||||||
self.tcp_peers.remove_entry(&peer_id);
|
self.tcp_peers.remove_entry(&peer_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_tcp_peer(&mut self, peer: TcpPeer) {
|
async fn add_tcp_peer(&mut self, peer: TcpPeer) {
|
||||||
log(msg!(DEBUG, "Added Peer from address: {}", peer.addr));
|
log(msg!(DEBUG, "Added Peer from address: {}", peer.addr));
|
||||||
self.tcp_peers.insert(peer.id.clone(), peer);
|
self.tcp_peers.insert(peer.id.clone(), peer);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn new_with_id(
|
pub async fn new_with_id(
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
addr: SocketAddr,
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
|
addr: Option<SocketAddr>,
|
||||||
chain: Blockchain,
|
chain: Blockchain,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let (tx, rx) = mpsc::channel::<NodeCommand>(100);
|
||||||
Self {
|
Self {
|
||||||
id: id.clone(),
|
id,
|
||||||
tcp_peers: HashMap::new(),
|
tcp_peers: HashMap::new(),
|
||||||
addr,
|
addr,
|
||||||
|
exec_tx,
|
||||||
chain,
|
chain,
|
||||||
listner_handle: None,
|
listner_handle: None,
|
||||||
tcp_connector: Connector::new(id, addr),
|
tcp_connector: None,
|
||||||
|
tx,
|
||||||
|
rx,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new(
|
pub fn new(
|
||||||
addr: SocketAddr,
|
addr: Option<SocketAddr>,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
chain: Blockchain,
|
chain: Blockchain,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let id = NodeId(*Uuid::new_v4().as_bytes());
|
let (tx, rx) = mpsc::channel::<NodeCommand>(100);
|
||||||
Self {
|
Self {
|
||||||
id: id.clone(),
|
id: NodeId(*Uuid::new_v4().as_bytes()),
|
||||||
tcp_peers: HashMap::new(),
|
tcp_peers: HashMap::new(),
|
||||||
addr,
|
addr,
|
||||||
|
exec_tx,
|
||||||
listner_handle: None,
|
listner_handle: None,
|
||||||
tcp_connector: Connector::new(id, addr),
|
tcp_connector: None,
|
||||||
chain,
|
chain,
|
||||||
|
tx,
|
||||||
|
rx,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn shutdown(&mut self) {
|
async fn shutdown(&mut self) {
|
||||||
|
if let Some(conn) = &self.tcp_connector {
|
||||||
|
let res = conn.send(ConnectorCommand::Shutdown).await;
|
||||||
|
if res.is_err() {
|
||||||
|
log(msg!(ERROR, "Failed to send shutdown signal to connector"));
|
||||||
|
}
|
||||||
|
}
|
||||||
let _ = self.chain.shutdown().await;
|
let _ = self.chain.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -155,25 +174,6 @@ impl Node {
|
|||||||
Ok(self.chain.blocks()?)
|
Ok(self.chain.blocks()?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_message(&mut self, peer_id: NodeId, message: &ProtocolMessage) -> Result<(), NodeError> {
|
|
||||||
self.tcp_connector.send_message_to_peer(peer_id, &message).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn broadcast_message(&mut self, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
|
||||||
let keys: Vec<_> = self.tcp_peers.keys().cloned().collect();
|
|
||||||
let mut results = Vec::new();
|
|
||||||
for id in keys {
|
|
||||||
let res = self.send_message(id, msg).await;
|
|
||||||
results.push(res);
|
|
||||||
}
|
|
||||||
if let Some(error) = results.into_iter().find(|r| r.is_err()) {
|
|
||||||
error
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn process_message(&mut self, peer_id: NodeId, message: ProtocolMessage) -> Result<(), NodeError> {
|
pub async fn process_message(&mut self, peer_id: NodeId, message: ProtocolMessage) -> Result<(), NodeError> {
|
||||||
match message {
|
match message {
|
||||||
ProtocolMessage::BootstrapRequest { .. } => {
|
ProtocolMessage::BootstrapRequest { .. } => {
|
||||||
@ -181,7 +181,7 @@ impl Node {
|
|||||||
let peer = &self.tcp_peers[&peer_id];
|
let peer = &self.tcp_peers[&peer_id];
|
||||||
let blocks = self.chain.bootstrap()?;
|
let blocks = self.chain.bootstrap()?;
|
||||||
let resp = ProtocolMessage::BootstrapResponse { blocks };
|
let resp = ProtocolMessage::BootstrapResponse { blocks };
|
||||||
self.send_message(peer.id.clone(), &resp).await?;
|
peer.sender.send(resp).await.unwrap();
|
||||||
log(msg!(DEBUG, "Send BootstrapResponse to {peer_id}"));
|
log(msg!(DEBUG, "Send BootstrapResponse to {peer_id}"));
|
||||||
}
|
}
|
||||||
ProtocolMessage::BootstrapResponse { blocks } => {
|
ProtocolMessage::BootstrapResponse { blocks } => {
|
||||||
@ -193,11 +193,11 @@ impl Node {
|
|||||||
}
|
}
|
||||||
ProtocolMessage::Ping { peer_id } => {
|
ProtocolMessage::Ping { peer_id } => {
|
||||||
log(msg!(DEBUG, "Received Ping from {peer_id}"));
|
log(msg!(DEBUG, "Received Ping from {peer_id}"));
|
||||||
let peer = &self.tcp_peers[&peer_id];
|
|
||||||
let resp = ProtocolMessage::Pong {
|
let resp = ProtocolMessage::Pong {
|
||||||
peer_id: self.id.clone(),
|
peer_id: self.id.clone(),
|
||||||
};
|
};
|
||||||
self.send_message(peer.id.clone(), &resp).await?;
|
let peer = &self.tcp_peers[&peer_id];
|
||||||
|
peer.sender.send(resp).await.unwrap();
|
||||||
}
|
}
|
||||||
ProtocolMessage::GetPeersRequest { peer_id } => {
|
ProtocolMessage::GetPeersRequest { peer_id } => {
|
||||||
log(msg!(DEBUG, "Received GetPeersRequest from {peer_id}"));
|
log(msg!(DEBUG, "Received GetPeersRequest from {peer_id}"));
|
||||||
@ -206,7 +206,7 @@ impl Node {
|
|||||||
peer_addresses: peers,
|
peer_addresses: peers,
|
||||||
};
|
};
|
||||||
let peer = &self.tcp_peers[&peer_id];
|
let peer = &self.tcp_peers[&peer_id];
|
||||||
self.send_message(peer.id.clone(), &resp).await?;
|
peer.sender.send(resp).await.unwrap();
|
||||||
}
|
}
|
||||||
ProtocolMessage::Block { block, .. } => {
|
ProtocolMessage::Block { block, .. } => {
|
||||||
log(msg!(DEBUG, "Received Block from {peer_id}"));
|
log(msg!(DEBUG, "Received Block from {peer_id}"));
|
||||||
@ -230,185 +230,279 @@ impl Node {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_message_to_peer_addr(&mut self, addr: SocketAddr, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
pub async fn send_message_to_peer_addr(&self, addr: SocketAddr, msg: ProtocolMessage) {
|
||||||
if let Some((_, peer)) = self.tcp_peers.iter().find(|(_, v)| v.addr == addr) {
|
if let Some((_, peer)) = self.tcp_peers.iter().find(|(_, v)| v.addr == addr) {
|
||||||
self.send_message(peer.id.clone(), &msg).await?;
|
if let Err(e) = peer.sender.send(msg).await {
|
||||||
Ok(())
|
log(msg!(ERROR, "Error Sending message to peer: {e}"));
|
||||||
|
}
|
||||||
|
log(msg!(DEBUG, "Sent BootstrapRequest to seed"));
|
||||||
} else {
|
} else {
|
||||||
Err(NodeError::UnknownPeerAddr(addr))
|
log(msg!(
|
||||||
|
ERROR,
|
||||||
|
"Error Sending message to peer: peer not in list"
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_message_to_peer_id(&mut self, id: NodeId, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
pub async fn send_message_to_peer_id(&self, id: NodeId, msg: ProtocolMessage) {
|
||||||
self.send_message(id.clone(), &msg).await?;
|
if let Some(peer) = self.tcp_peers.get(&id) {
|
||||||
Ok(())
|
if let Err(e) = peer.sender.send(msg).await {
|
||||||
|
log(msg!(ERROR, "Error Sending message to peer: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_message_to_seed(&mut self, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
async fn send_message_to_seed(&self, msg: ProtocolMessage) {
|
||||||
for seed in SEED_NODES.iter() {
|
for seed in SEED_NODES.iter() {
|
||||||
if let Some(s) = self.tcp_peers.iter().find(|(_, v)| v.addr == *seed) {
|
if let Some(_) = self.tcp_peers.iter().find(|(_, v)| v.addr == *seed) {
|
||||||
self.send_message_to_peer_addr(s.1.addr, &msg).await?;
|
self.send_message_to_peer_addr(*seed, msg).await;
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
self.send_message_to_peer_addr(*seed, msg).await;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
log(msg!(ERROR, "No Seed Nodes Avaliable"));
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn bootstrap(&mut self) -> Result<(), NodeError> {
|
async fn bootstrap(&mut self) -> Result<(), ValidationError> {
|
||||||
|
log(msg!(DEBUG, "Bootstrapping"));
|
||||||
|
|
||||||
let message = ProtocolMessage::BootstrapRequest {
|
let message = ProtocolMessage::BootstrapRequest {
|
||||||
peer_id: self.id.clone(),
|
peer_id: self.id.clone(),
|
||||||
version: "".to_string(),
|
version: "".to_string(),
|
||||||
};
|
};
|
||||||
self.send_message_to_seed(&message).await?;
|
self.send_message_to_seed(message).await;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn broadcast_network_data(&mut self, data: ChainData) -> Result<(), NodeError> {
|
async fn broadcast_network_data(&self, data: ChainData) {
|
||||||
|
for (id, peer) in &self.tcp_peers {
|
||||||
let message = ProtocolMessage::ChainData {
|
let message = ProtocolMessage::ChainData {
|
||||||
peer_id: self.id.clone(),
|
peer_id: self.id.clone(),
|
||||||
data,
|
data: data.clone(),
|
||||||
};
|
};
|
||||||
self.broadcast_message(&message).await
|
peer.sender.send(message).await.unwrap();
|
||||||
|
log(msg!(DEBUG, "Send Transaction message to {id}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn broadcast_block(&mut self, block: &blockchain_core::Block) -> Result<(), NodeError> {
|
async fn broadcast_block(&self, block: &blockchain_core::Block) {
|
||||||
|
for (id, peer) in &self.tcp_peers {
|
||||||
let message = ProtocolMessage::Block {
|
let message = ProtocolMessage::Block {
|
||||||
peer_id: self.id.clone(),
|
peer_id: self.id.clone(),
|
||||||
height: block.head().height as u64,
|
height: block.head().height as u64,
|
||||||
block: block.clone(),
|
block: block.clone(),
|
||||||
};
|
};
|
||||||
self.broadcast_message(&message).await
|
peer.sender.send(message).await.unwrap();
|
||||||
|
log(msg!(DEBUG, "Send Block message to {id}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn connector_cmd(&mut self, cmd: ConnectorCommand) -> Result<Option<NodeCommand>, NodeError> {
|
pub fn tx(&self) -> mpsc::Sender<NodeCommand> {
|
||||||
let res = self.tcp_connector.command(cmd).await?;
|
return self.tx.clone();
|
||||||
Ok(res)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_connection_listner(&mut self, addr: SocketAddr) {
|
pub fn exec_tx(&self) -> mpsc::Sender<ExecutorCommand> {
|
||||||
|
return self.exec_tx.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connector_cmd(&self, cmd: ConnectorCommand) {
|
||||||
|
match &self.tcp_connector {
|
||||||
|
Some(t) => match t.send(cmd).await {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) => log(msg!(ERROR, "Failed to Send Command to connector: {}", e)),
|
||||||
|
},
|
||||||
|
None => log(msg!(ERROR, "No Connector Availiable")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_connection_listner(&mut self, addr: SocketAddr) {
|
||||||
log(msg!(DEBUG, "Starting Connection Listener"));
|
log(msg!(DEBUG, "Starting Connection Listener"));
|
||||||
|
let (con_tx, con_rx) = mpsc::channel::<ConnectorCommand>(100);
|
||||||
|
|
||||||
let connector = Connector::new(self.id.clone(), addr);
|
self.tcp_connector = Some(con_tx);
|
||||||
|
|
||||||
|
self.listner_handle = Some(tokio::spawn({
|
||||||
|
let mut connector = Connector::new(self.id.clone(), addr, self.exec_tx(), con_rx);
|
||||||
log(msg!(DEBUG, "Connector Build"));
|
log(msg!(DEBUG, "Connector Build"));
|
||||||
self.tcp_connector = connector;
|
async move { connector.start().await }
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn connect_to_seed(&mut self) -> Result<Option<NodeCommand>, NodeError> {
|
async fn connect_to_seed(&mut self) {
|
||||||
let res = self.tcp_connector.command(ConnectorCommand::ConnectToTcpSeed(SEED_NODES[0])).await?;
|
self
|
||||||
Ok(res)
|
.connector_cmd(ConnectorCommand::ConnectToTcpSeed(SEED_NODES[0]))
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn command(&mut self, command: NodeCommand) -> Result<Option<WatcherCommand>, NodeError> {
|
async fn accept_command(&mut self) {
|
||||||
|
while let Some(command) = self.rx.recv().await {
|
||||||
match command {
|
match command {
|
||||||
NodeCommand::BootStrap => {
|
NodeCommand::BootStrap => {
|
||||||
self.bootstrap().await?;
|
log(msg!(DEBUG, "Received NodeCommand::BootStrap"));
|
||||||
|
let _ = self.bootstrap().await;
|
||||||
}
|
}
|
||||||
NodeCommand::BroadcastTransaction(sign_tx) => {
|
NodeCommand::BroadcastTransaction(sign_tx) => {
|
||||||
self.broadcast_network_data(ChainData::Transaction(sign_tx)).await?;
|
self.broadcast_network_data(ChainData::Transaction(sign_tx)).await;
|
||||||
}
|
}
|
||||||
NodeCommand::StartListner(addr) => {
|
NodeCommand::StartListner(addr) => {
|
||||||
self.start_connection_listner(addr);
|
self.start_connection_listner(addr).await;
|
||||||
}
|
}
|
||||||
NodeCommand::ConnectToSeeds => {
|
NodeCommand::ConnectToSeeds => {
|
||||||
self.connect_to_seed().await?;
|
self.connect_to_seed().await;
|
||||||
}
|
}
|
||||||
NodeCommand::ConnectTcpPeer(addr) => {
|
NodeCommand::ConnectTcpPeer(addr) => {
|
||||||
let addr_sock = addr.parse::<SocketAddr>()
|
log(msg!(DEBUG, "Received ConnectToPeer: {addr}"));
|
||||||
.map_err(|_| NodeError::InvalidAddress("Self".to_string(), self.addr))?;
|
if let Ok(addr_sock) = addr.parse::<SocketAddr>() {
|
||||||
let res = self.connector_cmd(ConnectorCommand::ConnectToTcpPeer(addr_sock)).await?;
|
let mes = ConnectorCommand::ConnectToTcpPeer(addr_sock);
|
||||||
if let Some(node_cmd) = res {
|
self.connector_cmd(mes).await;
|
||||||
return Ok(Some(WatcherCommand::Node(node_cmd)))
|
} else {
|
||||||
|
log(msg!(ERROR, "Failed to Parse to sock_addr: {addr}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NodeCommand::PingAddr(addr) => {
|
NodeCommand::PingAddr(addr) => {
|
||||||
let addr_sock = addr.parse::<SocketAddr>()
|
if let Ok(addr_sock) = addr.parse::<SocketAddr>() {
|
||||||
.map_err(|_| NodeError::InvalidAddress("Self".to_string(), self.addr))?;
|
|
||||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||||
self.send_message_to_peer_addr(addr_sock, &mes).await?;
|
self.send_message_to_peer_addr(addr_sock, mes).await;
|
||||||
|
} else {
|
||||||
|
log(msg!(ERROR, "Failed to Parse to sock_addr: {addr}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
NodeCommand::PingId(id) => {
|
NodeCommand::PingId(id) => {
|
||||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||||
self.send_message_to_peer_id(id, &mes).await?;
|
self.send_message_to_peer_id(id, mes).await;
|
||||||
}
|
}
|
||||||
NodeCommand::AddPeer(peer) => {
|
NodeCommand::AddPeer(peer) => {
|
||||||
self.add_tcp_peer(peer);
|
self.add_tcp_peer(peer).await;
|
||||||
}
|
}
|
||||||
NodeCommand::RemovePeer { peer_id } => {
|
NodeCommand::RemovePeer { peer_id } => {
|
||||||
self.remove_tcp_peer(peer_id).await;
|
self.remove_tcp_peer(peer_id).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
NodeCommand::ProcessMessage { peer_id, message } => {
|
NodeCommand::ProcessMessage { peer_id, message } => {
|
||||||
self.process_message(peer_id, message).await?;
|
self.process_message(peer_id, message).await.unwrap();
|
||||||
}
|
}
|
||||||
NodeCommand::AwardCurrency { address, amount } => {
|
NodeCommand::AwardCurrency { address, amount } => {
|
||||||
self.chain.award_currency(address, amount)?;
|
if let Err(e) = self.chain.award_currency(address, amount) {
|
||||||
|
print_error_chain(&e.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
NodeCommand::ProcessChainData(data) => {
|
NodeCommand::ProcessChainData(data) => {
|
||||||
self.chain.apply_chain_data(data.clone())?;
|
if let Err(e) = self.chain.apply_chain_data(data.clone()) {
|
||||||
self.broadcast_network_data(data).await?;
|
print_error_chain(&e.into());
|
||||||
|
}
|
||||||
|
self.broadcast_network_data(data).await;
|
||||||
}
|
}
|
||||||
NodeCommand::CreateBlock => {
|
NodeCommand::CreateBlock => {
|
||||||
let block = self.chain.create_block()?;
|
log(msg!(DEBUG, "Received CreateBlock Command"));
|
||||||
self.broadcast_block(&block).await?;
|
match self.chain.create_block() {
|
||||||
|
Ok(block) => {
|
||||||
|
log(msg!(
|
||||||
|
INFO,
|
||||||
|
"Created Block with hash {}",
|
||||||
|
hex::encode(block.head().block_hash())
|
||||||
|
));
|
||||||
|
self.broadcast_block(&block).await;
|
||||||
|
}
|
||||||
|
Err(e) => print_error_chain(&e.into()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
NodeCommand::DisplayBlockInteractive => {
|
NodeCommand::DisplayBlockInteractive => {
|
||||||
let blocks = self.chain.list_blocks()?;
|
let blocks = match self.chain.list_blocks() {
|
||||||
return Ok(Some(
|
Ok(b) => b,
|
||||||
WatcherCommand::SetMode(WatcherMode::Select {
|
Err(e) => return print_error_chain(&e.into()),
|
||||||
|
};
|
||||||
|
let wat_cmd = WatcherCommand::SetMode(WatcherMode::Select {
|
||||||
content: blocks.iter().map(|h| hex::encode(h)).collect::<Vec<String>>().into(),
|
content: blocks.iter().map(|h| hex::encode(h)).collect::<Vec<String>>().into(),
|
||||||
title: "Select Block to display".to_string(),
|
title: "Select Block to display".to_string(),
|
||||||
callback: Box::new(WatcherCommand::Node(NodeCommand::DisplayBlockByKey("".to_string()))),
|
callback: Box::new(ExecutorCommand::Node(NodeCommand::DisplayBlockByKey("".to_string()))),
|
||||||
index: 0,
|
index: 0
|
||||||
})
|
});
|
||||||
));
|
publish_watcher_event(wat_cmd);
|
||||||
}
|
}
|
||||||
NodeCommand::DisplayBlockByKey(key) => {
|
NodeCommand::DisplayBlockByKey(key) => {
|
||||||
self.chain.display_block_by_key(&hex::decode(key)?);
|
if let Ok(block_hash) = hex::decode(key) {
|
||||||
}
|
self.chain.display_block_by_key(&block_hash)
|
||||||
NodeCommand::DisplayBlockByHeight(height) => {
|
|
||||||
self.chain.display_block_by_height(height);
|
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
NodeCommand::DisplayBlockByHeight(height) => self.chain.display_block_by_height(height),
|
||||||
NodeCommand::ListBlocks => {
|
NodeCommand::ListBlocks => {
|
||||||
let s = self.chain.list_blocks()?;
|
log(msg!(DEBUG, "Received DebugListBlocks command"));
|
||||||
let block_list = s.iter().map(|h| format!("{}\n", hex::encode(h))).collect::<Vec<String>>().join("\n");
|
match self.chain.list_blocks() {
|
||||||
return Ok(Some(WatcherCommand::Print(block_list)));
|
Ok(s) => log(s.iter().map(|h| format!("{}\n", hex::encode(h))).collect::<Vec<String>>().join("\n")),
|
||||||
|
Err(e) => print_error_chain(&e.into()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
NodeCommand::ListPeers => {
|
NodeCommand::ListPeers => {
|
||||||
return Ok(Some(WatcherCommand::Print(self.list_peers())));
|
log(msg!(DEBUG, "Received DebugListPeers command"));
|
||||||
|
log(self.list_peers());
|
||||||
}
|
}
|
||||||
NodeCommand::ShowId => {
|
NodeCommand::ShowId => {
|
||||||
|
log(msg!(DEBUG, "Received DebugListBlocks command"));
|
||||||
self.show_id().await;
|
self.show_id().await;
|
||||||
}
|
}
|
||||||
NodeCommand::Exit => {}
|
NodeCommand::Exit => {
|
||||||
|
log(msg!(DEBUG, "Node Exit"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(None)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_error(&self, error: NodeError) {
|
pub async fn run(&mut self) {
|
||||||
log(msg!(ERROR, "{error}"));
|
if let Some(addr) = self.addr {
|
||||||
}
|
self.start_connection_listner(addr).await;
|
||||||
|
} else {
|
||||||
|
self
|
||||||
|
.start_connection_listner(SocketAddr::new(
|
||||||
|
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
|
||||||
|
8080,
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
};
|
||||||
|
|
||||||
pub async fn init(&mut self) {
|
let http_handle = tokio::spawn(async move {
|
||||||
let _http_handle = tokio::spawn(async move {
|
|
||||||
let _ = crate::api::server::start_server().await;
|
let _ = crate::api::server::start_server().await;
|
||||||
});
|
});
|
||||||
|
|
||||||
// let (_tx, rx) = mpsc::channel::<WsCommand>(100);
|
let (_tx, rx) = mpsc::channel::<WsCommand>(100);
|
||||||
|
|
||||||
// let mut ws_server = WsServer::new(rx, self.exec_tx());
|
let mut ws_server = WsServer::new(rx, self.exec_tx());
|
||||||
|
|
||||||
// let _ws_handle = tokio::spawn(async move {
|
let _ws_handle = tokio::spawn(async move {
|
||||||
// if let Err(e) = ws_server.run().await {
|
if let Err(e) = ws_server.run().await {
|
||||||
// print_error_chain(&e.into());
|
print_error_chain(&e.into());
|
||||||
// }
|
}
|
||||||
// });
|
});
|
||||||
|
|
||||||
|
let mut system_rx = subscribe_system_event();
|
||||||
|
publish_system_event(SystemEvent::NodeStarted);
|
||||||
|
|
||||||
self.chain.recover_mempool();
|
self.chain.recover_mempool();
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn poll(&mut self) -> Option<()> {
|
loop {
|
||||||
tokio::select! {
|
select! {
|
||||||
_con_cmd = self.tcp_connector.poll() => {
|
_ = self.accept_command() => {
|
||||||
None
|
|
||||||
|
}
|
||||||
|
event_result = system_rx.recv() => {
|
||||||
|
match event_result {
|
||||||
|
Ok(e) => {
|
||||||
|
match e {
|
||||||
|
SystemEvent::Shutdown => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http_handle.abort_handle().abort();
|
||||||
|
self.shutdown().await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,10 @@
|
|||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use tokio::sync::mpsc;
|
||||||
use vlogger::*;
|
use vlogger::*;
|
||||||
|
|
||||||
|
use crate::bus::{NetworkEvent, SystemEvent, subscribe_system_event};
|
||||||
|
use crate::executor::{Executor, ExecutorCommand};
|
||||||
use crate::{log, node};
|
use crate::{log, node};
|
||||||
use crate::node::{Node, NodeCommand};
|
use crate::node::{Node, NodeCommand};
|
||||||
use cli_renderer::{RenderLayoutKind, Renderer};
|
use cli_renderer::{RenderLayoutKind, Renderer};
|
||||||
@ -59,6 +62,8 @@ impl WatcherBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start(mut self) -> Watcher {
|
pub async fn start(mut self) -> Watcher {
|
||||||
|
let (exec_tx, exec_rx) = mpsc::channel::<ExecutorCommand>(100);
|
||||||
|
let mut sys_event = subscribe_system_event();
|
||||||
|
|
||||||
if self.debug {
|
if self.debug {
|
||||||
Watcher::log_memory().await;
|
Watcher::log_memory().await;
|
||||||
@ -71,33 +76,80 @@ impl WatcherBuilder {
|
|||||||
self.addr = Some(crate::seeds_constants::SEED_NODES[0]);
|
self.addr = Some(crate::seeds_constants::SEED_NODES[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.addr.is_none() {
|
|
||||||
self.addr = Some(SocketAddr::new(
|
|
||||||
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
|
|
||||||
8080,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
let chain = node::Blockchain::new(self.database, self.temporary).unwrap();
|
let chain = node::Blockchain::new(self.database, self.temporary).unwrap();
|
||||||
let mut node = Node::new(self.addr.unwrap(), chain);
|
let mut node = Node::new(self.addr.clone(), exec_tx.clone(), chain);
|
||||||
node.init().await;
|
|
||||||
|
|
||||||
log(msg!(INFO, "Built Node"));
|
log(msg!(INFO, "Built Node"));
|
||||||
|
|
||||||
|
let executor_handle = tokio::spawn({
|
||||||
|
let node_tx = node.tx();
|
||||||
|
async move {
|
||||||
|
let _ = Executor::new(node_tx, exec_rx).run().await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for i in 0..3 {
|
||||||
|
if let Ok(ev) = sys_event.recv().await {
|
||||||
|
match ev {
|
||||||
|
SystemEvent::ExecutorStarted => {
|
||||||
|
log(msg!(INFO, "Executor Started"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => log(msg!(WARNING, "Wrong Event: {ev:?}! Retrying... (try {i})")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let node_tx = node.tx();
|
||||||
|
let node_handle = tokio::spawn({
|
||||||
|
async move {
|
||||||
|
node.run().await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for i in 0..3 {
|
||||||
|
if let Ok(ev) = sys_event.recv().await {
|
||||||
|
match ev {
|
||||||
|
SystemEvent::NodeStarted => {
|
||||||
|
log(msg!(INFO, "Executor Started"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => log(msg!(WARNING, "Wrong Event: {ev:?}! Retrying... (try {i})")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.bootstrap {
|
if self.bootstrap {
|
||||||
node.command(NodeCommand::BootStrap).await.unwrap();
|
let exec_tx = exec_tx.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let seed_cmd = ExecutorCommand::Node(NodeCommand::ConnectToSeeds);
|
||||||
|
let mut ev_rx = crate::bus::subscribe_network_event();
|
||||||
|
let _ = exec_tx.send(seed_cmd).await;
|
||||||
|
|
||||||
|
while let Ok(e) = ev_rx.recv().await {
|
||||||
|
match e {
|
||||||
|
NetworkEvent::SeedConnected(_) => {
|
||||||
|
let bootstrap_cmd = ExecutorCommand::Node(NodeCommand::BootStrap);
|
||||||
|
let _ = exec_tx.send(bootstrap_cmd).await;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let cmd_history = Vec::new();
|
let cmd_history = Vec::new();
|
||||||
let history_index = 0;
|
let history_index = 0;
|
||||||
let cmd_buffer = String::new();
|
let cmd_buffer = String::new();
|
||||||
|
let handles = vec![executor_handle, node_handle];
|
||||||
Watcher::new(
|
Watcher::new(
|
||||||
|
node_tx,
|
||||||
|
exec_tx,
|
||||||
cmd_buffer,
|
cmd_buffer,
|
||||||
cmd_history,
|
cmd_history,
|
||||||
history_index,
|
history_index,
|
||||||
|
handles,
|
||||||
renderer,
|
renderer,
|
||||||
node,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,19 +1,12 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use cli_renderer::RenderCommand;
|
use cli_renderer::RenderCommand;
|
||||||
|
use crate::executor::ExecutorCommand;
|
||||||
use crate::node::NodeCommand;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum WatcherCommand {
|
pub enum WatcherCommand {
|
||||||
NodeResponse(String),
|
|
||||||
Node(NodeCommand),
|
|
||||||
Echo(Vec<String>),
|
|
||||||
Print(String),
|
|
||||||
InvalidCommand(String),
|
|
||||||
Render(RenderCommand),
|
Render(RenderCommand),
|
||||||
SetMode(WatcherMode),
|
SetMode(WatcherMode),
|
||||||
Exit,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@ -22,7 +15,7 @@ pub enum WatcherMode {
|
|||||||
Select{
|
Select{
|
||||||
content: Arc<Vec<String>>,
|
content: Arc<Vec<String>>,
|
||||||
title: String,
|
title: String,
|
||||||
callback: Box<WatcherCommand>,
|
callback: Box<ExecutorCommand>,
|
||||||
index: usize,
|
index: usize,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,15 +1,18 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
bus::{SystemEvent, publish_system_event, subscribe_system_event}, cli::cli, node::{Node, NodeError, node::NodeCommand}, watcher::WatcherMode
|
bus::{publish_system_event, subscribe_system_event, SystemEvent},
|
||||||
|
cli::cli,
|
||||||
|
node::node::NodeCommand,
|
||||||
|
watcher::WatcherMode
|
||||||
};
|
};
|
||||||
|
|
||||||
use ratatui::prelude::CrosstermBackend;
|
use shared::print_error_chain;
|
||||||
use crate::print_error_chain;
|
|
||||||
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind, MouseButton, MouseEventKind};
|
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind, MouseButton, MouseEventKind};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use memory_stats::memory_stats;
|
use memory_stats::memory_stats;
|
||||||
use std::io::{self, Stdout, Write};
|
use std::io::{self, Write};
|
||||||
use tokio::{
|
use tokio::{
|
||||||
select,
|
select,
|
||||||
|
sync::mpsc,
|
||||||
time::{Duration, interval},
|
time::{Duration, interval},
|
||||||
};
|
};
|
||||||
use vlogger::*;
|
use vlogger::*;
|
||||||
@ -17,6 +20,7 @@ use vlogger::*;
|
|||||||
use super::{ WatcherBuilder, WatcherCommand };
|
use super::{ WatcherBuilder, WatcherCommand };
|
||||||
|
|
||||||
use crate::bus::subscribe_watcher_event;
|
use crate::bus::subscribe_watcher_event;
|
||||||
|
use crate::executor::*;
|
||||||
use crate::log;
|
use crate::log;
|
||||||
|
|
||||||
use cli_renderer::{
|
use cli_renderer::{
|
||||||
@ -25,37 +29,37 @@ use cli_renderer::{
|
|||||||
RenderCommand
|
RenderCommand
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
pub enum WatcherError {
|
|
||||||
#[error("Node Error")]
|
|
||||||
Node(#[from] NodeError),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct Watcher {
|
pub struct Watcher {
|
||||||
|
node_tx: mpsc::Sender<NodeCommand>,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
cmd_buffer: String,
|
cmd_buffer: String,
|
||||||
cmd_history: Vec<String>,
|
cmd_history: Vec<String>,
|
||||||
history_index: usize,
|
history_index: usize,
|
||||||
|
handles: Vec<tokio::task::JoinHandle<()>>,
|
||||||
event_stream: crossterm::event::EventStream,
|
event_stream: crossterm::event::EventStream,
|
||||||
mode: WatcherMode,
|
mode: WatcherMode,
|
||||||
pub renderer: Renderer,
|
pub renderer: Renderer,
|
||||||
node: Node,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Watcher {
|
impl Watcher {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
|
node_tx: mpsc::Sender<NodeCommand>,
|
||||||
|
exec_tx: mpsc::Sender<ExecutorCommand>,
|
||||||
cmd_buffer: String,
|
cmd_buffer: String,
|
||||||
cmd_history: Vec<String>,
|
cmd_history: Vec<String>,
|
||||||
history_index: usize,
|
history_index: usize,
|
||||||
|
handles: Vec<tokio::task::JoinHandle<()>>,
|
||||||
renderer: Renderer,
|
renderer: Renderer,
|
||||||
node: Node,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
node_tx,
|
||||||
|
exec_tx,
|
||||||
cmd_buffer,
|
cmd_buffer,
|
||||||
cmd_history,
|
cmd_history,
|
||||||
history_index,
|
history_index,
|
||||||
|
handles,
|
||||||
renderer,
|
renderer,
|
||||||
node,
|
|
||||||
mode: WatcherMode::Input,
|
mode: WatcherMode::Input,
|
||||||
event_stream: EventStream::new(),
|
event_stream: EventStream::new(),
|
||||||
}
|
}
|
||||||
@ -72,6 +76,10 @@ impl Watcher {
|
|||||||
|
|
||||||
async fn shutdown(&mut self) -> io::Result<()> {
|
async fn shutdown(&mut self) -> io::Result<()> {
|
||||||
ratatui::restore();
|
ratatui::restore();
|
||||||
|
let handles = std::mem::take(&mut self.handles);
|
||||||
|
for handle in handles {
|
||||||
|
handle.await.unwrap()
|
||||||
|
}
|
||||||
crossterm::execute!(
|
crossterm::execute!(
|
||||||
std::io::stdout(),
|
std::io::stdout(),
|
||||||
crossterm::event::DisableBracketedPaste,
|
crossterm::event::DisableBracketedPaste,
|
||||||
@ -80,6 +88,24 @@ impl Watcher {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn handle_cmd(&mut self, cmd: WatcherCommand) {
|
||||||
|
match cmd {
|
||||||
|
WatcherCommand::Render(rend_cmd) => {
|
||||||
|
self.renderer.apply(rend_cmd);
|
||||||
|
}
|
||||||
|
WatcherCommand::SetMode(mode) => {
|
||||||
|
match &mode {
|
||||||
|
WatcherMode::Input => {}
|
||||||
|
WatcherMode::Select{content, title, ..} => {
|
||||||
|
let rd_cmd = RenderCommand::SetMode(InputMode::PopUp(content.clone(), title.clone(), 0));
|
||||||
|
self.renderer.apply(rd_cmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.mode = mode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn run(&mut self) -> std::io::Result<()> {
|
pub async fn run(&mut self) -> std::io::Result<()> {
|
||||||
let mut ui_rx = subscribe_watcher_event();
|
let mut ui_rx = subscribe_watcher_event();
|
||||||
let mut render_interval = interval(Duration::from_millis(32));
|
let mut render_interval = interval(Duration::from_millis(32));
|
||||||
@ -93,9 +119,10 @@ impl Watcher {
|
|||||||
poll_res = self.poll() => {
|
poll_res = self.poll() => {
|
||||||
match poll_res {
|
match poll_res {
|
||||||
Ok(event) => {
|
Ok(event) => {
|
||||||
match self.handle_event(event, &mut terminal).await {
|
self.renderer.set_area(terminal.get_frame().area());
|
||||||
Ok(_) => {}
|
match self.handle_event(event).await {
|
||||||
Err(e) => print_error_chain(&e.into()),
|
Ok(ret) => if !ret { self.exit(); break }
|
||||||
|
Err(e) => log(msg!(ERROR, "{}", e)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(()) => { log(msg!(ERROR, "Failed to read from Stream")) }
|
Err(()) => { log(msg!(ERROR, "Failed to read from Stream")) }
|
||||||
@ -105,13 +132,10 @@ impl Watcher {
|
|||||||
match ui_event {
|
match ui_event {
|
||||||
Ok(cmd) => {
|
Ok(cmd) => {
|
||||||
self.renderer.set_area(terminal.get_frame().area());
|
self.renderer.set_area(terminal.get_frame().area());
|
||||||
match self.command(cmd).await {
|
self.handle_cmd(cmd);
|
||||||
Ok(_) => {}
|
|
||||||
Err(e) => print_error_chain(&e.into()),
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
print_error_chain(&e.into())
|
log(msg!(ERROR, "{}", e))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -138,72 +162,31 @@ impl Watcher {
|
|||||||
WatcherBuilder::new()
|
WatcherBuilder::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exit(&mut self) {
|
pub fn exec_tx(&self) -> mpsc::Sender<ExecutorCommand> {
|
||||||
log(msg!(DEBUG, "Watcher Exit"));
|
self.exec_tx.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn echo(&mut self, s: Vec<String>) {
|
pub fn exit(&self) {}
|
||||||
let mut str = s.join(" ");
|
|
||||||
str.push_str("\n");
|
|
||||||
self.renderer.apply(RenderCommand::StringToPaneId {
|
|
||||||
str,
|
|
||||||
pane: cli_renderer::RenderTarget::CliOutput,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn invalid_command(&mut self, str: String) {
|
async fn handle_enter(&mut self) {
|
||||||
self.renderer.apply(RenderCommand::StringToPaneId {
|
|
||||||
str,
|
|
||||||
pane: cli_renderer::RenderTarget::CliOutput,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_mode(&mut self, mode: WatcherMode) {
|
|
||||||
match &mode {
|
|
||||||
WatcherMode::Input => {}
|
|
||||||
WatcherMode::Select{content, title, ..} => {
|
|
||||||
let rd_cmd = RenderCommand::SetMode(InputMode::PopUp(content.clone(), title.clone(), 0));
|
|
||||||
self.renderer.apply(rd_cmd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.mode = mode;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn command(&mut self, cmd: WatcherCommand) -> Result<Option<WatcherCommand>, WatcherError> {
|
|
||||||
match cmd {
|
|
||||||
WatcherCommand::NodeResponse(resp) => log(resp),
|
|
||||||
WatcherCommand::Node(n) => return Ok(self.node.command(n).await?),
|
|
||||||
WatcherCommand::Render(p) => self.renderer.apply(p),
|
|
||||||
WatcherCommand::Echo(s) => self.echo(s),
|
|
||||||
WatcherCommand::Print(s) => log(s),
|
|
||||||
WatcherCommand::InvalidCommand(str) => self.invalid_command(str).await,
|
|
||||||
WatcherCommand::Exit => self.exit(),
|
|
||||||
WatcherCommand::SetMode(mode) => self.set_mode(mode),
|
|
||||||
};
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_enter(&mut self) -> Result<(), WatcherError> {
|
|
||||||
match &self.mode {
|
match &self.mode {
|
||||||
WatcherMode::Input => {
|
WatcherMode::Input => {
|
||||||
if !self.cmd_buffer.is_empty() {
|
if !self.cmd_buffer.is_empty() {
|
||||||
let mut cmd = cli(&self.cmd_buffer);
|
let exec_event = cli(&self.cmd_buffer);
|
||||||
|
let _ = self.exec_tx.send(exec_event).await;
|
||||||
self.cmd_buffer.clear();
|
self.cmd_buffer.clear();
|
||||||
self.renderer.handle_enter();
|
self.renderer.handle_enter()
|
||||||
while let Some(new_cmd) = self.command(cmd).await? {
|
|
||||||
cmd = new_cmd;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
WatcherMode::Select { content, callback, index, .. } => {
|
WatcherMode::Select { content, callback, index, .. } => {
|
||||||
match &&**callback {
|
match &&**callback {
|
||||||
&WatcherCommand::Node(nd_cmd) => {
|
&ExecutorCommand::Node(nd_cmd) => {
|
||||||
match nd_cmd {
|
match nd_cmd {
|
||||||
NodeCommand::DisplayBlockByKey(_) => {
|
NodeCommand::DisplayBlockByKey(_) => {
|
||||||
let key = (*content)[*index].clone().to_string();
|
let key = (*content)[*index].clone().to_string();
|
||||||
log(msg!(DEBUG, "KEY IN ENTER: {key}"));
|
log(msg!(DEBUG, "KEY IN ENTER: {key}"));
|
||||||
self.node.command(NodeCommand::DisplayBlockByKey(key)).await?;
|
let resp = ExecutorCommand::Node(NodeCommand::DisplayBlockByKey(key));
|
||||||
|
let _ = self.exec_tx.send(resp).await;
|
||||||
}
|
}
|
||||||
_ => {log(msg!(DEBUG, "TODO: Implement callback for {:?}", nd_cmd))}
|
_ => {log(msg!(DEBUG, "TODO: Implement callback for {:?}", nd_cmd))}
|
||||||
}
|
}
|
||||||
@ -213,7 +196,6 @@ impl Watcher {
|
|||||||
self.mode = WatcherMode::Input;
|
self.mode = WatcherMode::Input;
|
||||||
let rd_cmd = RenderCommand::SetMode(InputMode::Input);
|
let rd_cmd = RenderCommand::SetMode(InputMode::Input);
|
||||||
self.renderer.apply(rd_cmd);
|
self.renderer.apply(rd_cmd);
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -282,7 +264,7 @@ impl Watcher {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_event(&mut self, event: Event, terminal: &mut ratatui::Terminal<CrosstermBackend<Stdout>>) -> Result<(), WatcherError> {
|
pub async fn handle_event(&mut self, event: Event) -> io::Result<bool> {
|
||||||
match event {
|
match event {
|
||||||
Event::Mouse(event) => match event.kind {
|
Event::Mouse(event) => match event.kind {
|
||||||
MouseEventKind::ScrollUp => {
|
MouseEventKind::ScrollUp => {
|
||||||
@ -302,9 +284,6 @@ impl Watcher {
|
|||||||
},
|
},
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
Event::Resize(_, _) => {
|
|
||||||
self.renderer.set_area(terminal.get_frame().area());
|
|
||||||
}
|
|
||||||
Event::Key(k) if k.kind == KeyEventKind::Press => match k.code {
|
Event::Key(k) if k.kind == KeyEventKind::Press => match k.code {
|
||||||
KeyCode::Esc => publish_system_event(SystemEvent::Shutdown),
|
KeyCode::Esc => publish_system_event(SystemEvent::Shutdown),
|
||||||
KeyCode::Char(c) => {
|
KeyCode::Char(c) => {
|
||||||
@ -316,7 +295,7 @@ impl Watcher {
|
|||||||
self.renderer.handle_backspace()
|
self.renderer.handle_backspace()
|
||||||
}
|
}
|
||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
self.handle_enter().await?;
|
self.handle_enter().await;
|
||||||
}
|
}
|
||||||
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right => {
|
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right => {
|
||||||
self.handle_arrow_key(k.code);
|
self.handle_arrow_key(k.code);
|
||||||
@ -330,7 +309,7 @@ impl Watcher {
|
|||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn poll(&mut self) -> Result<Event, ()> {
|
pub async fn poll(&mut self) -> Result<Event, ()> {
|
||||||
|
|||||||
@ -8,7 +8,7 @@ use thiserror::Error;
|
|||||||
pub struct AddressParser {}
|
pub struct AddressParser {}
|
||||||
|
|
||||||
impl clap::builder::TypedValueParser for AddressParser {
|
impl clap::builder::TypedValueParser for AddressParser {
|
||||||
type Value = Address;
|
type Value = [u8; 20];
|
||||||
|
|
||||||
fn parse_ref(
|
fn parse_ref(
|
||||||
&self,
|
&self,
|
||||||
@ -21,20 +21,14 @@ impl clap::builder::TypedValueParser for AddressParser {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let stripped_value = str.strip_prefix("0x").unwrap_or(str);
|
let stripped_value = str.strip_prefix("0x").unwrap_or(str);
|
||||||
let mut bytes: [u8; 20] = [0; 20];
|
let bytes = hex::decode(stripped_value).map_err(|_| {
|
||||||
|
|
||||||
let decoded_hex = hex::decode(stripped_value).map_err(|_| {
|
|
||||||
clap::Error::new(clap::error::ErrorKind::InvalidValue)
|
clap::Error::new(clap::error::ErrorKind::InvalidValue)
|
||||||
})?;
|
})?;
|
||||||
let bytes_len = bytes.len() - 1;
|
|
||||||
for (i, b) in decoded_hex.into_iter().enumerate() {
|
|
||||||
if i == bytes.len() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
bytes[bytes_len - i] = b;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(bytes)
|
let mut addr = [0u8; 20];
|
||||||
|
|
||||||
|
addr.copy_from_slice(&bytes[..12]);
|
||||||
|
Ok(addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
10
testing/tauri/test/.gitignore
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
/build
|
||||||
|
/.svelte-kit
|
||||||
|
/package
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
vite.config.js.timestamp-*
|
||||||
|
vite.config.ts.timestamp-*
|
||||||
7
testing/tauri/test/.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"svelte.svelte-vscode",
|
||||||
|
"tauri-apps.tauri-vscode",
|
||||||
|
"rust-lang.rust-analyzer"
|
||||||
|
]
|
||||||
|
}
|
||||||
3
testing/tauri/test/.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"svelte.enable-ts-plugin": true
|
||||||
|
}
|
||||||
7
testing/tauri/test/README.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# Tauri + SvelteKit + TypeScript
|
||||||
|
|
||||||
|
This template should help get you started developing with Tauri, SvelteKit and TypeScript in Vite.
|
||||||
|
|
||||||
|
## Recommended IDE Setup
|
||||||
|
|
||||||
|
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
|
||||||
16
testing/tauri/test/components.json
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://shadcn-svelte.com/schema.json",
|
||||||
|
"tailwind": {
|
||||||
|
"css": "src/app.css",
|
||||||
|
"baseColor": "zinc"
|
||||||
|
},
|
||||||
|
"aliases": {
|
||||||
|
"components": "$lib/components",
|
||||||
|
"utils": "$lib/utils",
|
||||||
|
"ui": "$lib/components/ui",
|
||||||
|
"hooks": "$lib/hooks",
|
||||||
|
"lib": "$lib"
|
||||||
|
},
|
||||||
|
"typescript": true,
|
||||||
|
"registry": "https://shadcn-svelte.com/registry"
|
||||||
|
}
|
||||||
36
testing/tauri/test/package.json
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"name": "test",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite dev",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
|
"tauri": "export WEBKIT_DISABLE_COMPOSITING_MODE=1; tauri"
|
||||||
|
},
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.1.13",
|
||||||
|
"@tauri-apps/api": "^2",
|
||||||
|
"@tauri-apps/plugin-opener": "^2",
|
||||||
|
"tailwindcss": "^4.1.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@lucide/svelte": "^0.544.0",
|
||||||
|
"@sveltejs/adapter-static": "^3.0.6",
|
||||||
|
"@sveltejs/kit": "^2.9.0",
|
||||||
|
"@sveltejs/vite-plugin-svelte": "^5.0.0",
|
||||||
|
"@tauri-apps/cli": "^2",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"svelte": "^5.0.0",
|
||||||
|
"svelte-check": "^4.0.0",
|
||||||
|
"tailwind-merge": "^3.3.1",
|
||||||
|
"tailwind-variants": "^3.1.1",
|
||||||
|
"tw-animate-css": "^1.3.8",
|
||||||
|
"typescript": "~5.6.2",
|
||||||
|
"vite": "^6.0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
1545
testing/tauri/test/pnpm-lock.yaml
generated
Normal file
7
testing/tauri/test/src-tauri/.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# Generated by Cargo
|
||||||
|
# will have compiled files and executables
|
||||||
|
/target/
|
||||||
|
|
||||||
|
# Generated by Tauri
|
||||||
|
# will have schema files for capabilities auto-completion
|
||||||
|
/gen/schemas
|
||||||
5286
testing/tauri/test/src-tauri/Cargo.lock
generated
Normal file
25
testing/tauri/test/src-tauri/Cargo.toml
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "test"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "A Tauri App"
|
||||||
|
authors = ["you"]
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
# The `_lib` suffix may seem redundant but it is necessary
|
||||||
|
# to make the lib name unique and wouldn't conflict with the bin name.
|
||||||
|
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
|
||||||
|
name = "test_lib"
|
||||||
|
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tauri = { version = "2", features = [] }
|
||||||
|
tauri-plugin-opener = "2"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
|
||||||
3
testing/tauri/test/src-tauri/build.rs
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
tauri_build::build()
|
||||||
|
}
|
||||||
10
testing/tauri/test/src-tauri/capabilities/default.json
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "default",
|
||||||
|
"description": "Capability for the main window",
|
||||||
|
"windows": ["main"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"opener:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
BIN
testing/tauri/test/src-tauri/icons/128x128.png
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
BIN
testing/tauri/test/src-tauri/icons/128x128@2x.png
Normal file
|
After Width: | Height: | Size: 6.8 KiB |
BIN
testing/tauri/test/src-tauri/icons/32x32.png
Normal file
|
After Width: | Height: | Size: 974 B |
BIN
testing/tauri/test/src-tauri/icons/Square107x107Logo.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square142x142Logo.png
Normal file
|
After Width: | Height: | Size: 3.8 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square150x150Logo.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square284x284Logo.png
Normal file
|
After Width: | Height: | Size: 7.6 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square30x30Logo.png
Normal file
|
After Width: | Height: | Size: 903 B |
BIN
testing/tauri/test/src-tauri/icons/Square310x310Logo.png
Normal file
|
After Width: | Height: | Size: 8.4 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square44x44Logo.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square71x71Logo.png
Normal file
|
After Width: | Height: | Size: 2.0 KiB |
BIN
testing/tauri/test/src-tauri/icons/Square89x89Logo.png
Normal file
|
After Width: | Height: | Size: 2.4 KiB |
BIN
testing/tauri/test/src-tauri/icons/StoreLogo.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
testing/tauri/test/src-tauri/icons/icon.icns
Normal file
BIN
testing/tauri/test/src-tauri/icons/icon.ico
Normal file
|
After Width: | Height: | Size: 85 KiB |
BIN
testing/tauri/test/src-tauri/icons/icon.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
14
testing/tauri/test/src-tauri/src/lib.rs
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
|
||||||
|
#[tauri::command]
|
||||||
|
fn greet(name: &str) -> String {
|
||||||
|
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
pub fn run() {
|
||||||
|
tauri::Builder::default()
|
||||||
|
.plugin(tauri_plugin_opener::init())
|
||||||
|
.invoke_handler(tauri::generate_handler![greet])
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while running tauri application");
|
||||||
|
}
|
||||||
6
testing/tauri/test/src-tauri/src/main.rs
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
test_lib::run()
|
||||||
|
}
|
||||||
35
testing/tauri/test/src-tauri/tauri.conf.json
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"productName": "test",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"identifier": "com.test.app",
|
||||||
|
"build": {
|
||||||
|
"beforeDevCommand": " pnpm dev",
|
||||||
|
"devUrl": "http://localhost:1420",
|
||||||
|
"beforeBuildCommand": "pnpm build",
|
||||||
|
"frontendDist": "../build"
|
||||||
|
},
|
||||||
|
"app": {
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"title": "test",
|
||||||
|
"width": 800,
|
||||||
|
"height": 600
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": {
|
||||||
|
"csp": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"active": true,
|
||||||
|
"targets": "all",
|
||||||
|
"icon": [
|
||||||
|
"icons/32x32.png",
|
||||||
|
"icons/128x128.png",
|
||||||
|
"icons/128x128@2x.png",
|
||||||
|
"icons/icon.icns",
|
||||||
|
"icons/icon.ico"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
121
testing/tauri/test/src/app.css
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
@import "tw-animate-css";
|
||||||
|
|
||||||
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--radius: 0.625rem;
|
||||||
|
--background: oklch(1 0 0);
|
||||||
|
--foreground: oklch(0.141 0.005 285.823);
|
||||||
|
--card: oklch(1 0 0);
|
||||||
|
--card-foreground: oklch(0.141 0.005 285.823);
|
||||||
|
--popover: oklch(1 0 0);
|
||||||
|
--popover-foreground: oklch(0.141 0.005 285.823);
|
||||||
|
--primary: oklch(0.21 0.006 285.885);
|
||||||
|
--primary-foreground: oklch(0.985 0 0);
|
||||||
|
--secondary: oklch(0.967 0.001 286.375);
|
||||||
|
--secondary-foreground: oklch(0.21 0.006 285.885);
|
||||||
|
--muted: oklch(0.967 0.001 286.375);
|
||||||
|
--muted-foreground: oklch(0.552 0.016 285.938);
|
||||||
|
--accent: oklch(0.967 0.001 286.375);
|
||||||
|
--accent-foreground: oklch(0.21 0.006 285.885);
|
||||||
|
--destructive: oklch(0.577 0.245 27.325);
|
||||||
|
--border: oklch(0.92 0.004 286.32);
|
||||||
|
--input: oklch(0.92 0.004 286.32);
|
||||||
|
--ring: oklch(0.705 0.015 286.067);
|
||||||
|
--chart-1: oklch(0.646 0.222 41.116);
|
||||||
|
--chart-2: oklch(0.6 0.118 184.704);
|
||||||
|
--chart-3: oklch(0.398 0.07 227.392);
|
||||||
|
--chart-4: oklch(0.828 0.189 84.429);
|
||||||
|
--chart-5: oklch(0.769 0.188 70.08);
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
||||||
|
--sidebar-primary: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.967 0.001 286.375);
|
||||||
|
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-border: oklch(0.92 0.004 286.32);
|
||||||
|
--sidebar-ring: oklch(0.705 0.015 286.067);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.141 0.005 285.823);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
--card: oklch(0.21 0.006 285.885);
|
||||||
|
--card-foreground: oklch(0.985 0 0);
|
||||||
|
--popover: oklch(0.21 0.006 285.885);
|
||||||
|
--popover-foreground: oklch(0.985 0 0);
|
||||||
|
--primary: oklch(0.92 0.004 286.32);
|
||||||
|
--primary-foreground: oklch(0.21 0.006 285.885);
|
||||||
|
--secondary: oklch(0.274 0.006 286.033);
|
||||||
|
--secondary-foreground: oklch(0.985 0 0);
|
||||||
|
--muted: oklch(0.274 0.006 286.033);
|
||||||
|
--muted-foreground: oklch(0.705 0.015 286.067);
|
||||||
|
--accent: oklch(0.274 0.006 286.033);
|
||||||
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
|
--destructive: oklch(0.704 0.191 22.216);
|
||||||
|
--border: oklch(1 0 0 / 10%);
|
||||||
|
--input: oklch(1 0 0 / 15%);
|
||||||
|
--ring: oklch(0.552 0.016 285.938);
|
||||||
|
--chart-1: oklch(0.488 0.243 264.376);
|
||||||
|
--chart-2: oklch(0.696 0.17 162.48);
|
||||||
|
--chart-3: oklch(0.769 0.188 70.08);
|
||||||
|
--chart-4: oklch(0.627 0.265 303.9);
|
||||||
|
--chart-5: oklch(0.645 0.246 16.439);
|
||||||
|
--sidebar: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.274 0.006 286.033);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
testing/tauri/test/src/app.html
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Tauri + SvelteKit + Typescript App</title>
|
||||||
|
%sveltekit.head%
|
||||||
|
</head>
|
||||||
|
<body data-sveltekit-preload-data="hover">
|
||||||
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
13
testing/tauri/test/src/lib/utils.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { clsx, type ClassValue } from "clsx";
|
||||||
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs));
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
export type WithoutChild<T> = T extends { child?: any } ? Omit<T, "child"> : T;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
export type WithoutChildren<T> = T extends { children?: any } ? Omit<T, "children"> : T;
|
||||||
|
export type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;
|
||||||
|
export type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & { ref?: U | null };
|
||||||
7
testing/tauri/test/src/routes/+layout.svelte
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import "../app.css";
|
||||||
|
|
||||||
|
let { children } = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{@render children()}
|
||||||
5
testing/tauri/test/src/routes/+layout.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
// Tauri doesn't have a Node.js server to do proper SSR
|
||||||
|
// so we will use adapter-static to prerender the app (SSG)
|
||||||
|
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
|
||||||
|
export const prerender = true;
|
||||||
|
export const ssr = false;
|
||||||
105
testing/tauri/test/src/routes/+page.svelte
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
<!-- Telegram-like UI in Svelte with Tailwind -->
|
||||||
|
<script lang="ts">
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
|
||||||
|
let currentChat = 'John Doe';
|
||||||
|
let message = '';
|
||||||
|
let messages = [
|
||||||
|
{ id: 1, text: 'Hey there!', own: false },
|
||||||
|
{ id: 2, text: 'Hi! How are you?', own: true },
|
||||||
|
{ id: 3, text: "I'm doing great, thanks for asking!", own: false }
|
||||||
|
];
|
||||||
|
|
||||||
|
let chats = [
|
||||||
|
{ name: 'John Doe', preview: 'Hey, how are you?', active: true },
|
||||||
|
{ name: 'Alice Smith', preview: 'See you tomorrow!', active: false },
|
||||||
|
{ name: 'Bob Wilson', preview: 'Thanks for the help!', active: false }
|
||||||
|
];
|
||||||
|
|
||||||
|
async function sendMessage() {
|
||||||
|
if (!message.trim()) return;
|
||||||
|
|
||||||
|
messages = [...messages, {
|
||||||
|
id: Date.now(),
|
||||||
|
text: message,
|
||||||
|
own: true
|
||||||
|
}];
|
||||||
|
|
||||||
|
// Call Tauri backend
|
||||||
|
try {
|
||||||
|
await invoke('send_message', { content: message });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to send message:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
message = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectChat(chatName: string) {
|
||||||
|
chats = chats.map(chat => ({
|
||||||
|
...chat,
|
||||||
|
active: chat.name === chatName
|
||||||
|
}));
|
||||||
|
currentChat = chatName;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex h-screen bg-slate-900">
|
||||||
|
<!-- Sidebar -->
|
||||||
|
<div class="w-80 bg-slate-800 text-white border-r border-slate-700">
|
||||||
|
<!-- Sidebar Header -->
|
||||||
|
<div class="p-5 border-b border-slate-700">
|
||||||
|
<h3 class="text-lg font-semibold">Chats</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Chat List -->
|
||||||
|
<div class="overflow-y-auto h-[calc(100vh-80px)]">
|
||||||
|
{#each chats as chat}
|
||||||
|
<button
|
||||||
|
class="px-5 w-full text-start py-3 border-b border-slate-700 cursor-pointer hover:bg-slate-700 transition-colors {chat.active ? 'bg-slate-700' : ''}"
|
||||||
|
on:click={() => selectChat(chat.name)}
|
||||||
|
tabindex="0"
|
||||||
|
>
|
||||||
|
<div class="font-medium mb-1">{chat.name}</div>
|
||||||
|
<div class="text-gray-400 text-sm">{chat.preview}</div>
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Main Chat Area -->
|
||||||
|
<div class="flex-1 flex flex-col bg-slate-900">
|
||||||
|
<!-- Chat Header -->
|
||||||
|
<div class="p-4 bg-slate-800 border-b border-slate-700 text-white">
|
||||||
|
<h3 class="text-lg font-semibold">{currentChat}</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Messages -->
|
||||||
|
<div class="flex-1 p-5 overflow-y-auto bg-slate-900">
|
||||||
|
{#each messages as msg}
|
||||||
|
<div class="mb-4 max-w-[70%] {msg.own ? 'ml-auto text-right' : ''}">
|
||||||
|
<div class="inline-block px-3 py-2 rounded-xl text-white {msg.own ? 'bg-blue-600' : 'bg-slate-700'}">
|
||||||
|
{msg.text}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Input Area -->
|
||||||
|
<div class="p-4 bg-slate-800 border-t border-slate-700 flex gap-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={message}
|
||||||
|
on:keydown={(e) => e.key === 'Enter' && sendMessage()}
|
||||||
|
placeholder="Type a message..."
|
||||||
|
class="flex-1 px-4 py-2 bg-slate-900 border border-slate-600 rounded-full text-white placeholder-gray-400 outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
on:click={sendMessage}
|
||||||
|
class="w-10 h-10 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors flex items-center justify-center"
|
||||||
|
>
|
||||||
|
→
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
BIN
testing/tauri/test/static/favicon.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
1
testing/tauri/test/static/svelte.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.9 KiB |
6
testing/tauri/test/static/tauri.svg
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||||
|
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.5 KiB |
1
testing/tauri/test/static/vite.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
15
testing/tauri/test/svelte.config.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Tauri doesn't have a Node.js server to do proper SSR
|
||||||
|
// so we will use adapter-static to prerender the app (SSG)
|
||||||
|
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
|
||||||
|
import adapter from "@sveltejs/adapter-static";
|
||||||
|
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||||
|
|
||||||
|
/** @type {import('@sveltejs/kit').Config} */
|
||||||
|
const config = {
|
||||||
|
preprocess: vitePreprocess(),
|
||||||
|
kit: {
|
||||||
|
adapter: adapter(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
23
testing/tauri/test/tsconfig.json
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"extends": "./.svelte-kit/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"allowJs": true,
|
||||||
|
"checkJs": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"strict": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"paths": {
|
||||||
|
"$lib": ["./src/lib"],
|
||||||
|
"$lib/*": ["./src/lib/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||||
|
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
|
||||||
|
//
|
||||||
|
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||||
|
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||||
|
}
|
||||||
33
testing/tauri/test/vite.config.js
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import { sveltekit } from "@sveltejs/kit/vite";
|
||||||
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
|
|
||||||
|
// @ts-expect-error process is a nodejs global
|
||||||
|
const host = process.env.TAURI_DEV_HOST;
|
||||||
|
|
||||||
|
// https://vitejs.dev/config/
|
||||||
|
export default defineConfig(async () => ({
|
||||||
|
plugins: [tailwindcss(), sveltekit()],
|
||||||
|
|
||||||
|
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
|
||||||
|
//
|
||||||
|
// 1. prevent vite from obscuring rust errors
|
||||||
|
clearScreen: false,
|
||||||
|
// 2. tauri expects a fixed port, fail if that port is not available
|
||||||
|
server: {
|
||||||
|
port: 1420,
|
||||||
|
strictPort: true,
|
||||||
|
host: host || false,
|
||||||
|
hmr: host
|
||||||
|
? {
|
||||||
|
protocol: "ws",
|
||||||
|
host,
|
||||||
|
port: 1421,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
watch: {
|
||||||
|
// 3. tell vite to ignore watching `src-tauri`
|
||||||
|
ignored: ["**/src-tauri/**"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||