子进程切换到 rust win32job 实现

This commit is contained in:
2024-02-25 10:30:20 +08:00
parent 238e255489
commit 3c0c80abd2
12 changed files with 232 additions and 39 deletions

View File

@ -12,7 +12,7 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
flutter_rust_bridge = "=2.0.0-dev.24"
tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros"] }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros","process"] }
url = "2.5.0"
uuid = { version = "1.7.0", features = ["v4", "fast-rng", "macro-diagnostics"] }
async-std = "1.12.0"
@ -21,3 +21,4 @@ once_cell = "1.19.0"
reqwest = { version = "0.11", features = ["rustls-tls-native-roots", "cookies", "gzip", "json","stream"] }
hickory-resolver = {version = "0.24.0"}
anyhow = "1.0"
win32job = "2"

View File

@ -3,7 +3,6 @@ use hyper::Method;
use crate::http_package;
use crate::http_package::RustHttpResponse;
pub enum MyMethod {
Options,
Gets,

View File

@ -2,3 +2,5 @@
// Do not put code in `mod.rs`, but put in e.g. `simple.rs`.
//
pub mod http_api;
pub mod process_api;

View File

@ -0,0 +1,79 @@
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, BufReader};
use crate::frb_generated::StreamSink;
pub async fn start_process(
executable: String,
arguments: Vec<String>,
working_directory: String,
stream_sink: StreamSink<String>,
) {
let stream_sink_arc = Arc::from(stream_sink);
let mut command = tokio::process::Command::new(&executable);
command
.args(arguments)
.current_dir(working_directory)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
command.creation_flags(0x08000000);
let job = win32job::Job::create().unwrap();
let mut info = job.query_extended_limit_info().unwrap();
info.limit_kill_on_job_close();
job.set_extended_limit_info(&mut info).unwrap();
job.assign_current_process().unwrap();
if let Ok(mut child) = command.spawn() {
let stdout = child.stdout.take().expect("Failed to open stdout");
let stderr = child.stderr.take().expect("Failed to open stderr");
let output_task = tokio::spawn(process_output(stdout, stream_sink_arc.clone()));
let error_task = tokio::spawn(process_error(stderr, stream_sink_arc.clone()));
tokio::select! {
_ = output_task => (),
_ = error_task => (),
}
let exit_status = child.wait().await.expect("Failed to wait for child process");
if !exit_status.success() {
eprintln!("Child process exited with an error: {:?}", exit_status);
stream_sink_arc.add("exit:".to_string()).unwrap();
}
} else {
eprintln!("Failed to start {}", executable);
stream_sink_arc.add("error:Failed to start".to_string()).unwrap();
}
}
async fn process_output<R>(stdout: R, stream_sink: Arc<StreamSink<String>>)
where
R: tokio::io::AsyncRead + Unpin,
{
let reader = BufReader::new(stdout);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await.unwrap() {
if line.trim().is_empty() {
continue;
}
println!("{}", line.trim());
stream_sink.add("output:".to_string() + &*line.trim().to_string()).unwrap();
}
}
async fn process_error<R>(stderr: R, stream_sink: Arc<StreamSink<String>>)
where
R: tokio::io::AsyncRead + Unpin,
{
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await.unwrap() {
println!("{}", line.trim());
stream_sink.add("error:".to_string() + &*line.trim().to_string()).unwrap();
}
}

View File

@ -150,6 +150,53 @@ fn wire_set_default_header_impl(
},
)
}
fn wire_start_process_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "start_process",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Stream,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_executable = <String>::sse_decode(&mut deserializer);
let api_arguments = <Vec<String>>::sse_decode(&mut deserializer);
let api_working_directory = <String>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse(
(move || async move {
Result::<_, ()>::Ok(
crate::api::process_api::start_process(
api_executable,
api_arguments,
api_working_directory,
StreamSink::new(
context.rust2dart_context().stream_sink::<_, String>(),
),
)
.await,
)
})()
.await,
)
}
},
)
}
// Section: related_funcs
@ -382,6 +429,7 @@ fn pde_ffi_dispatcher_primary_impl(
3 => wire_dns_lookup_txt_impl(port, ptr, rust_vec_len, data_len),
2 => wire_fetch_impl(port, ptr, rust_vec_len, data_len),
1 => wire_set_default_header_impl(port, ptr, rust_vec_len, data_len),
4 => wire_start_process_impl(port, ptr, rust_vec_len, data_len),
_ => unreachable!(),
}
}

View File

@ -1,3 +1,3 @@
mod frb_generated;
mod api;
mod http_package;
pub mod api;
pub mod http_package;