Skip to content

Commit

Permalink
Merge branch 'dev' into extension
Browse files Browse the repository at this point in the history
  • Loading branch information
CheatCod committed Jun 16, 2024
2 parents b7bf507 + 308f1bf commit 93708c9
Show file tree
Hide file tree
Showing 25 changed files with 215 additions and 150 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnPaste": true,
"editor.formatOnSave": true
}
3 changes: 1 addition & 2 deletions core/src/db/read.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::{
error::Error, output_types::ClientEvent,
prelude::LODESTONE_EPOCH_MIL, events::EventQuery,
error::Error, events::EventQuery, output_types::ClientEvent, prelude::LODESTONE_EPOCH_MIL,
};

use color_eyre::eyre::Context;
Expand Down
2 changes: 1 addition & 1 deletion core/src/deno_ops/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod events;
pub mod instance_control;
pub mod prelude;
pub mod prelude;
8 changes: 5 additions & 3 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ pub struct Error {
pub source: color_eyre::Report,
}


impl Error {
pub fn log(self) -> Self {
error!("An error occurred ({kind}): {source}", kind = self.kind, source = self.source);
error!(
"An error occurred ({kind}): {source}",
kind = self.kind,
source = self.source
);
self
}
}
Expand All @@ -47,7 +50,6 @@ impl Error {
}
}


impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down
1 change: 0 additions & 1 deletion core/src/global_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ impl GlobalSettings {
pub fn playit_enabled(&self) -> bool {
self.global_settings_data.playit_enabled
}

}

impl AsRef<GlobalSettingsData> for GlobalSettings {
Expand Down
5 changes: 4 additions & 1 deletion core/src/handlers/global_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ pub fn get_global_settings_routes(state: AppState) -> Router {
.route("/global_settings/name", put(change_core_name))
.route("/global_settings/safe_mode", put(change_core_safe_mode))
.route("/global_settings/domain", put(change_domain))
.route("/global_settings/playit_enabled", put(change_core_playit_enabled))
.route(
"/global_settings/playit_enabled",
put(change_core_playit_enabled),
)
.with_state(state)
}
60 changes: 41 additions & 19 deletions core/src/handlers/instance_macro.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum::{
extract::Path,
routing::{get, put, post},
routing::{get, post, put},
Json, Router,
};

Expand All @@ -10,6 +10,7 @@ use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::traits::t_configurable::manifest::SettingManifest;
use crate::{
auth::user::UserAction,
error::{Error, ErrorKind},
Expand All @@ -19,13 +20,12 @@ use crate::{
types::InstanceUuid,
AppState,
};
use crate::traits::t_configurable::manifest::SettingManifest;

#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct GetConfigResponse {
pub config: IndexMap<String, SettingManifest>,
pub message: Option<String>,
pub message: Option<String>,
pub error: Option<ErrorKind>,
}

Expand Down Expand Up @@ -145,22 +145,36 @@ pub async fn get_macro_configs(

let mut config = instance.get_macro_config(&macro_name).await?;

match instance.validate_local_config(&macro_name, Some(&config)).await {
match instance
.validate_local_config(&macro_name, Some(&config))
.await
{
Ok(local_value) => {
local_value.iter().for_each(|(setting_id, local_cache)| {
config[setting_id].set_optional_value(local_cache.get_value().clone()).unwrap();
config[setting_id]
.set_optional_value(local_cache.get_value().clone())
.unwrap();
});
Ok(Json(GetConfigResponse{ config, message: None, error: None }))
},
Err(e) => {
match e.kind {
ErrorKind::NotFound => {
Ok(Json(GetConfigResponse { config, message: Some("Local config cache not found".to_string()), error: Some(ErrorKind::NotFound) }))
},
_ => {
Ok(Json(GetConfigResponse { config, message: Some("There is a mismatch between a config type and its locally-stored value".to_string()), error: Some(ErrorKind::Internal) }))
}
}
Ok(Json(GetConfigResponse {
config,
message: None,
error: None,
}))
}
Err(e) => match e.kind {
ErrorKind::NotFound => Ok(Json(GetConfigResponse {
config,
message: Some("Local config cache not found".to_string()),
error: Some(ErrorKind::NotFound),
})),
_ => Ok(Json(GetConfigResponse {
config,
message: Some(
"There is a mismatch between a config type and its locally-stored value"
.to_string(),
),
error: Some(ErrorKind::Internal),
})),
},
}
}
Expand All @@ -179,7 +193,9 @@ pub async fn store_config_to_local(
source: eyre!("Instance not found"),
})?;

instance.store_macro_config_to_local(&macro_name, &config_to_store).await?;
instance
.store_macro_config_to_local(&macro_name, &config_to_store)
.await?;
Ok(())
}

Expand All @@ -188,8 +204,14 @@ pub fn get_instance_macro_routes(state: AppState) -> Router {
.route("/instance/:uuid/macro/run/:macro_name", put(run_macro))
.route("/instance/:uuid/macro/kill/:pid", put(kill_macro))
.route("/instance/:uuid/macro/list", get(get_instance_macro_list))
.route("/instance/:uuid/macro/config/get/:macro_name", get(get_macro_configs))
.route("/instance/:uuid/macro/config/store/:macro_name", post(store_config_to_local))
.route(
"/instance/:uuid/macro/config/get/:macro_name",
get(get_macro_configs),
)
.route(
"/instance/:uuid/macro/config/store/:macro_name",
post(store_config_to_local),
)
.route("/instance/:uuid/task/list", get(get_instance_task_list))
.route(
"/instance/:uuid/history/list",
Expand Down
11 changes: 4 additions & 7 deletions core/src/handlers/instance_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,10 @@ pub async fn start_instance(
user_id: requester.uid.clone(),
user_name: requester.username.clone(),
};
let instance = state
.instances
.get(&uuid)
.ok_or_else(|| Error {
kind: ErrorKind::NotFound,
source: eyre!("Instance not found"),
})?;
let instance = state.instances.get(&uuid).ok_or_else(|| Error {
kind: ErrorKind::NotFound,
source: eyre!("Instance not found"),
})?;
let port = instance.port().await;

// check if port is already in use
Expand Down
2 changes: 1 addition & 1 deletion core/src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ pub mod instance_players;
pub mod instance_server;
pub mod instance_setup_configs;
pub mod monitor;
pub mod playitgg;
pub mod setup;
pub mod system;
pub mod users;
pub mod playitgg;
mod util;
pub mod extension;
9 changes: 7 additions & 2 deletions core/src/handlers/playitgg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use axum::{routing::{post, get}, Router};
use crate::playitgg::{stop_cli, generate_signup_link, start_cli, verify_key, cli_is_running, get_tunnels};
use crate::playitgg::{
cli_is_running, generate_signup_link, get_tunnels, start_cli, stop_cli, verify_key,
};
use axum::{
routing::{get, post},
Router,
};

use crate::AppState;

Expand Down
4 changes: 2 additions & 2 deletions core/src/implementations/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl GenericInstance {
path: PathBuf,
dot_lodestone_config: DotLodestoneConfig,
setup_value: SetupValue,
progression_event_id : &ProgressionEventID,
progression_event_id: &ProgressionEventID,
event_broadcaster: EventBroadcaster,
core_macro_executor: MacroExecutor,
) -> Result<Self, Error> {
Expand Down Expand Up @@ -145,7 +145,7 @@ impl GenericInstance {
.call(ProcedureCallInner::SetupInstance {
dot_lodestone_config: dot_lodestone_config.clone(),
setup_value,
progression_event_id : progression_event_id.inner(),
progression_event_id: progression_event_id.inner(),
path: path.clone(),
})
.await?;
Expand Down
80 changes: 52 additions & 28 deletions core/src/implementations/minecraft/macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@ use async_trait::async_trait;
use color_eyre::eyre::{eyre, Context};
use indexmap::IndexMap;

use crate::error::ErrorKind;
use crate::macro_executor::MacroExecutor;
use crate::traits::t_configurable::manifest::{
ConfigurableValue, SettingLocalCache, SettingManifest,
};
use crate::{
error::Error,
events::CausedBy,
macro_executor::{DefaultWorkerOptionGenerator, MacroPID, SpawnResult},
traits::t_macro::{HistoryEntry, MacroEntry, TMacro, TaskEntry},
};
use crate::error::ErrorKind;
use crate::macro_executor::MacroExecutor;
use crate::traits::t_configurable::manifest::{
SettingLocalCache,
SettingManifest,
ConfigurableValue,
};

use super::MinecraftInstance;

Expand Down Expand Up @@ -128,7 +126,13 @@ impl TMacro for MinecraftInstance {
// compose config injection code
let config_code = match configs {
Some(config_map) => {
let tokens: Vec<_> = config_map.get_index(0).unwrap().1.get_identifier().split('|').collect();
let tokens: Vec<_> = config_map
.get_index(0)
.unwrap()
.1
.get_identifier()
.split('|')
.collect();
let config_var_name = tokens[0];
let mut code_string = format!("let {config_var_name} = {{\r\n");

Expand All @@ -139,10 +143,12 @@ impl TMacro for MinecraftInstance {
ConfigurableValue::Enum(str_val) => format!("\'{str_val}\'"),
ConfigurableValue::Boolean(b_val) => b_val.to_string(),
ConfigurableValue::Float(num) => num.to_string(),
_ => return Err(Error{
kind: ErrorKind::Internal,
source: eyre!("Unsupported config data type"),
}),
_ => {
return Err(Error {
kind: ErrorKind::Internal,
source: eyre!("Unsupported config data type"),
})
}
},
None => "undefined".to_string(),
};
Expand All @@ -152,7 +158,7 @@ impl TMacro for MinecraftInstance {
code_string.push_str("};\r\n");

Some(code_string)
},
}
None => None,
};

Expand Down Expand Up @@ -190,7 +196,10 @@ impl TMacro for MinecraftInstance {
Ok(())
}

async fn get_macro_config(&self, name: &str) -> Result<IndexMap<String, SettingManifest>, Error> {
async fn get_macro_config(
&self,
name: &str,
) -> Result<IndexMap<String, SettingManifest>, Error> {
let path_to_macro = resolve_macro_invocation(&self.path_to_macros, name)
.ok_or_else(|| eyre!("Failed to resolve macro invocation for {}", name))?;
MacroExecutor::get_config_manifest(&path_to_macro).await
Expand All @@ -203,14 +212,19 @@ impl TMacro for MinecraftInstance {
) -> Result<(), Error> {
let mut local_configs: IndexMap<String, SettingLocalCache> = IndexMap::new();
config_to_store.iter().for_each(|(var_name, config)| {
local_configs.insert(var_name.clone(), SettingLocalCache::from(config));
local_configs.insert(var_name.clone(), SettingLocalCache::from(config));
});

let config_file_path = self.path_to_macros.join(name).join(format!("{name}_config")).with_extension("json");
let config_file_path = self
.path_to_macros
.join(name)
.join(format!("{name}_config"))
.with_extension("json");
std::fs::write(
config_file_path,
serde_json::to_string_pretty(&local_configs).unwrap(),
).context("failed to create the config file")?;
)
.context("failed to create the config file")?;

Ok(())
}
Expand All @@ -224,7 +238,9 @@ impl TMacro for MinecraftInstance {
.ok_or_else(|| eyre!("Failed to resolve macro invocation for {}", name))?;

let is_config_needed = match config_to_validate {
None => std::fs::read_to_string(path_to_macro).context("failed to read macro file")?.contains("LodestoneConfig"),
None => std::fs::read_to_string(path_to_macro)
.context("failed to read macro file")?
.contains("LodestoneConfig"),
Some(_) => true,
};

Expand All @@ -233,23 +249,31 @@ impl TMacro for MinecraftInstance {
return Ok(IndexMap::new());
}

let config_file_path = self.path_to_macros.join(name).join(format!("{name}_config")).with_extension("json");
let config_file_path = self
.path_to_macros
.join(name)
.join(format!("{name}_config"))
.with_extension("json");
match std::fs::read_to_string(config_file_path) {
Ok(config_string) => {
let local_configs: IndexMap<String, SettingLocalCache> = serde_json::from_str(&config_string)
.context("failed to parse local config cache")?;
let local_configs: IndexMap<String, SettingLocalCache> =
serde_json::from_str(&config_string)
.context("failed to parse local config cache")?;

let configs = match config_to_validate {
Some(config) => config.clone(),
None => self.get_macro_config(name).await?,
};

let validation_result = local_configs.iter().fold(local_configs.len() == configs.len(), |partial_result, (setting_id, local_cache)| {
if !partial_result {
return false;
}
local_cache.validate_type(configs.get(setting_id))
});
let validation_result = local_configs.iter().fold(
local_configs.len() == configs.len(),
|partial_result, (setting_id, local_cache)| {
if !partial_result {
return false;
}
local_cache.validate_type(configs.get(setting_id))
},
);

if !validation_result {
return Err(Error {
Expand All @@ -259,7 +283,7 @@ impl TMacro for MinecraftInstance {
}

Ok(local_configs)
},
}
Err(_) => Err(Error {
kind: ErrorKind::NotFound,
source: eyre!("Local config cache is not found"),
Expand Down
Loading

0 comments on commit 93708c9

Please sign in to comment.