From 94a3df08cb3accd82ae0bb6e0971defff5c225a8 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 11:54:16 +0530 Subject: [PATCH 01/11] Added new logging to deno core --- executor/src/deno.ts | 16 ++++++++ executor/src/utils_extension.d.ts | 4 ++ rust-executor/Cargo.toml | 2 + rust-executor/src/js_core/utils_extension.js | 13 ++++++- rust-executor/src/js_core/utils_extension.rs | 39 +++++++++++++++++++- 5 files changed, 71 insertions(+), 3 deletions(-) diff --git a/executor/src/deno.ts b/executor/src/deno.ts index b24d498b5..f4c4dc20b 100644 --- a/executor/src/deno.ts +++ b/executor/src/deno.ts @@ -18,6 +18,22 @@ export const init = internalInit export const path = internalPath export const os = internalOs +console.log = (...args) => { + UTILS.consoleLog(`${args.reduce((acc, cur) => acc += `${cur} `, "")}`) +}; + +console.debug = (...args) => { + UTILS.consoleDebug(`${args.reduce((acc, cur) => acc += `${cur} `, "")}`) +}; + +console.error = (...args) => { + UTILS.consoleError(`${args.reduce((acc, cur) => acc += `${cur} `, "")}`) +}; + +console.warn = (...args) => { + UTILS.consoleWarn(`${args.reduce((acc, cur) => acc += `${cur} `, "")}`) +}; + import "https://deno.land/x/xhr@0.3.0/mod.ts"; import { HTMLElement } from "linkedom" diff --git a/executor/src/utils_extension.d.ts b/executor/src/utils_extension.d.ts index be1a35622..ef5e79dfd 100644 --- a/executor/src/utils_extension.d.ts +++ b/executor/src/utils_extension.d.ts @@ -2,6 +2,10 @@ declare global { interface Utils { getSigningDNA: () => Uint8Array; hash: (data: string | buffer) => string; + consoleLog: (...args) => void; + consoleDebug: (...args) => void; + consoleError: (...args) => void; + consoleWarn: (...args) => void; async loadModule: (path: String) => string; } diff --git a/rust-executor/Cargo.toml b/rust-executor/Cargo.toml index 7eaa23b04..ba5d7be07 100644 --- a/rust-executor/Cargo.toml +++ b/rust-executor/Cargo.toml @@ -54,3 +54,5 @@ warp = "0.3.4" jsonwebtoken = "8.3.0" holochain = "0.1.3" + +tracing = "0.1" diff --git a/rust-executor/src/js_core/utils_extension.js b/rust-executor/src/js_core/utils_extension.js index b04aa1dbe..f570d8a9a 100644 --- a/rust-executor/src/js_core/utils_extension.js +++ b/rust-executor/src/js_core/utils_extension.js @@ -7,7 +7,18 @@ }, loadModule: async (path) => { return core.opAsync("load_module", path); + }, + consoleLog: (args) => { + return core.ops.console_log(args); + }, + consoleDebug: (args) => { + return core.ops.console_debug(args); + }, + consoleError: (args) => { + return core.ops.console_error(args); + }, + consoleWarn: (args) => { + return core.ops.console_warn(args); } }; })(globalThis); - \ No newline at end of file diff --git a/rust-executor/src/js_core/utils_extension.rs b/rust-executor/src/js_core/utils_extension.rs index 453308469..880e96b25 100644 --- a/rust-executor/src/js_core/utils_extension.rs +++ b/rust-executor/src/js_core/utils_extension.rs @@ -1,8 +1,8 @@ use cid::Cid; use deno_core::{error::AnyError, include_js_files, op, Extension}; -use log::info; use multibase::Base; use multihash::{Code, MultihashDigest}; +use tracing::{error, info, debug, warn}; use super::JS_CORE_HANDLE; @@ -20,6 +20,34 @@ fn hash(data: String) -> Result { Ok(format!("Qm{}", encoded_cid)) } +#[op] +fn console_log(data: String) -> Result { + info!("[JSCORE]: {:?}", data); + + Ok(String::from("temp")) +} + +#[op] +fn console_debug(data: String) -> Result { + debug!("[JSCORE]: {:?}", data); + + Ok(String::from("temp")) +} + +#[op] +fn console_error(data: String) -> Result { + error!("[JSCORE]: {:?}", data); + + Ok(String::from("temp")) +} + +#[op] +fn console_warn(data: String) -> Result { + warn!("[JSCORE]: {:?}", data); + + Ok(String::from("temp")) +} + #[op] async fn load_module(path: String) -> Result { info!("Trying to load module: {}", path); @@ -37,7 +65,14 @@ async fn load_module(path: String) -> Result { pub fn build() -> Extension { Extension::builder("utils") .js(include_js_files!(utils "utils_extension.js",)) - .ops(vec![hash::decl(), load_module::decl()]) + .ops(vec![ + hash::decl(), + load_module::decl(), + console_log::decl(), + console_debug::decl(), + console_error::decl(), + console_warn::decl(), + ]) .force_op_registration() .build() } From 82dd6e64dbe68fbeee4c6f68cfd7471032e1b76f Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 11:57:22 +0530 Subject: [PATCH 02/11] Fixed env_logger intialization --- rust-executor/src/init.rs | 4 ++-- rust-executor/src/main.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/rust-executor/src/init.rs b/rust-executor/src/init.rs index 54380314c..50af02b79 100644 --- a/rust-executor/src/init.rs +++ b/rust-executor/src/init.rs @@ -1,4 +1,4 @@ -use log::{info, warn}; +use tracing::{info, warn}; use semver::{Version, VersionReq}; use std::error::Error; use std::fs; @@ -13,7 +13,7 @@ pub fn init( network_bootstrap_seed: Option, ) -> Result<(), Box> { std::env::set_var("RUST_LOG", "info"); - env_logger::init(); + env_logger::try_init(); //Get the default data path if none is provided let app_data_path = match data_path { diff --git a/rust-executor/src/main.rs b/rust-executor/src/main.rs index 336876550..71b2ff9a5 100644 --- a/rust-executor/src/main.rs +++ b/rust-executor/src/main.rs @@ -8,7 +8,7 @@ mod wallet; pub mod init; mod pubsub; -use log::{error, info}; +use tracing::{error, info}; use rust_executor::Ad4mConfig; use std::env; @@ -17,7 +17,7 @@ use js_core::JsCore; #[tokio::main(flavor = "multi_thread")] async fn main() { env::set_var("RUST_LOG", "rust_executor=info"); - env_logger::init(); + env_logger::try_init(); let mut config = Ad4mConfig::default(); config.prepare(); From 5906d09da690dc67c9aee9e352b63c600c04cead Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 11:58:12 +0530 Subject: [PATCH 03/11] Removed unused path functions --- ui/src-tauri/src/config.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/ui/src-tauri/src/config.rs b/ui/src-tauri/src/config.rs index 58104db68..fbe3ffd83 100644 --- a/ui/src-tauri/src/config.rs +++ b/ui/src-tauri/src/config.rs @@ -10,18 +10,6 @@ pub fn log_path() -> PathBuf { data_path().join("ad4m.log") } -pub fn binary_path() -> PathBuf { - data_path().join("binary") -} - -pub fn holochain_binary_path() -> PathBuf { - if cfg!(windows) { - binary_path().join("holochain.exe") - } else { - binary_path().join("holochain") - } -} - #[cfg(feature = "custom-protocol")] pub fn app_url() -> String { "index.html".to_string() From 9a1e9dc34763f12f5ff9138d82f10abe37394e34 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 11:59:01 +0530 Subject: [PATCH 04/11] Updated the rust-executor lib to work properly in the launcher --- rust-executor/src/lib.rs | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/rust-executor/src/lib.rs b/rust-executor/src/lib.rs index 18f06b161..9e10aa230 100644 --- a/rust-executor/src/lib.rs +++ b/rust-executor/src/lib.rs @@ -5,12 +5,14 @@ mod holochain_service; mod js_core; mod utils; mod wallet; +use tokio; + pub mod init; mod pubsub; -use log::{error, info}; use std::env; +use tracing::{info, error}; //use graphql::start_server; use js_core::JsCore; @@ -19,7 +21,7 @@ pub use config::Ad4mConfig; /// Runs the GraphQL server and the deno core runtime pub async fn run(mut config: Ad4mConfig) { - env::set_var("RUST_LOG", "rust_executor=trace,warp::server"); + env::set_var("RUST_LOG", "rust_executor=info,warp::server"); let _ = env_logger::try_init(); config.prepare(); @@ -29,19 +31,23 @@ pub async fn run(mut config: Ad4mConfig) { info!("js_core initialized."); info!("Starting GraphQL..."); - match graphql::start_server( - js_core_handle, - config.gql_port.expect("Did not get gql port"), - ) - .await - { - Ok(_) => { - info!("GraphQL server stopped."); - std::process::exit(0); - } - Err(err) => { - error!("GraphQL server stopped with error: {}", err); - std::process::exit(1); - } - } + + tokio::task::spawn_blocking(move || { + let result = graphql::start_server( + js_core_handle, + config.gql_port.expect("Did not get gql port"), + ); + tokio::runtime::Handle::current().block_on(async { + match result.await { + Ok(_) => { + info!("GraphQL server stopped."); + std::process::exit(0); + } + Err(err) => { + error!("GraphQL server stopped with error: {}", err); + std::process::exit(1); + } + } + }); + }); } From e81385aadfc0c7d078c89a5bf0438c5fc958b2a3 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 12:01:37 +0530 Subject: [PATCH 05/11] Updatted dependencies --- Cargo.lock | 4 ++++ ui/src-tauri/Cargo.toml | 3 +++ 2 files changed, 7 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 855aa2fa9..aad52dafa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,6 +75,7 @@ dependencies = [ "portpicker", "remove_dir_all", "reqwest", + "rust-executor", "serde", "serde_json", "sysinfo 0.23.13", @@ -82,6 +83,8 @@ dependencies = [ "tauri-build", "tauri-plugin-positioner", "tokio", + "tracing", + "tracing-subscriber 0.2.25", "uuid 0.8.2", ] @@ -8846,6 +8849,7 @@ dependencies = [ "serde_json", "tokio", "tokio-stream", + "tracing", "url 2.3.1", "uuid 1.3.0", "warp", diff --git a/ui/src-tauri/Cargo.toml b/ui/src-tauri/Cargo.toml index 5150da465..e1ebc334d 100644 --- a/ui/src-tauri/Cargo.toml +++ b/ui/src-tauri/Cargo.toml @@ -35,6 +35,9 @@ tauri-plugin-positioner = { version = "1.0", features = ["system-tray"] } remove_dir_all = "0.7.0" reqwest = { version = "0.11", features = ["json"] } ad4m-client = { path = "../../rust-client" } +rust-executor = { path = "../../rust-executor" } +tracing = "0.1" +tracing-subscriber = "0.2" [features] # by default Tauri runs in production mode From c412dc1b951cf4233f6960d27bd24fd1ed82bd5f Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 12:02:48 +0530 Subject: [PATCH 06/11] Got rust-executor working in the laucher --- ui/src-tauri/src/main.rs | 125 +++++++++++++++++++-------------------- 1 file changed, 62 insertions(+), 63 deletions(-) diff --git a/ui/src-tauri/src/main.rs b/ui/src-tauri/src/main.rs index 417ebd7bf..b6d1b5967 100644 --- a/ui/src-tauri/src/main.rs +++ b/ui/src-tauri/src/main.rs @@ -3,13 +3,17 @@ windows_subsystem = "windows" )] +use log::info; +use rust_executor::Ad4mConfig; use tauri::LogicalSize; use tauri::Size; +use tracing_subscriber::EnvFilter; +use tracing_subscriber::fmt::format; +use std::env; use std::sync::Mutex; extern crate remove_dir_all; use remove_dir_all::*; -use config::holochain_binary_path; use config::app_url; use logs::setup_logs; use menu::build_menu; @@ -43,6 +47,8 @@ use crate::menu::{handle_menu_event, open_logs_folder}; use crate::util::has_processes_running; use crate::util::{find_and_kill_processes, create_main_window, save_executor_port}; +use tracing_subscriber::{fmt::format::FmtSpan, FmtSubscriber}; + // the payload type must implement `Serialize` and `Clone`. #[derive(Clone, serde::Serialize)] struct Payload { @@ -64,6 +70,22 @@ pub struct AppState { } fn main() { + env::set_var("RUST_LOG", "rust_executor=info,warp::server"); + + let format = format::debug_fn(|writer, field, value| { + write!(writer, "{:?}", value) + }); + + let filter = EnvFilter::from_default_env(); + + let subscriber = tracing_subscriber::fmt() + .with_env_filter(filter) + .fmt_fields(format) + .finish(); + + tracing::subscriber::set_global_default(subscriber) + .expect("Failed to set tracing subscriber"); + let app_name = if std::env::consts::OS == "windows" { "AD4M.exe" } else { "AD4M" }; if has_processes_running(app_name) > 1 { println!("AD4M is already running"); @@ -88,22 +110,18 @@ fn main() { find_and_kill_processes("holochain"); - let prepare = Command::new_sidecar("ad4m-host") - .expect("Failed to create ad4m command") - .args(["prepare"]) - .status() - .expect("Failed to run ad4m prepare"); - assert!(prepare.success()); - - if !holochain_binary_path().exists() { - log::info!("init command by copy holochain binary"); - let status = Command::new_sidecar("ad4m-host") - .expect("Failed to create ad4m command") - .args(["init"]) - .status() - .expect("Failed to run ad4m init"); - assert!(status.success()); - } + match rust_executor::init::init( + Some(String::from(data_path().to_str().unwrap())), + None + ) { + Ok(()) => { + println!("Ad4m initialized sucessfully"); + }, + Err(e) => { + println!("Ad4m initialization failed: {}", e); + std::process::exit(1); + } + }; let req_credential = Uuid::new_v4().to_string(); @@ -147,57 +165,38 @@ fn main() { open_logs_folder(); }); - let (mut rx, _child) = Command::new_sidecar("ad4m-host") - .expect("Failed to create ad4m command") - .args([ - "serve", - "--port", &free_port.to_string(), - "--reqCredential", &req_credential, - ]) - .spawn() - .expect("Failed to spawn ad4m serve"); + let mut config = Ad4mConfig::default(); + config.admin_credential = Some(req_credential.to_string()); + config.app_data_path = Some(String::from(data_path().to_str().unwrap())); + config.gql_port = Some(free_port); + config.network_bootstrap_seed = None; let handle = app.handle(); - tauri::async_runtime::spawn(async move { - while let Some(event) = rx.recv().await { - match event.clone() { - CommandEvent::Stdout(line) => { - log::info!("{}", line); - - if line.contains("GraphQL server started, Unlock the agent to start holohchain") { - let url = app_url(); - log::info!("Executor started on: {:?}", url); - let _ = splashscreen_clone.hide(); - create_tray_message_windows(&handle); - let main = get_main_window(&handle); - main.emit("ready", Payload { message: "ad4m-executor is ready".into() }).unwrap(); - } - }, - CommandEvent::Stderr(line) => { - let is_prolog_redefined_line = line.starts_with("Warning: /var") || line.starts_with("Warning: Redefined") || line.starts_with("Warning: Previously"); - if !is_prolog_redefined_line { - log::error!("{}", line); - } - } - CommandEvent::Terminated(line) => { - log::info!("Terminated {:?}", line); - let main = get_main_window(&handle); - - if let Ok(true) = &splashscreen_clone.is_visible() { - log_error(&splashscreen_clone, "Something went wrong while starting ad4m-executor please check the logs"); - } - - if let Ok(true) = main.is_visible() { - log_error(&main, "There was an error with the AD4M Launcher. Restarting may fix this, otherwise please contact the AD4M team for support."); - } - - log::info!("Terminated {:?}", line); - }, - CommandEvent::Error(line) => log::info!("Error {:?}", line), - _ => log::error!("{:?}", event), + + + + async fn test(config: Ad4mConfig, splashscreen_clone: Window, handle: &AppHandle) { + let my_closure = || { + let url = app_url(); + log::info!("Executor clone on: {:?}", url); + let _ = splashscreen_clone.hide(); + create_tray_message_windows(&handle); + let main = get_main_window(&handle); + main.emit("ready", Payload { message: "ad4m-executor is ready".into() }).unwrap(); + }; + + match rust_executor::run(config.clone()).await { + () => { + my_closure(); + + info!("GraphQL server stopped.") } } + } + + tauri::async_runtime::spawn(async move { + test(config.clone(), splashscreen.clone(), &handle).await }); Ok(()) From 71c51f10c45040efb76cc3250afa9c7e67999e69 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 12:37:40 +0530 Subject: [PATCH 07/11] Updated logging --- .../src/graphql/mutation_resolvers.rs | 4 +- .../holochain_service_extension.rs | 2 +- rust-executor/src/holochain_service/mod.rs | 2 +- rust-executor/src/js_core/mod.rs | 6 +-- .../src/js_core/string_module_loader.rs | 2 +- rust-executor/src/js_core/wallet_extension.rs | 2 +- rust-executor/src/pubsub.rs | 3 +- ui/src-tauri/src/logs.rs | 28 ------------- ui/src-tauri/src/main.rs | 41 +++++++++---------- 9 files changed, 30 insertions(+), 60 deletions(-) delete mode 100644 ui/src-tauri/src/logs.rs diff --git a/rust-executor/src/graphql/mutation_resolvers.rs b/rust-executor/src/graphql/mutation_resolvers.rs index 9e714fe71..e3a7202f9 100644 --- a/rust-executor/src/graphql/mutation_resolvers.rs +++ b/rust-executor/src/graphql/mutation_resolvers.rs @@ -1,6 +1,6 @@ #![allow(non_snake_case)] use juniper::{graphql_object, graphql_value, FieldResult}; -use log::debug; +use tracing::debug; use super::graphql_types::*; use super::utils::get_capabilies; @@ -823,7 +823,7 @@ impl Mutation { {{ mutations: {}, uuid: "{}", status: {} }}, {{ capabilities: {} }} ))"#, - mutations_json, uuid, status, capabilities + mutations_json, uuid, status, capabilities ); let result = js.execute(script).await?; let result: JsResultType = serde_json::from_str(&result)?; diff --git a/rust-executor/src/holochain_service/holochain_service_extension.rs b/rust-executor/src/holochain_service/holochain_service_extension.rs index ab14ce61e..14bc406f6 100644 --- a/rust-executor/src/holochain_service/holochain_service_extension.rs +++ b/rust-executor/src/holochain_service/holochain_service_extension.rs @@ -6,7 +6,7 @@ use holochain::{ Signature, ZomeCallResponse, }, }; -use log::info; +use tracing::info; use crate::holochain_service::{HolochainService, LocalConductorConfig}; diff --git a/rust-executor/src/holochain_service/mod.rs b/rust-executor/src/holochain_service/mod.rs index 135f47748..a766a538d 100644 --- a/rust-executor/src/holochain_service/mod.rs +++ b/rust-executor/src/holochain_service/mod.rs @@ -16,7 +16,7 @@ use holochain::prelude::{ Signature, Timestamp, TransportConfig, ZomeCallResponse, ZomeCallUnsigned, }; use holochain::test_utils::itertools::Either; -use log::info; +use tracing::info; use rand::Rng; use serde::{Deserialize, Serialize}; use tokio::sync::{mpsc, oneshot, Mutex}; diff --git a/rust-executor/src/js_core/mod.rs b/rust-executor/src/js_core/mod.rs index 3cd657d70..0c3716f03 100644 --- a/rust-executor/src/js_core/mod.rs +++ b/rust-executor/src/js_core/mod.rs @@ -4,7 +4,7 @@ use deno_core::resolve_url_or_path; use deno_runtime::worker::MainWorker; use deno_runtime::{permissions::PermissionsContainer, BootstrapOptions}; use holochain::prelude::{ExternIO, Signal}; -use log::{error, info}; +use tracing::{error, info}; use once_cell::sync::Lazy; use std::env::current_dir; use std::sync::Arc; @@ -215,8 +215,8 @@ impl JsCore { let wrapped_script = format!( r#" globalThis.asyncResult = undefined; - (async () => {{ - globalThis.asyncResult = ({}); + (async () => {{ + globalThis.asyncResult = ({}); }})(); "#, script diff --git a/rust-executor/src/js_core/string_module_loader.rs b/rust-executor/src/js_core/string_module_loader.rs index c191cb898..d7e7df2f9 100644 --- a/rust-executor/src/js_core/string_module_loader.rs +++ b/rust-executor/src/js_core/string_module_loader.rs @@ -7,7 +7,7 @@ use deno_core::ModuleSpecifier; use deno_core::ModuleType; use deno_core::ResolutionKind; use deno_runtime::deno_core::error::AnyError; -use log::info; +use tracing::info; use std::collections::HashMap; use std::pin::Pin; diff --git a/rust-executor/src/js_core/wallet_extension.rs b/rust-executor/src/js_core/wallet_extension.rs index ff250291b..11f408fc6 100644 --- a/rust-executor/src/js_core/wallet_extension.rs +++ b/rust-executor/src/js_core/wallet_extension.rs @@ -1,7 +1,7 @@ use base64::{engine::general_purpose as base64engine, Engine as _}; use deno_core::{anyhow::anyhow, error::AnyError, include_js_files, op, Extension}; use did_key::{CoreSign, PatchedKeyPair}; -use log::error; +use tracing::error; use serde::{Deserialize, Serialize}; use crate::wallet::Wallet; diff --git a/rust-executor/src/pubsub.rs b/rust-executor/src/pubsub.rs index b7c008cfc..6d3459744 100644 --- a/rust-executor/src/pubsub.rs +++ b/rust-executor/src/pubsub.rs @@ -3,8 +3,7 @@ use crate::graphql::graphql_types::GetValue; use futures::Stream; use futures::StreamExt; use juniper::{graphql_value, FieldError, FieldResult}; -use log::debug; -use log::error; +use tracing::{debug, error}; use serde::de::DeserializeOwned; use std::collections::HashMap; use std::pin::Pin; diff --git a/ui/src-tauri/src/logs.rs b/ui/src-tauri/src/logs.rs deleted file mode 100644 index dfa33a675..000000000 --- a/ui/src-tauri/src/logs.rs +++ /dev/null @@ -1,28 +0,0 @@ -use log::LevelFilter; -use log4rs::{ - append::file::FileAppender, - config::{Appender, Root}, - encode::pattern::PatternEncoder, - Config, -}; -use std::fs; - -use crate::config::{log_path}; - -pub fn setup_logs() -> Result<(), String> { - let _ = fs::remove_file(log_path()); - - let logfile = FileAppender::builder() - .encoder(Box::new(PatternEncoder::new("[{d}] {l} - {m}\n"))) - .build(log_path()) - .map_err(|err| format!("Could not build log config: {:?}", err))?; - - let config = Config::builder() - .appender(Appender::builder().build("logfile", Box::new(logfile))) - .build(Root::builder().appender("logfile").build(LevelFilter::Info)) - .map_err(|err| format!("Could not init log config: {:?}", err))?; - - log4rs::init_config(config).map_err(|err| format!("Could not init log config: {:?}", err))?; - - Ok(()) -} \ No newline at end of file diff --git a/ui/src-tauri/src/main.rs b/ui/src-tauri/src/main.rs index b6d1b5967..d9451b59b 100644 --- a/ui/src-tauri/src/main.rs +++ b/ui/src-tauri/src/main.rs @@ -3,19 +3,21 @@ windows_subsystem = "windows" )] -use log::info; +use tracing::{info, error}; use rust_executor::Ad4mConfig; use tauri::LogicalSize; use tauri::Size; use tracing_subscriber::EnvFilter; use tracing_subscriber::fmt::format; use std::env; +use std::fs; +use std::fs::File; +use std::sync::Arc; use std::sync::Mutex; extern crate remove_dir_all; use remove_dir_all::*; use config::app_url; -use logs::setup_logs; use menu::build_menu; use system_tray::{ build_system_tray, handle_system_tray_event }; use tauri::{ @@ -30,7 +32,6 @@ use uuid::Uuid; mod config; mod util; -mod logs; mod system_tray; mod menu; mod commands; @@ -41,12 +42,13 @@ use crate::commands::proxy::{get_proxy, login_proxy, setup_proxy, stop_proxy}; use crate::commands::state::{get_port, request_credential}; use crate::commands::app::{close_application, close_main_window, clear_state, open_tray, open_tray_message}; use crate::config::data_path; +use crate::config::log_path; use crate::util::create_tray_message_windows; use crate::util::find_port; use crate::menu::{handle_menu_event, open_logs_folder}; use crate::util::has_processes_running; use crate::util::{find_and_kill_processes, create_main_window, save_executor_port}; - +use std::io::{self, Write}; use tracing_subscriber::{fmt::format::FmtSpan, FmtSubscriber}; // the payload type must implement `Serialize` and `Clone`. @@ -70,9 +72,15 @@ pub struct AppState { } fn main() { - env::set_var("RUST_LOG", "rust_executor=info,warp::server"); + env::set_var("RUST_LOG", "rust_executor=info,error,warn,debugad4m-launcher=info,warn,error"); + + let _ = fs::remove_file(log_path()); + + let file = File::create(log_path()).unwrap(); + let file = Arc::new(Mutex::new(file)); - let format = format::debug_fn(|writer, field, value| { + let format = format::debug_fn(move |writer, _field, value| { + let _ = writeln!(file.lock().unwrap(), "{:?}" value); write!(writer, "{:?}", value) }); @@ -96,13 +104,9 @@ fn main() { let _ = remove_dir_all(data_path()); } - if let Err(err) = setup_logs() { - println!("Error setting up the logs: {:?}", err); - } - let free_port = find_port(12000, 13000); - log::info!("Free port: {:?}", free_port); + info!("Free port: {:?}", free_port); save_executor_port(free_port); @@ -157,10 +161,8 @@ fn main() { let splashscreen = app.get_window("splashscreen").unwrap(); - let splashscreen_clone = splashscreen.clone(); - let _id = splashscreen.listen("copyLogs", |event| { - log::info!("got window event-name with payload {:?} {:?}", event, event.payload()); + info!("got window event-name with payload {:?} {:?}", event, event.payload()); open_logs_folder(); }); @@ -173,13 +175,10 @@ fn main() { let handle = app.handle(); - - - - async fn test(config: Ad4mConfig, splashscreen_clone: Window, handle: &AppHandle) { + async fn spawn_executor(config: Ad4mConfig, splashscreen_clone: Window, handle: &AppHandle) { let my_closure = || { let url = app_url(); - log::info!("Executor clone on: {:?}", url); + info!("Executor clone on: {:?}", url); let _ = splashscreen_clone.hide(); create_tray_message_windows(&handle); let main = get_main_window(&handle); @@ -196,7 +195,7 @@ fn main() { } tauri::async_runtime::spawn(async move { - test(config.clone(), splashscreen.clone(), &handle).await + spawn_executor(config.clone(), splashscreen.clone(), &handle).await }); Ok(()) @@ -234,7 +233,7 @@ fn main() { }; }); } - Err(err) => log::error!("Error building the app: {:?}", err), + Err(err) => error!("Error building the app: {:?}", err), } } From b51aa02a1c032ade4a7d482dd0862ab6407690e3 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 14:29:24 +0530 Subject: [PATCH 08/11] Fixed syntax error --- ui/src-tauri/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/src-tauri/src/main.rs b/ui/src-tauri/src/main.rs index d9451b59b..44380d439 100644 --- a/ui/src-tauri/src/main.rs +++ b/ui/src-tauri/src/main.rs @@ -80,7 +80,7 @@ fn main() { let file = Arc::new(Mutex::new(file)); let format = format::debug_fn(move |writer, _field, value| { - let _ = writeln!(file.lock().unwrap(), "{:?}" value); + let _ = writeln!(file.lock().unwrap(), "{:?}", value); write!(writer, "{:?}", value) }); From 1ef04aa3464249c7900ed27cd5e10857664c62df Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 14:48:16 +0530 Subject: [PATCH 09/11] Fix no ad4m folder found error --- ui/src-tauri/src/main.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ui/src-tauri/src/main.rs b/ui/src-tauri/src/main.rs index 44380d439..a2838fde9 100644 --- a/ui/src-tauri/src/main.rs +++ b/ui/src-tauri/src/main.rs @@ -74,7 +74,13 @@ pub struct AppState { fn main() { env::set_var("RUST_LOG", "rust_executor=info,error,warn,debugad4m-launcher=info,warn,error"); - let _ = fs::remove_file(log_path()); + if !data_path().exists() { + let _ = fs::create_dir_all(data_path()); + } + + if log_path().exists() { + let _ = fs::remove_file(log_path()); + } let file = File::create(log_path()).unwrap(); let file = Arc::new(Mutex::new(file)); @@ -100,10 +106,6 @@ fn main() { return; } - if data_path().exists() && !data_path().join("ad4m").join("agent.json").exists() { - let _ = remove_dir_all(data_path()); - } - let free_port = find_port(12000, 13000); info!("Free port: {:?}", free_port); From 0bdb04500bae8772508af0ef2844a6328ac069bd Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 15:03:50 +0530 Subject: [PATCH 10/11] Added a seperate method for laucher thats uses tokio --- rust-executor/src/lib.rs | 30 ++++++++++++++++++++++++++++++ ui/src-tauri/src/main.rs | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/rust-executor/src/lib.rs b/rust-executor/src/lib.rs index 9e10aa230..c4b84d1e4 100644 --- a/rust-executor/src/lib.rs +++ b/rust-executor/src/lib.rs @@ -32,6 +32,36 @@ pub async fn run(mut config: Ad4mConfig) { info!("Starting GraphQL..."); + match graphql::start_server( + js_core_handle, + config.gql_port.expect("Did not get gql port"), + ) + .await + { + Ok(_) => { + info!("GraphQL server stopped."); + std::process::exit(0); + } + Err(err) => { + error!("GraphQL server stopped with error: {}", err); + std::process::exit(1); + } + }; +} + +/// Runs the GraphQL server and the deno core runtime +pub async fn run_with_tokio(mut config: Ad4mConfig) { + env::set_var("RUST_LOG", "rust_executor=info,warp::server"); + let _ = env_logger::try_init(); + config.prepare(); + + info!("Starting js_core..."); + let mut js_core_handle = JsCore::start(config.clone()).await; + js_core_handle.initialized().await; + info!("js_core initialized."); + + info!("Starting GraphQL..."); + tokio::task::spawn_blocking(move || { let result = graphql::start_server( js_core_handle, diff --git a/ui/src-tauri/src/main.rs b/ui/src-tauri/src/main.rs index a2838fde9..bdadaa838 100644 --- a/ui/src-tauri/src/main.rs +++ b/ui/src-tauri/src/main.rs @@ -187,7 +187,7 @@ fn main() { main.emit("ready", Payload { message: "ad4m-executor is ready".into() }).unwrap(); }; - match rust_executor::run(config.clone()).await { + match rust_executor::run_with_tokio(config.clone()).await { () => { my_closure(); From fd9e66e549d339edffccca94b0b9dd74650d70b1 Mon Sep 17 00:00:00 2001 From: Fayeed Pawaskar Date: Thu, 27 Jul 2023 16:36:34 +0530 Subject: [PATCH 11/11] updated clear_state --- ui/src-tauri/src/commands/app.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ui/src-tauri/src/commands/app.rs b/ui/src-tauri/src/commands/app.rs index 9e8667e7a..8ce33728a 100644 --- a/ui/src-tauri/src/commands/app.rs +++ b/ui/src-tauri/src/commands/app.rs @@ -65,10 +65,6 @@ pub fn open_tray_message(app_handle: tauri::AppHandle) { #[tauri::command] pub fn clear_state(app_handle: tauri::AppHandle) { - find_and_kill_processes("ad4m-host"); - - find_and_kill_processes("holochain"); - let _ = remove_dir_all(data_path()); app_handle.restart();