mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-16 06:38:03 +08:00
Wire up async runtimes
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
@@ -8,8 +9,31 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use std::error::Error;
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::Duration;
|
||||
|
||||
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
async fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
loop {
|
||||
while completion.try_recv().is_ok() {}
|
||||
match executor.execute(render_config.clone()).await? {
|
||||
GPoll::Final(value) => return Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
log::error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
return Ok(value);
|
||||
}
|
||||
GPoll::Partial(_) | GPoll::Pending => {
|
||||
completion
|
||||
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
|
||||
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
|
||||
}
|
||||
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
@@ -36,6 +60,7 @@ pub async fn export_document(
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
transparent: bool,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Determine export format based on file type
|
||||
let export_format = match file_type {
|
||||
@@ -57,10 +82,7 @@ pub async fn export_document(
|
||||
}
|
||||
|
||||
// Execute the graph
|
||||
let (result, evaluation_error) = executor.execute(render_config).await?;
|
||||
if let Some(error) = evaluation_error {
|
||||
log::error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
}
|
||||
let result = execute_until_final(executor, render_config, completion).await?;
|
||||
|
||||
// Handle the result based on output type
|
||||
match result {
|
||||
@@ -159,6 +181,7 @@ pub async fn export_gif(
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
animation: AnimationParams,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
use image::codecs::gif::{GifEncoder, Repeat};
|
||||
use image::{Frame, RgbaImage};
|
||||
@@ -198,10 +221,7 @@ pub async fn export_gif(
|
||||
}
|
||||
|
||||
// Execute the graph for this frame
|
||||
let (result, evaluation_error) = executor.execute(render_config).await?;
|
||||
if let Some(error) = evaluation_error {
|
||||
log::error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
}
|
||||
let result = execute_until_final(executor, render_config, completion).await?;
|
||||
|
||||
// Extract RGBA data from result
|
||||
let (data, img_width, img_height) = match result {
|
||||
|
||||
@@ -14,7 +14,7 @@ use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner, RuntimeHandle};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::error::Error;
|
||||
@@ -29,6 +29,29 @@ impl NodeGraphUpdateSender for UpdateLogger {
|
||||
}
|
||||
}
|
||||
|
||||
struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
impl TokioSpawner {
|
||||
fn new() -> Self {
|
||||
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
|
||||
}
|
||||
}
|
||||
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
self.0.as_ref().expect("runtime lives until drop").spawn(task);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
|
||||
impl Drop for TokioSpawner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.0.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[clap(name = "graphene-cli", version)]
|
||||
pub struct App {
|
||||
@@ -183,7 +206,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let preferences = EditorPreferences {
|
||||
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
||||
};
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>));
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()) as Box<DynSpawner>));
|
||||
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
|
||||
graph_runtime.set_notifier(Arc::new(move || {
|
||||
let _ = completion_sender.send(());
|
||||
}));
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io_for_api),
|
||||
node_graph_message_sender: Box::new(UpdateLogger {}),
|
||||
@@ -230,9 +257,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Perform export based on file type
|
||||
if file_type == export::FileType::Gif {
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation).await?;
|
||||
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver).await?;
|
||||
} else {
|
||||
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent).await?;
|
||||
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver).await?;
|
||||
}
|
||||
}
|
||||
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
||||
|
||||
@@ -170,11 +170,11 @@ impl DynamicExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Executor<I, (TaggedValue, Option<core_types::gpoll::GraphError>)> for &DynamicExecutor
|
||||
impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
|
||||
where
|
||||
I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
|
||||
{
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<(TaggedValue, Option<core_types::gpoll::GraphError>), Box<dyn Error>>> {
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<GPoll<TaggedValue>, Box<dyn Error>>> {
|
||||
Box::pin(async move {
|
||||
let Some(handle) = self.tree.get(self.output) else {
|
||||
return Err("Output node not found in executor".into());
|
||||
@@ -185,13 +185,14 @@ where
|
||||
Err(error) => GPoll::Final(Err(error)),
|
||||
});
|
||||
match result {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => Ok((value?, None)),
|
||||
GPoll::Final(value) => Ok(GPoll::Final(value?)),
|
||||
GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
Ok((value?, Some(error)))
|
||||
Ok(GPoll::Fallback(Box::new((value?, error))))
|
||||
}
|
||||
GPoll::Pending => Err("Node graph evaluation is pending".into()),
|
||||
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}").into()),
|
||||
GPoll::Pending => Ok(GPoll::Pending),
|
||||
GPoll::Error(error) => Ok(GPoll::Error(error)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -48,6 +48,11 @@ pub type DynSpawner = dyn Spawner + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynSpawner = dyn Spawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynNotifier = dyn Fn() + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynNotifier = dyn Fn();
|
||||
|
||||
impl<S: Spawner + ?Sized> Spawner for Box<S> {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
(**self).spawn(task)
|
||||
@@ -74,6 +79,7 @@ impl Default for RuntimeHandle {
|
||||
pub struct GraphRuntime<S> {
|
||||
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
|
||||
dirty: Arc<AtomicBool>,
|
||||
notifier: Arc<Mutex<Arc<DynNotifier>>>,
|
||||
spawner: S,
|
||||
}
|
||||
|
||||
@@ -89,10 +95,15 @@ impl<S> GraphRuntime<S> {
|
||||
Self {
|
||||
generations: Arc::default(),
|
||||
dirty: Arc::default(),
|
||||
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
|
||||
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
|
||||
}
|
||||
|
||||
pub fn retain_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
@@ -121,12 +132,16 @@ impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
let generations = Arc::clone(&self.generations);
|
||||
let dirty = Arc::clone(&self.dirty);
|
||||
let notifier = Arc::clone(&self.notifier);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
future.await;
|
||||
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(generation) = generations.get_mut(&source) {
|
||||
*generation += 1;
|
||||
dirty.store(true, Ordering::Release);
|
||||
drop(generations);
|
||||
let notifier = Arc::clone(¬ifier.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
notifier();
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -405,6 +420,36 @@ mod tests {
|
||||
assert!(!runtime.take_dirty(), "take_dirty drains the flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_notifies_after_setting_dirty() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
let observed_dirty = Arc::new(AtomicBool::new(false));
|
||||
let dirty_at_notify = Arc::clone(&runtime.dirty);
|
||||
let observed = Arc::clone(&observed_dirty);
|
||||
runtime.set_notifier(Arc::new(move || {
|
||||
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
|
||||
}));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_of_a_removed_source_does_not_notify() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
let notified = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(¬ified);
|
||||
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
runtime.retain_sources(&[]);
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(!notified.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_of_a_removed_source_is_inert() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
|
||||
Reference in New Issue
Block a user