use std::{
collections::VecDeque,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use bevy_ecs::resource::Resource;
use bevy_mod_scripting_asset::Language;
use bevy_mod_scripting_script::{Recipients, ScriptAttachment};
use bevy_mod_scripting_world::WorldGuard;
use parking_lot::{Mutex, RwLock};
use crate::{InteropError, ScriptValue};
pub type ScriptCallbackResults = Vec<(ScriptAttachment, Result<ScriptValue, InteropError>)>;
pub type ScriptCallbackRunner = dyn Fn(
WorldGuard,
&Recipients,
&str,
Vec<ScriptValue>,
) -> Result<ScriptCallbackResults, InteropError>
+ Send
+ Sync
+ 'static;
pub type ScriptCallbackErrorSink =
dyn Fn(WorldGuard, Option<&ScriptAttachment>, String, InteropError) + Send + Sync + 'static;
#[derive(Clone, Debug)]
pub struct QueuedScriptCallback {
pub recipients: Recipients,
pub label: String,
pub args: Vec<ScriptValue>,
}
#[derive(Clone, Resource, Default)]
pub struct AppScriptCallbackRunners {
runners: Arc<RwLock<Vec<(Language, Arc<ScriptCallbackRunner>)>>>,
queue: Arc<CallbackQueue>,
error_sink: Arc<RwLock<Option<Arc<ScriptCallbackErrorSink>>>>,
}
#[derive(Default)]
struct CallbackQueue {
not_empty: AtomicBool,
callbacks: Mutex<VecDeque<QueuedScriptCallback>>,
}
#[profiling::all_functions]
impl AppScriptCallbackRunners {
pub fn register(&self, language: Language, runner: Arc<ScriptCallbackRunner>) {
let mut runners = self.runners.write();
match runners.iter_mut().find(|(l, _)| *l == language) {
Some((_, existing)) => *existing = runner,
None => runners.push((language, runner)),
}
}
pub fn set_error_sink(&self, sink: Arc<ScriptCallbackErrorSink>) {
*self.error_sink.write() = Some(sink);
}
pub fn report_error(
&self,
world: WorldGuard,
attachment: Option<&ScriptAttachment>,
context: String,
error: InteropError,
) {
let sink = self.error_sink.read().clone();
match sink {
Some(sink) => sink(world, attachment, context, error),
None => match attachment {
Some(attachment) => {
bevy_log::error!("error {context} of script {attachment}: {error}")
}
None => bevy_log::error!("error {context}: {error}"),
},
}
}
pub fn run(
&self,
world: WorldGuard,
recipients: &Recipients,
label: &str,
args: Vec<ScriptValue>,
) -> Result<ScriptCallbackResults, InteropError> {
let runners = self
.runners
.read()
.iter()
.map(|(_, runner)| runner.clone())
.collect::<Vec<_>>();
let mut results = Vec::new();
for runner in runners {
results.extend(runner(world.clone(), recipients, label, args.clone())?);
}
Ok(results)
}
pub fn run_or_queue(
&self,
world: WorldGuard,
recipients: &Recipients,
label: &str,
args: Vec<ScriptValue>,
) -> Result<ScriptCallbackResults, InteropError> {
let mut results = self.run(world, recipients, label, args.clone())?;
results.retain(|(attachment, result)| match result {
Err(e) if e.is_context_busy() => {
self.queue(QueuedScriptCallback {
recipients: Recipients::from(attachment.clone()),
label: label.to_owned(),
args: args.clone(),
});
false
}
_ => true,
});
Ok(results)
}
pub fn queue(&self, callback: QueuedScriptCallback) {
let mut callbacks = self.queue.callbacks.lock();
callbacks.push_back(callback);
self.queue.not_empty.store(true, Ordering::Release);
}
pub fn has_queued(&self) -> bool {
self.queue.not_empty.load(Ordering::Acquire)
}
pub fn pop_queued(&self) -> Option<QueuedScriptCallback> {
let mut callbacks = self.queue.callbacks.lock();
let next = callbacks.pop_front();
self.queue
.not_empty
.store(!callbacks.is_empty(), Ordering::Release);
next
}
}
#[cfg(test)]
mod test {
use bevy_asset::Handle;
use bevy_ecs::world::World;
use super::*;
use crate::{CurrentScriptAttachment, WorldAccessGuard, WorldExtensions};
fn runner_answering(value: i64) -> Arc<ScriptCallbackRunner> {
Arc::new(move |_, _, _, _| {
Ok(vec![(
ScriptAttachment::StaticScript(Handle::default()),
Ok(ScriptValue::Integer(value)),
)])
})
}
fn run(runners: &AppScriptCallbackRunners) -> Vec<i64> {
let mut world = World::new();
let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
runners
.run(guard, &Recipients::AllScripts, "ping", vec![])
.unwrap()
.into_iter()
.map(|(_, result)| match result {
Ok(ScriptValue::Integer(n)) => n,
other => panic!("unexpected result: {other:?}"),
})
.collect()
}
#[test]
fn queued_callbacks_are_taken_in_order() {
let runners = AppScriptCallbackRunners::default();
assert!(!runners.has_queued());
for label in ["first", "second"] {
runners.queue(QueuedScriptCallback {
recipients: Recipients::AllScripts,
label: label.to_owned(),
args: vec![],
});
}
assert!(runners.has_queued());
assert_eq!(
runners.pop_queued().map(|c| c.label).as_deref(),
Some("first")
);
assert!(runners.has_queued());
assert_eq!(
runners.pop_queued().map(|c| c.label).as_deref(),
Some("second")
);
assert!(!runners.has_queued());
assert!(runners.pop_queued().is_none());
}
#[test]
fn runs_every_language_and_replaces_runner_of_same_language() {
let runners = AppScriptCallbackRunners::default();
runners.register(Language::Lua, runner_answering(1));
runners.register(Language::Rune, runner_answering(2));
assert_eq!(run(&runners), vec![1, 2]);
runners.register(Language::Lua, runner_answering(3));
assert_eq!(run(&runners), vec![3, 2]);
}
#[test]
fn reported_errors_go_to_the_error_sink() {
let runners = AppScriptCallbackRunners::default();
let reported = Arc::new(Mutex::new(Vec::new()));
let r = reported.clone();
runners.set_error_sink(Arc::new(move |_, attachment, context, _| {
r.lock().push((attachment.is_some(), context));
}));
let mut world = World::new();
let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
let attachment = ScriptAttachment::StaticScript(Handle::default());
runners.report_error(
guard.clone(),
Some(&attachment),
"in observer callback: a".to_owned(),
InteropError::string("boom".to_owned()),
);
runners.report_error(
guard,
None,
"in observer callback: b".to_owned(),
InteropError::string("boom".to_owned()),
);
assert_eq!(
*reported.lock(),
vec![
(true, "in observer callback: a".to_owned()),
(false, "in observer callback: b".to_owned())
]
);
}
}