Skip to content

Commit

Permalink
fiew an Error event on error
Browse files Browse the repository at this point in the history
  • Loading branch information
www committed Nov 28, 2024
1 parent f06f61c commit a4e80b2
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 43 deletions.
79 changes: 70 additions & 9 deletions core/rust.bot_modules.core/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
.collect::<Vec<String>>()
.join(" ");

dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -67,7 +67,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
}

AntiraidEvent::Custom(ref event) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new(
Expand All @@ -83,7 +83,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
.await
}
AntiraidEvent::StingCreate(ref sting) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -101,7 +101,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
Ok(())
}
AntiraidEvent::StingExpire(ref sting) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -119,7 +119,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
Ok(())
}
AntiraidEvent::StingDelete(ref sting) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -137,7 +137,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
Ok(())
}
AntiraidEvent::PunishmentCreate(ref punishment) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -155,7 +155,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
Ok(())
}
AntiraidEvent::PunishmentExpire(ref punishment) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new_arc(
Expand All @@ -173,7 +173,7 @@ pub(crate) async fn event_listener(ectx: &EventHandlerContext) -> Result<(), sil
Ok(())
}
AntiraidEvent::OnStartup(ref modified) => {
dispatch_audit_log(
dispatch(
ctx,
&ectx.data,
templating::event::CreateEventArc::new(
Expand Down Expand Up @@ -222,7 +222,68 @@ pub(crate) async fn should_dispatch_event(
Ok(filters.contains(&event_name.to_string()))
}

async fn dispatch_audit_log(
async fn dispatch(
ctx: &serenity::all::client::Context,
data: &silverpelt::data::Data,
event: templating::event::CreateEventArc,
guild_id: serenity::model::id::GuildId,
) -> Result<(), silverpelt::Error> {
let templates = templating::cache::get_all_guild_templates(guild_id, &data.pool).await?;

if templates.is_empty() {
return Ok(());
}

for template in templates.iter() {
// Verify event dispatch
if !should_dispatch_event(&event.name, {
// False positive, unwrap_or_default cannot be used here as it moves the event out of the sink
#[allow(clippy::manual_unwrap_or_default)]
if let Some(ref events) = template.events {
events
} else {
&[]
}
})
.await?
{
continue;
}

match templating::execute::<Option<()>>(
guild_id,
templating::Template::Named(template.name.clone()),
data.pool.clone(),
ctx.clone(),
data.reqwest.clone(),
event.into_event(),
)
.await
{
Ok(_) => {}
Err(e) => {
dispatch_error(
ctx,
data,
templating::event::CreateEventArc::new(
"Error".to_string(),
"Error".to_string(),
"Error".to_string(),
e.to_string().into(),
false,
None,
),
guild_id,
)
.await?;
}
}
}

Ok(())
}

async fn dispatch_error(
ctx: &serenity::all::client::Context,
data: &silverpelt::data::Data,
event: templating::event::CreateEventArc,
Expand Down
18 changes: 0 additions & 18 deletions core/rust.templating/src/lang_lua/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,6 @@ pub struct Event {
uid: sqlx::types::Uuid,
/// The author, if any, of the event
author: Option<String>,

#[serde(skip)]
#[serde(default = "std::sync::Mutex::default")]
/// The cached serialized value of the data
cached_data: std::sync::Mutex<Option<LuaValue>>,
}

impl Event {
Expand Down Expand Up @@ -169,7 +164,6 @@ impl Event {
data,
is_deniable,
uid: sqlx::types::Uuid::new_v4(),
cached_data: std::sync::Mutex::new(None),
author,
}
}
Expand Down Expand Up @@ -202,20 +196,8 @@ impl LuaUserData for Event {
Ok(name)
});
fields.add_field_method_get("data", |lua, this| {
let mut cached_data = this
.cached_data
.lock()
.map_err(|e| LuaError::external(e.to_string()))?;

if let Some(v) = cached_data.as_ref() {
return Ok(v.clone());
}

log::info!("Event: Serializing data");
let v = lua.to_value(&*this.data)?;

*cached_data = Some(v.clone());

Ok(v)
});
fields.add_field_method_get("is_deniable", |_, this| Ok(this.is_deniable));
Expand Down
8 changes: 4 additions & 4 deletions core/rust.templating/src/lang_lua/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub async fn handle_event(action: LuaVmAction, tis_ref: &ArLuaThreadInnerState)
{
Ok(bytecode) => bytecode,
Err(e) => {
return LuaVmResult::LuaError { err: e };
return LuaVmResult::LuaError { err: e.to_string() };
}
};

Expand Down Expand Up @@ -65,7 +65,7 @@ pub async fn handle_event(action: LuaVmAction, tis_ref: &ArLuaThreadInnerState)
_ => {}
}

return LuaVmResult::LuaError { err: e };
return LuaVmResult::LuaError { err: e.to_string() };
}
};

Expand All @@ -74,7 +74,7 @@ pub async fn handle_event(action: LuaVmAction, tis_ref: &ArLuaThreadInnerState)
return LuaVmResult::Ok { result_val: v };
}
Err(e) => {
return LuaVmResult::LuaError { err: e };
return LuaVmResult::LuaError { err: e.to_string() };
}
}
}
Expand All @@ -101,7 +101,7 @@ pub async fn handle_event(action: LuaVmAction, tis_ref: &ArLuaThreadInnerState)
};
}
Err(e) => {
return LuaVmResult::LuaError { err: e };
return LuaVmResult::LuaError { err: e.to_string() };
}
};
}
Expand Down
16 changes: 8 additions & 8 deletions core/rust.templating/src/lang_lua/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub enum LuaVmAction {

pub enum LuaVmResult {
Ok { result_val: serde_json::Value },
LuaError { err: LuaError },
LuaError { err: String },
VmBroken {},
}

Expand Down Expand Up @@ -331,7 +331,7 @@ local args, token = ...
pub async fn render_template<Response: serde::de::DeserializeOwned>(
event: event::Event,
state: ParseCompileState,
) -> LuaResult<Response> {
) -> Result<Response, silverpelt::Error> {
let state = ParseCompileState {
template_content: unravel_function_expression(state.template_content),
..state
Expand Down Expand Up @@ -367,30 +367,30 @@ pub async fn render_template<Response: serde::de::DeserializeOwned>(

tokio::select! {
_ = tokio::time::sleep(MAX_TEMPLATES_EXECUTION_TIME) => {
Err(LuaError::external("Template took too long to compile"))
Err("Template took too long to compile".into())
}
value = rx => {
let Ok(value) = value else {
return Err(LuaError::external("Could not receive data from Lua thread"));
return Err("Could not receive data from Lua thread".into());
};
match value {
LuaVmResult::Ok { result_val: value }=> {
// Check for __error
if let serde_json::Value::Object(ref map) = value {
if let Some(value) = map.get("__error") {
return Err(LuaError::external(value.to_string()));
return Err(value.to_string().into());
}
}

let v: Response = serde_json::from_value(value)
.map_err(|e| LuaError::external(e.to_string()))?;
.map_err(|e| e.to_string())?;

Ok(v)
}
LuaVmResult::LuaError { err } => Err(err),
LuaVmResult::LuaError { err } => Err(err.into()),
LuaVmResult::VmBroken {} => {
// Rerun render_template
return Err(LuaError::external("Lua VM is broken"));
return Err("Lua VM is broken".into());
},
}
}
Expand Down
7 changes: 4 additions & 3 deletions core/rust.templating/src/lang_lua/thread_proc/impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ pub fn lua_thread_impl(
.build()
.unwrap();

let tis_ref = thread_inner_state.clone();
let local = tokio::task::LocalSet::new();

rt.block_on(async {
let tis_ref = thread_inner_state.clone();
local.block_on(&rt, async {
// Catch panics
fn panic_catcher(
guild_id: GuildId,
Expand All @@ -46,7 +47,7 @@ pub fn lua_thread_impl(

while let Some((action, callback)) = rx.recv().await {
let tis_ref = tis_ref.clone();
rt.spawn(async move {
local.spawn_local(async move {
let result = handle_event(action, &tis_ref).await;

let _ = callback.send(result);
Expand Down
2 changes: 1 addition & 1 deletion services/website

0 comments on commit a4e80b2

Please sign in to comment.