Extract the Nexus runtime from Tessera
This commit is contained in:
Vendored
+193
@@ -0,0 +1,193 @@
|
||||
//! 完整程序装载与宿主返回值处理的无 UI 回归;需在获授权环境编译、执行。
|
||||
//! 使用可观察原生回调/析构检查入口策略和拥有根,避免依赖 Tessera 的页面实现。
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{
|
||||
CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload,
|
||||
ObjectRef, Value, VmError,
|
||||
};
|
||||
use endorphin_nexus_runtime::{
|
||||
DEFAULT_LIMITS, VmSession,
|
||||
program::{CodeRetention, PreparedProgram},
|
||||
};
|
||||
use frontend::EndorReader;
|
||||
use std::{
|
||||
any::Any,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
/// main 显式调用才递增,装载定义或检查源码不应触发该宿主能力。
|
||||
struct Mark(Arc<AtomicUsize>);
|
||||
impl NativeCallable for Mark {
|
||||
/// 宿主能力使用确定零参契约。
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
Some(CallArity::exact(0))
|
||||
}
|
||||
/// 返回纯数值给源 main,计数留在 VM 外观察。
|
||||
fn invoke(
|
||||
&self,
|
||||
_cx: &mut NativeContext<'_>,
|
||||
_args: &[Value],
|
||||
) -> Result<NativeResult, VmError> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(NativeResult::Return(Value::Number(7_i64.into())))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解码读取的借用对象身份,不建立或释放根。
|
||||
fn object(value: Value) -> ObjectRef {
|
||||
let Value::Object(value) = value else {
|
||||
panic!("expected object")
|
||||
};
|
||||
value
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 两种代码根策略都只执行模块定义;main 何时调用由宿主决定,装载的函数在代码根释放后仍有效。
|
||||
fn module_loading_preserves_function_identity_without_calling_main() {
|
||||
let program = PreparedProgram::compile(
|
||||
EndorReader::from_text(
|
||||
"headless module",
|
||||
"function main(): Number { return mark() }",
|
||||
),
|
||||
["mark".to_owned()].into_iter().collect(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(program.ast_nodes() > 0);
|
||||
for retention in [CodeRetention::Execution, CodeRetention::Session] {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
let mark = runtime
|
||||
.vm_mut()
|
||||
.allocate(ContextNativeFunction::new(
|
||||
"mark",
|
||||
Mark(calls.clone()),
|
||||
vec![],
|
||||
))
|
||||
.unwrap();
|
||||
runtime.keep_root(mark);
|
||||
runtime
|
||||
.vm_mut()
|
||||
.dict_set(globals, Value::Text("mark".into()), Value::Object(mark))
|
||||
.unwrap();
|
||||
runtime.execute_program(&program, retention).unwrap();
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
let main = object(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(globals, &Value::Text("main".into()))
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
let value = runtime
|
||||
.with_call_result(main, &[], DEFAULT_LIMITS, |_vm, value| {
|
||||
Ok(value.clone()) // 此处返回标量,不把借用的托管对象带出。
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(value, Value::Number(7_i64.into()));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 脚本中途出错不回滚前段写入,两种代码根清理路径都必须能关闭至空堆。
|
||||
fn script_failure_keeps_completed_writes_and_releases_both_code_policies() {
|
||||
let program = PreparedProgram::compile(
|
||||
EndorReader::from_text(
|
||||
"headless program failure",
|
||||
"total = 1\ntotal = total + 1\n1 / 0",
|
||||
),
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for retention in [CodeRetention::Execution, CodeRetention::Session] {
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
let error = runtime
|
||||
.execute_program(&program, retention)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("headless program failure"));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(globals, &Value::Text("total".into()))
|
||||
.unwrap(),
|
||||
Some(Value::Number(2_i64.into()))
|
||||
);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// 每个真正返回的新对象拥有独立析构事件,验证宿主处理失败后的根也被归还。
|
||||
struct Returned(Arc<AtomicUsize>);
|
||||
impl ObjectPayload for Returned {
|
||||
/// 支持 Aster 载荷识别,不引入额外托管出边。
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
/// 测试诊断类别,与 UI 名义类型无关。
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"returned-test-object"
|
||||
}
|
||||
}
|
||||
impl Drop for Returned {
|
||||
/// 真实拥有根归零时计数;仅 drop Rust Value 不会触发此回调。
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 模拟 main 返回新对象,返回前没有其他拥有边。
|
||||
struct Allocate(Arc<AtomicUsize>);
|
||||
impl NativeCallable for Allocate {
|
||||
/// 与宿主调用的空实参数量一致。
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
Some(CallArity::exact(0))
|
||||
}
|
||||
/// NativeContext 把分配根提升为返回根,Nexus 的处理接口负责后续归还。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let result = cx.allocate(Returned(self.0.clone()))?;
|
||||
Ok(NativeResult::Return(Value::Object(result)))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 成功/错误宿主处理都可在返回对象存活期间访问它,处理结束后立即释放唯一返回根。
|
||||
fn host_result_errors_release_the_returned_object() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let callee = runtime
|
||||
.vm_mut()
|
||||
.allocate(ContextNativeFunction::new(
|
||||
"allocate",
|
||||
Allocate(drops.clone()),
|
||||
vec![],
|
||||
))
|
||||
.unwrap();
|
||||
runtime.keep_root(callee);
|
||||
let baseline = runtime.vm().object_count();
|
||||
for fail in [false, true] {
|
||||
let result: Result<()> =
|
||||
runtime.with_call_result(callee, &[], DEFAULT_LIMITS, |vm, value| {
|
||||
assert!(vm.object(object(value.clone())).is_ok());
|
||||
if fail {
|
||||
bail!("host presentation failed");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(result.is_err(), fail);
|
||||
assert_eq!(runtime.vm().object_count(), baseline);
|
||||
}
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 2);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
Reference in New Issue
Block a user