Extend subtask stdlib for file, function, and foreign concurrency.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
63e5be80ab
commit
3da7b276d3
11 files changed
+574
-78
No files matched your search
@@ -2,23 +2,24 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | v1 已落地 |
|
||||
| 状态 | v2 |
|
||||
| 库 | `lib/subtask.mq.md` · `lib/子任务.mq.md` |
|
||||
|
||||
## 定位
|
||||
|
||||
OS 进程式并发:`spawn` 另起 `marqdo run <path>` 子进程;**父进程结束(含 panic)时 KillOnDrop 终止所有未 join 的子进程**。
|
||||
**并发**执行单元。`spawn` 四选一:
|
||||
|
||||
v1 不共享 Marqdo 堆;子任务通过 stdout / 文件 / 环境通信。
|
||||
| 参数 | 执行方式 | `join` 返回值 |
|
||||
|------|----------|---------------|
|
||||
| `path=` | `marqdo run <file>` 子进程 | 退出码 `Int` |
|
||||
| `fn=` + 可选 `args=` | 当前入口模块中的函数(进程内线程) | 函数返回值 `Value` |
|
||||
| `code=` | 外联代码块(`Value::Code`)子进程 | stdout `Text` |
|
||||
| `lang=` + `source=` | 外联源码子进程 | stdout `Text` |
|
||||
|
||||
## API
|
||||
`args=`:文件子任务为 `List`(命令行参数);函数子任务为 `Map`(形参绑定)或 `List`(按 `arg0`… 命名)。
|
||||
|
||||
| EN | ZH | 说明 |
|
||||
|----|-----|------|
|
||||
| `spawn` | `启动` | `path=`(`.mq.md`) |
|
||||
| `poll` | `探测` | `id=` → status map |
|
||||
| `wait` | `等待` | `id=` → exit code(避免与内置 `join` 冲突) |
|
||||
| `kill` | `终止` | `id=` |
|
||||
| `wait_all` | `等待全部` | 所有子进程 exit codes |
|
||||
父进程结束(含 panic)时 **KillOnDrop** 终止所有文件/外联子进程;函数线程标记为 killed 并 detach(无法强杀 OS 线程)。
|
||||
|
||||
`poll` → `{ status: running | done | failed, … }`;函数 done 时含 `value`,进程/外联 failed 时含 `code` 或 `error`。
|
||||
|
||||
Host:`host_subtask_*`(`src/host/subtask.rs`)。
|
||||
+9
-3
@@ -1,12 +1,18 @@
|
||||
---
|
||||
title: lib/subtask
|
||||
description: OS subprocess subtasks (parent exit kills children)
|
||||
description: Concurrent subtasks — file, function, or foreign code
|
||||
---
|
||||
|
||||
## spawn
|
||||
+ `path`
|
||||
+ `path`=None
|
||||
+ `fn`=None
|
||||
+ `args`=None
|
||||
+ `code`=None
|
||||
+ `lang`=None
|
||||
+ `source`=None
|
||||
+ `stdin`=None
|
||||
|
||||
**> host_subtask_spawn path=`path`**
|
||||
**> host_subtask_spawn path=`path` fn=`fn` args=`args` code=`code` lang=`lang` source=`source` stdin=`stdin`**
|
||||
|
||||
## poll
|
||||
+ `id`
|
||||
|
||||
+9
-3
@@ -1,12 +1,18 @@
|
||||
---
|
||||
title: lib/子任务
|
||||
description: OS 子进程子任务(父进程结束则子进程结束)
|
||||
description: 并发子任务 — 文件、函数或外联代码
|
||||
---
|
||||
|
||||
## 启动
|
||||
+ `路径`
|
||||
+ `路径`=None
|
||||
+ `函数`=None
|
||||
+ `参数`=None
|
||||
+ `代码`=None
|
||||
+ `语言`=None
|
||||
+ `源码`=None
|
||||
+ `输入`=None
|
||||
|
||||
**> host_subtask_spawn path=`路径`**
|
||||
**> host_subtask_spawn path=`路径` fn=`函数` args=`参数` code=`代码` lang=`语言` source=`源码` stdin=`输入`**
|
||||
|
||||
## 探测
|
||||
+ `id`
|
||||
|
||||
@@ -456,7 +456,7 @@ impl HostFn {
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
Self::SubtaskSpawn => &["path"],
|
||||
Self::SubtaskSpawn => &[],
|
||||
Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"],
|
||||
Self::SubtaskWaitAll => &[],
|
||||
}
|
||||
@@ -477,7 +477,7 @@ impl HostFn {
|
||||
Self::ForeignSetCmd => &["args"],
|
||||
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
|
||||
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => &["at_end"],
|
||||
Self::SubtaskSpawn => &["args"],
|
||||
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -684,11 +684,7 @@ pub fn call_host(
|
||||
HostFn::WritebackGet => writeback::get(ctx, bound.get("at_end")),
|
||||
HostFn::WritebackClear => writeback::clear(ctx, bound.get("at_end")),
|
||||
HostFn::WritebackList => writeback::list(ctx),
|
||||
HostFn::SubtaskSpawn => subtask::spawn(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
bound.get("args"),
|
||||
),
|
||||
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
|
||||
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
|
||||
|
||||
+72
-14
@@ -11,7 +11,7 @@ use crate::host::HostContext;
|
||||
use crate::value::{CodeBlock, Value};
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT: usize = 1_048_576;
|
||||
pub(crate) const MAX_OUTPUT: usize = 1_048_576;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, what: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
@@ -195,13 +195,37 @@ fn write_temp_script(lang: &str, source: &str) -> Result<PathBuf, String> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn run_argv(
|
||||
/// Background foreign subprocess (for `lib/subtask`); caller removes `script_path` after join.
|
||||
pub struct SpawnedForeign {
|
||||
pub child: std::process::Child,
|
||||
pub script_path: PathBuf,
|
||||
pub stdout: thread::JoinHandle<String>,
|
||||
pub stderr: thread::JoinHandle<String>,
|
||||
}
|
||||
|
||||
pub fn spawn_source(
|
||||
ctx: &HostContext,
|
||||
lang: &str,
|
||||
source: &str,
|
||||
stdin: Option<&str>,
|
||||
) -> Result<SpawnedForeign, String> {
|
||||
let lang_key = lang.to_ascii_lowercase();
|
||||
let argv = resolve_argv(ctx, &lang_key)?;
|
||||
let script_path = write_temp_script(&lang_key, source)?;
|
||||
match spawn_argv(ctx, &argv, &script_path, stdin, &lang_key) {
|
||||
Ok(spawned) => Ok(spawned),
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&script_path);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_foreign_command(
|
||||
ctx: &HostContext,
|
||||
argv: &[String],
|
||||
script: &Path,
|
||||
stdin: Option<&str>,
|
||||
lang: &str,
|
||||
) -> Result<Value, String> {
|
||||
) -> Result<Command, String> {
|
||||
if argv.is_empty() {
|
||||
return Err("foreign cmd argv is empty — check set_cmd / env".into());
|
||||
}
|
||||
@@ -216,14 +240,25 @@ fn run_argv(
|
||||
command.stderr(Stdio::piped());
|
||||
command.env("PYTHONIOENCODING", "utf-8");
|
||||
command.env("PYTHONUTF8", "1");
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
let mut child = command.spawn().map_err(|e| {
|
||||
format!(
|
||||
"foreign run failed (lang={lang}, cmd={}): {e} — check your interpreter / \
|
||||
MARQDO_FOREIGN_* / set_cmd",
|
||||
argv.join(" ")
|
||||
)
|
||||
})?;
|
||||
fn spawn_argv(
|
||||
ctx: &HostContext,
|
||||
argv: &[String],
|
||||
script: &Path,
|
||||
stdin: Option<&str>,
|
||||
lang: &str,
|
||||
) -> Result<SpawnedForeign, String> {
|
||||
let mut child = build_foreign_command(ctx, argv, script)?
|
||||
.spawn()
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"foreign spawn failed (lang={lang}, cmd={}): {e} — check your interpreter / \
|
||||
MARQDO_FOREIGN_* / set_cmd",
|
||||
argv.join(" ")
|
||||
)
|
||||
})?;
|
||||
|
||||
if let Some(data) = stdin {
|
||||
if let Some(mut pipe) = child.stdin.take() {
|
||||
@@ -235,14 +270,14 @@ fn run_argv(
|
||||
|
||||
let mut stdout_pipe = child.stdout.take();
|
||||
let mut stderr_pipe = child.stderr.take();
|
||||
let t_out = thread::spawn(move || {
|
||||
let stdout = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stdout_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
});
|
||||
let t_err = thread::spawn(move || {
|
||||
let stderr = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stderr_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
@@ -250,6 +285,29 @@ fn run_argv(
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
});
|
||||
|
||||
Ok(SpawnedForeign {
|
||||
child,
|
||||
script_path: script.to_path_buf(),
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_argv(
|
||||
ctx: &HostContext,
|
||||
argv: &[String],
|
||||
script: &Path,
|
||||
stdin: Option<&str>,
|
||||
lang: &str,
|
||||
) -> Result<Value, String> {
|
||||
let spawned = spawn_argv(ctx, argv, script, stdin, lang)?;
|
||||
let SpawnedForeign {
|
||||
mut child,
|
||||
stdout: t_out,
|
||||
stderr: t_err,
|
||||
..
|
||||
} = spawned;
|
||||
|
||||
let start = Instant::now();
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
|
||||
+2
-3
@@ -23,7 +23,6 @@ pub use plugin::PluginState;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Child;
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
@@ -83,8 +82,8 @@ pub struct HostContext {
|
||||
pub current_line: u32,
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// OS subprocess subtasks (`lib/subtask`).
|
||||
pub subtasks: HashMap<u64, Child>,
|
||||
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
|
||||
pub subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub subtask_seq: u64,
|
||||
}
|
||||
|
||||
|
||||
+390
-37
@@ -1,9 +1,53 @@
|
||||
//! OS subprocess subtasks (`marqdo run` children); parent exit kills all children.
|
||||
//! Concurrent subtasks: OS file children, in-process functions, foreign subprocesses.
|
||||
//! Parent `HostContext` drop kills/waits file & foreign children; function threads detach.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use crate::host::foreign;
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
use crate::interp::Interpreter;
|
||||
use crate::load::load_module;
|
||||
use crate::value::{CodeBlock, Value};
|
||||
|
||||
/// Stored subtask handle (tagged by spawn kind).
|
||||
pub(crate) enum Handle {
|
||||
File(Child),
|
||||
Foreign(ForeignTask),
|
||||
Function(FunctionTask),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Handle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Handle::File(_) => f.write_str("Subtask::File"),
|
||||
Handle::Foreign(_) => f.write_str("Subtask::Foreign"),
|
||||
Handle::Function(_) => f.write_str("Subtask::Function"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ForeignTask {
|
||||
child: Child,
|
||||
temp_script: PathBuf,
|
||||
stdout: JoinHandle<String>,
|
||||
stderr: JoinHandle<String>,
|
||||
}
|
||||
|
||||
enum FnState {
|
||||
Running,
|
||||
Done(Value),
|
||||
Failed(String),
|
||||
Killed,
|
||||
}
|
||||
|
||||
struct FunctionTask {
|
||||
state: Arc<Mutex<FnState>>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
@@ -12,21 +56,129 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn child_id(_ctx: &HostContext, id: &Value) -> Result<u64, String> {
|
||||
fn as_code(v: &Value) -> Result<&CodeBlock, String> {
|
||||
match v {
|
||||
Value::Code(c) => Ok(c),
|
||||
_ => Err("code must be a bound ```lang fence value".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_text(v: Option<&Value>) -> Result<Option<&str>, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(None),
|
||||
Some(v) => Ok(Some(as_text(v, "value")?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_set(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None => false,
|
||||
Some(Value::None) => false,
|
||||
Some(Value::Text(s)) if s.is_empty() => false,
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn child_id(id: &Value) -> Result<u64, String> {
|
||||
match id {
|
||||
Value::Int(n) if *n > 0 => Ok(*n as u64),
|
||||
_ => Err("subtask id must be positive int".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill_all(ctx: &mut HostContext) {
|
||||
for (_, mut child) in ctx.subtasks.drain() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
fn next_id(ctx: &mut HostContext) -> u64 {
|
||||
ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1);
|
||||
ctx.subtask_seq
|
||||
}
|
||||
|
||||
fn status_map(status: &str, extra: Vec<(String, Value)>) -> Value {
|
||||
let mut pairs = vec![("status".into(), Value::Text(status.into()))];
|
||||
pairs.extend(extra);
|
||||
Value::Map(pairs)
|
||||
}
|
||||
|
||||
fn fn_args_from_value(args: Option<&Value>) -> Result<Vec<(String, Value)>, String> {
|
||||
let Some(args) = args else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
match args {
|
||||
Value::None => Ok(Vec::new()),
|
||||
Value::Map(pairs) => Ok(pairs.clone()),
|
||||
Value::List(items) => {
|
||||
let mut out = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
out.push((format!("arg{i}"), item.clone()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
other => Err(format!(
|
||||
"fn args must be map or list, got {}",
|
||||
other.as_display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(
|
||||
pub fn kill_all(ctx: &mut HostContext) {
|
||||
for (_, handle) in ctx.subtasks.drain() {
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
let _ = task.child.kill();
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
let _ = task.stdout.join();
|
||||
let _ = task.stderr.join();
|
||||
}
|
||||
Handle::Function(mut task) => {
|
||||
if let Ok(mut st) = task.state.lock() {
|
||||
if matches!(*st, FnState::Running) {
|
||||
*st = FnState::Killed;
|
||||
}
|
||||
}
|
||||
drop(task.handle.take());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(ctx: &mut HostContext, bound: &HashMap<String, Value>) -> Result<Value, String> {
|
||||
let has_path = is_set(bound.get("path"));
|
||||
let has_fn = is_set(bound.get("fn"));
|
||||
let has_code = is_set(bound.get("code"));
|
||||
let has_lang = is_set(bound.get("lang")) && is_set(bound.get("source"));
|
||||
let kinds = [has_path, has_fn, has_code, has_lang]
|
||||
.into_iter()
|
||||
.filter(|b| *b)
|
||||
.count();
|
||||
if kinds != 1 {
|
||||
return Err(
|
||||
"spawn: specify exactly one of path=, fn=, code=, or lang=+source=".into(),
|
||||
);
|
||||
}
|
||||
if has_path {
|
||||
spawn_file(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
bound.get("args"),
|
||||
)
|
||||
} else if has_fn {
|
||||
spawn_fn(ctx, require(bound, "fn")?, bound.get("args"))
|
||||
} else if has_code {
|
||||
spawn_code(ctx, require(bound, "code")?, bound.get("stdin"))
|
||||
} else {
|
||||
spawn_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_file(
|
||||
ctx: &mut HostContext,
|
||||
path: &Value,
|
||||
args: Option<&Value>,
|
||||
@@ -53,64 +205,265 @@ pub fn spawn(
|
||||
let child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
|
||||
ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1);
|
||||
let id = ctx.subtask_seq;
|
||||
ctx.subtasks.insert(id, child);
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(id, Handle::File(child));
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
fn spawn_fn(
|
||||
ctx: &mut HostContext,
|
||||
name: &Value,
|
||||
args: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let name = as_text(name, "fn")?.to_string();
|
||||
let call_args = fn_args_from_value(args)?;
|
||||
let module_path = ctx
|
||||
.entry_path
|
||||
.clone()
|
||||
.ok_or_else(|| "subtask fn: no entry module (run a .mq.md file first)".to_string())?;
|
||||
let cwd = ctx.cwd.clone();
|
||||
let caps = ctx.caps.clone();
|
||||
let foreign_cmds = ctx.foreign_cmds.clone();
|
||||
let fs_root = ctx.fs_root.clone();
|
||||
let argv = ctx.argv.clone();
|
||||
|
||||
let state = Arc::new(Mutex::new(FnState::Running));
|
||||
let state_bg = Arc::clone(&state);
|
||||
let handle = thread::spawn(move || {
|
||||
let result = (|| -> Result<Value, String> {
|
||||
let module = load_module(&module_path).map_err(|e| e.to_string())?;
|
||||
let source = std::fs::read_to_string(&module_path)
|
||||
.map_err(|e| format!("subtask fn: read {}: {e}", module_path.display()))?;
|
||||
let mut host = HostContext::for_capture(Some(&module_path), caps);
|
||||
host.cwd = cwd;
|
||||
host.fs_root = fs_root;
|
||||
host.argv = argv;
|
||||
host.foreign_cmds = foreign_cmds;
|
||||
host.set_entry_source(Some(&module_path), &source);
|
||||
let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host);
|
||||
interp
|
||||
.invoke_function(&module, &name, &call_args)
|
||||
.map_err(|e| e.to_string())
|
||||
})();
|
||||
if let Ok(mut st) = state_bg.lock() {
|
||||
if !matches!(*st, FnState::Killed) {
|
||||
*st = match result {
|
||||
Ok(v) => FnState::Done(v),
|
||||
Err(e) => FnState::Failed(e),
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::Function(FunctionTask {
|
||||
state,
|
||||
handle: Some(handle),
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
fn spawn_code(
|
||||
ctx: &mut HostContext,
|
||||
code: &Value,
|
||||
stdin: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let block = as_code(code)?;
|
||||
let stdin = opt_text(stdin)?;
|
||||
spawn_foreign(ctx, &block.lang, &block.source, stdin)
|
||||
}
|
||||
|
||||
fn spawn_lang(
|
||||
ctx: &mut HostContext,
|
||||
lang: &Value,
|
||||
source: &Value,
|
||||
stdin: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let lang = as_text(lang, "lang")?;
|
||||
let source = as_text(source, "source")?;
|
||||
let stdin = opt_text(stdin)?;
|
||||
spawn_foreign(ctx, lang, source, stdin)
|
||||
}
|
||||
|
||||
fn spawn_foreign(
|
||||
ctx: &mut HostContext,
|
||||
lang: &str,
|
||||
source: &str,
|
||||
stdin: Option<&str>,
|
||||
) -> Result<Value, String> {
|
||||
let spawned = foreign::spawn_source(ctx, lang, source, stdin)?;
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::Foreign(ForeignTask {
|
||||
child: spawned.child,
|
||||
temp_script: spawned.script_path,
|
||||
stdout: spawned.stdout,
|
||||
stderr: spawned.stderr,
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let child = ctx
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(child) => poll_child(child),
|
||||
Handle::Foreign(task) => poll_child(&mut task.child),
|
||||
Handle::Function(task) => poll_function(&task.state),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_child(child: &mut Child) -> Result<Value, String> {
|
||||
match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? {
|
||||
None => Ok(Value::Map(vec![("status".into(), Value::Text("running".into()))])),
|
||||
None => Ok(status_map("running", vec![])),
|
||||
Some(status) => {
|
||||
let code = status.code().unwrap_or(-1);
|
||||
let st = if status.success() {
|
||||
"done"
|
||||
} else {
|
||||
"failed"
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Text(st.into())),
|
||||
("code".into(), Value::Int(code as i64)),
|
||||
]))
|
||||
let st = if status.success() { "done" } else { "failed" };
|
||||
Ok(status_map(
|
||||
st,
|
||||
vec![("code".into(), Value::Int(code as i64))],
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_function(state: &Arc<Mutex<FnState>>) -> Result<Value, String> {
|
||||
let st = state
|
||||
.lock()
|
||||
.map_err(|_| "subtask fn: lock poisoned".to_string())?;
|
||||
match &*st {
|
||||
FnState::Running => Ok(status_map("running", vec![])),
|
||||
FnState::Done(v) => Ok(status_map(
|
||||
"done",
|
||||
vec![("value".into(), v.clone())],
|
||||
)),
|
||||
FnState::Failed(e) => Ok(status_map(
|
||||
"failed",
|
||||
vec![("error".into(), Value::Text(e.clone()))],
|
||||
)),
|
||||
FnState::Killed => Ok(status_map("failed", vec![("error".into(), Value::Text("killed".into()))])),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let mut child = ctx
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
let status = child
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask join: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
|
||||
}
|
||||
Handle::Foreign(task) => join_foreign(task),
|
||||
Handle::Function(task) => join_function(task),
|
||||
}
|
||||
}
|
||||
|
||||
fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
|
||||
let status = task
|
||||
.child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask join: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
|
||||
.map_err(|e| format!("subtask foreign join: {e}"))?;
|
||||
let stdout = task.stdout.join().unwrap_or_default();
|
||||
let stderr = task.stderr.join().unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
if stdout.len() > foreign::MAX_OUTPUT || stderr.len() > foreign::MAX_OUTPUT {
|
||||
return Err("subtask foreign output too large".into());
|
||||
}
|
||||
if !status.success() {
|
||||
let code = status.code().unwrap_or(1);
|
||||
let mut msg = format!("subtask foreign failed (exit={code})");
|
||||
if !stderr.trim().is_empty() {
|
||||
msg.push_str(": ");
|
||||
msg.push_str(stderr.trim());
|
||||
}
|
||||
return Err(msg);
|
||||
}
|
||||
let mut out = stdout;
|
||||
if out.ends_with('\n') {
|
||||
out.pop();
|
||||
if out.ends_with('\r') {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
fn join_function(mut task: FunctionTask) -> Result<Value, String> {
|
||||
if let Some(handle) = task.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
let st = task
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| "subtask fn: lock poisoned".to_string())?;
|
||||
match &*st {
|
||||
FnState::Done(v) => Ok(v.clone()),
|
||||
FnState::Failed(e) => Err(e.clone()),
|
||||
FnState::Killed => Err("subtask fn killed".into()),
|
||||
FnState::Running => Err("subtask fn still running".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let mut child = ctx
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = child.wait();
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = child.wait();
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
task.child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
let _ = task.stdout.join();
|
||||
let _ = task.stderr.join();
|
||||
}
|
||||
Handle::Function(mut task) => {
|
||||
if let Ok(mut st) = task.state.lock() {
|
||||
if matches!(*st, FnState::Running) {
|
||||
*st = FnState::Killed;
|
||||
}
|
||||
}
|
||||
drop(task.handle.take());
|
||||
}
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
let ids: Vec<u64> = ctx.subtasks.keys().copied().collect();
|
||||
let mut codes = Vec::new();
|
||||
let mut results = Vec::new();
|
||||
for id in ids {
|
||||
let code = join(ctx, &Value::Int(id as i64))?;
|
||||
codes.push(code);
|
||||
results.push(join(ctx, &Value::Int(id as i64))?);
|
||||
}
|
||||
Ok(Value::List(codes))
|
||||
Ok(Value::List(results))
|
||||
}
|
||||
|
||||
fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value, String> {
|
||||
bound
|
||||
.get(key)
|
||||
.ok_or_else(|| format!("host call missing `{key}`"))
|
||||
}
|
||||
@@ -126,6 +126,18 @@ impl Interpreter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a function by name anywhere in the module (for `lib/subtask` workers).
|
||||
pub fn invoke_function(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
name: &str,
|
||||
args: &[(String, Value)],
|
||||
) -> Result<Value> {
|
||||
let fun = find_function_anywhere(module, name)
|
||||
.ok_or_else(|| self.err(format!("unknown function `{name}`")))?;
|
||||
self.run_function(module, fun, Env::new(), args)
|
||||
}
|
||||
|
||||
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
|
||||
if let Some(main) = find_top(module, "main") {
|
||||
return self.run_function(module, main, Env::new(), &[]);
|
||||
@@ -809,6 +821,18 @@ fn find_top<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
||||
module.functions.iter().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
fn find_function_anywhere<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
||||
for f in &module.functions {
|
||||
if f.name == name {
|
||||
return Some(f);
|
||||
}
|
||||
if let Some(child) = find_in_tree(f, name) {
|
||||
return Some(child);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn lookup_function<'a>(
|
||||
module: &'a Module,
|
||||
current: &'a Function,
|
||||
|
||||
@@ -652,6 +652,20 @@ fn lib_subtask_spawn() {
|
||||
assert_out("tests/lib/subtask-spawn.mq.md", "done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_subtask_fn() {
|
||||
assert_out("tests/lib/subtask-fn.mq.md", "42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_subtask_foreign() {
|
||||
if !python_available() {
|
||||
eprintln!("skip lib_subtask_foreign: no python on PATH");
|
||||
return;
|
||||
}
|
||||
assert_out("tests/lib/subtask-foreign.mq.md", "15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_json_quote() {
|
||||
assert_out("tests/lib/json-quote.mq.md", "\"hi\"");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: subtask spawn fn
|
||||
> lib/subtask.mq.md
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`args` = > parse text={"n":21} *
|
||||
|
||||
*`id` = > spawn fn=worker args=`args` *
|
||||
|
||||
*`v` = > wait id=`id` *
|
||||
|
||||
> print text=`v`
|
||||
|
||||
---
|
||||
|
||||
## worker
|
||||
+ `n`
|
||||
|
||||
**`n` * 2**
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: subtask foreign spawn
|
||||
> lib/subtask.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`py` =
|
||||
```python
|
||||
print(7 + 8)
|
||||
```
|
||||
|
||||
*`id` = > spawn code=`py` *
|
||||
|
||||
*`out` = > wait id=`id` *
|
||||
|
||||
> print text=`out`
|
||||
Reference in new issue
Block a user