Extract the Nexus runtime from Tessera

This commit is contained in:
2026-11-23 02:55:07 +08:00
parent 6d1ffdbcb4
commit 7217bbde97
36 changed files with 3973 additions and 2181 deletions
+128
View File
@@ -0,0 +1,128 @@
//! 无 UI 的持久输入回归,覆盖实际全局身份、准备阶段无副作用、失败边界和返回对象拥有关系。
//! 测试通过真实 VM 和借用/拥有根观察结果,不依赖 GUI 或历史回放。
use endor_core::Value;
use endorphin_nexus_runtime::{VmSession, budget::MAX_AST_NODES};
use frontend::EndorReader;
/// 新建只有真实全局字典的运行时,不安装任何 GUI 能力或重放历史输入。
fn session() -> VmSession {
let mut runtime = VmSession::new().unwrap();
runtime.create_globals().unwrap();
runtime
}
/// 独立来源标记用于检查运行错误仍指向当前输入,而非累计浏览 transcript。
fn execute(runtime: &mut VmSession, name: &str, text: &str) -> String {
let input = runtime
.prepare_input(EndorReader::from_text(name, text), 0)
.unwrap();
runtime.execute_input(input).unwrap()
}
/// 读取借用字典值,只用于观察;不会给对象额外建立拥有根。
fn global(runtime: &VmSession, name: &str) -> Option<Value> {
runtime
.vm()
.dict_get(runtime.globals().unwrap(), &Value::Text(name.into()))
.unwrap()
}
#[test]
/// 新输入使用原全局字典;准备成功也不执行,代码模板释放后函数仍可从全局被调用。
fn persistent_inputs_preserve_bindings_and_function_identity() {
let mut runtime = session();
let input = runtime
.prepare_input(EndorReader::from_text("first", "counter = 1"), 0)
.unwrap();
assert!(input.ast_nodes() > 0);
assert_eq!(input.source().text(), "counter = 1");
assert_eq!(input.plan().roots().len(), 1);
assert_eq!(global(&runtime, "counter"), None);
assert_eq!(runtime.execute_input(input).unwrap(), "1");
assert_eq!(
execute(&mut runtime, "second", "counter = counter + 1"),
"2"
);
assert_eq!(
global(&runtime, "counter"),
Some(Value::Number(2_i64.into()))
);
execute(
&mut runtime,
"definition",
"function identity(value: Number): Number { return value }",
);
// 表达式结果是函数对象;_ 必须建立真实强边,不能只保留 repr 或 Rust 句柄。
let display = execute(&mut runtime, "function value", "identity");
assert!(!display.is_empty());
assert_eq!(global(&runtime, "_"), global(&runtime, "identity"));
assert_eq!(execute(&mut runtime, "call", "identity(counter)"), "2");
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
}
#[test]
/// 全部片段编译成功前不执行;执行期失败保留前段写入,错误仍携带独立输入来源。
fn compile_failure_is_preflight_but_runtime_failure_keeps_prior_writes() {
let mut runtime = session();
execute(&mut runtime, "initial", "counter = 1");
assert!(
runtime
.prepare_input(
EndorReader::from_text("compile failure", "counter = 8\nnotDeclared"),
0
)
.is_err()
);
assert_eq!(
global(&runtime, "counter"),
Some(Value::Number(1_i64.into()))
);
let input = runtime
.prepare_input(
EndorReader::from_text("headless execution failure", "counter = 9\n1 / 0"),
0,
)
.unwrap();
let error = runtime.execute_input(input).unwrap_err().to_string();
assert!(error.contains("division by zero"));
assert!(error.contains("headless execution failure"));
assert_eq!(
global(&runtime, "counter"),
Some(Value::Number(9_i64.into()))
);
// 失败输入并未导致历史重放,后续输入继续操作同一当前全局值。
assert_eq!(execute(&mut runtime, "after failure", "counter + 1"), "10");
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
}
#[test]
/// 累计节点和输入字节预算在准备阶段失败,既不更新 _ 也不写业务变量。
fn source_and_cumulative_ast_limits_do_not_execute_partial_inputs() {
let mut runtime = session();
execute(&mut runtime, "initial", "counter = 3");
for used in [MAX_AST_NODES, usize::MAX] {
assert!(
runtime
.prepare_input(
EndorReader::from_text("over AST budget", "counter = 8"),
used
)
.is_err()
);
}
let large = " ".repeat(endorphin_nexus_runtime::MAX_SOURCE_BYTES + 1);
let error = runtime
.prepare_input(EndorReader::from_text("over source budget", large), 0)
.err()
.unwrap();
assert!(error.to_string().contains("input exceeds 1 MiB"));
assert_eq!(
global(&runtime, "counter"),
Some(Value::Number(3_i64.into()))
);
assert_eq!(global(&runtime, "_"), Some(Value::Number(3_i64.into())));
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
}
+117
View File
@@ -0,0 +1,117 @@
//! Console 历史与累计预算的无 UI 契约回归;需在获授权构建环境编译执行。
use endor_core::Value;
use endorphin_nexus_runtime::{
MAX_SOURCE_BYTES, VmSession, budget::MAX_AST_NODES, console::ConsoleHistory,
program::PreparedProgram,
};
use frontend::EndorReader;
/// 创建真实环境但不安装 UI;历史本身没有管理对象或回放职责。
fn session() -> VmSession {
let mut runtime = VmSession::new().unwrap();
runtime.create_globals().unwrap();
runtime
}
#[test]
/// 解析/编译失败不接受输入;运行错误发生在接受之后,历史和前段写入都保留。
fn only_accepted_inputs_enter_history_and_execution_errors_remain_recorded() {
let mut runtime = session();
let mut history = ConsoleHistory::default();
assert!(
history
.prepare(&runtime, 7, "value = 1\nunknownName")
.is_err()
);
assert_eq!(history.inputs(), 0);
assert_eq!(history.ast_nodes(), 0);
assert_eq!(history.source(), "");
let input = history.prepare(&runtime, 7, "value = 9\n1 / 0").unwrap();
assert_eq!(
format!("{}", input.source().origin()),
"console session 7 input 1"
);
let cost = input.ast_nodes();
let accepted = history.accept(input).unwrap();
assert_eq!(accepted.number(), 1);
assert_eq!(accepted.line_offset(), 1);
assert!(accepted.execute(&mut runtime).is_err());
assert_eq!(history.inputs(), 1);
assert_eq!(history.ast_nodes(), cost);
assert_eq!(history.source(), "// Console input 1\nvalue = 9\n1 / 0\n");
assert_eq!(
runtime
.vm()
.dict_get(runtime.globals().unwrap(), &Value::Text("value".into()))
.unwrap(),
Some(Value::Number(9_i64.into()))
);
runtime.close().unwrap();
}
#[test]
/// 输入次数与 AST 总量分别限制,失败准备不增加计数或追加分隔注释。
fn input_count_and_cumulative_ast_budgets_are_shared_by_headless_hosts() {
let mut runtime = session();
let mut history = ConsoleHistory::default();
// 简单表达式不触发 AST/字节上限,因此第 257 次明确检验次数门槛。
for number in 1..=256 {
let input = history.prepare(&runtime, 1, "1").unwrap();
let accepted = history.accept(input).unwrap();
assert_eq!(accepted.number(), number);
}
let before = history.source().to_owned();
assert!(history.prepare(&runtime, 1, "1").is_err());
assert_eq!(history.inputs(), 256);
assert_eq!(history.source(), before);
// 每个输入有多个浅层语句,避开单输入深度限制,实际检验跨输入累计结构量。
let mut history = ConsoleHistory::default();
let text = "value = 1\n".repeat(50);
let cost = history.prepare(&runtime, 2, &text).unwrap().ast_nodes();
let allowed = MAX_AST_NODES / cost;
assert!(allowed < 256);
for _ in 0..allowed {
let input = history.prepare(&runtime, 2, &text).unwrap();
history.accept(input).unwrap();
}
let before = history.source().to_owned();
let error = history.prepare(&runtime, 2, &text).err().unwrap();
assert!(error.to_string().contains("10000 AST nodes"));
assert_eq!(history.inputs(), allowed);
assert_eq!(history.ast_nodes(), cost * allowed);
assert_eq!(history.source(), before);
runtime.close().unwrap();
}
#[test]
/// 完整源码、Unicode 与 CRLF/CR 原文保持;输入偏移按共享字节行首规则计算,累计字节预算含程序文本。
fn program_history_preserves_source_and_enforces_the_combined_byte_budget() {
let mut runtime = session();
let raw = "base = 1\r\nlabel = \"中\"\r";
let program =
PreparedProgram::compile(EndorReader::from_text("program", raw), Default::default())
.unwrap();
let mut history = ConsoleHistory::from_program(&program);
assert_eq!(history.inputs(), 0);
assert_eq!(history.ast_nodes(), program.ast_nodes());
assert_eq!(history.source(), raw);
let input = history.prepare(&runtime, 8, "\"新\"\r\n").unwrap();
let accepted = history.accept(input).unwrap();
assert_eq!(accepted.line_offset(), 3);
assert_eq!(
history.source(),
format!("{raw}\n// Console input 1\n\"新\"\r\n")
);
assert_eq!(accepted.execute(&mut runtime).unwrap(), "\"新\"");
// 近上限的有效程序只包含长注释和一个表达式;新输入要计算既有文本和固定分隔余量。
let raw = format!("//{}\n1", "x".repeat(MAX_SOURCE_BYTES - 20));
let program = PreparedProgram::compile(
EndorReader::from_text("large program", raw),
Default::default(),
)
.unwrap();
let history = ConsoleHistory::from_program(&program);
assert!(history.prepare(&runtime, 9, "1").is_err());
assert_eq!(history.inputs(), 0);
runtime.close().unwrap();
}
+170
View File
@@ -0,0 +1,170 @@
//! 不依赖 Tessera 的 Nexus 宿主契约回归;需在获授权的构建环境编译/执行。
//! 验证宿主注册、半完成安装清理、脚本跨片名称和原文位置,而不是复制私有实现断言。
use anyhow::{Result, bail};
use endor_core::{ObjectPayload, ObjectRef, Value, Vm};
use endorphin_nexus_runtime as nexus;
use frontend::{
EndorReader,
ast::{Spanned, visitor::Visitor},
};
use nexus::{HostRegistration, VmSession, budget::AstBudget, program::compile_plan};
use std::{
any::Any,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
#[derive(Debug)]
/// 由假宿主分配的资源,析构计数在 VM 外可观察,不携带 UI 类型或托管出边。
struct Capability(Arc<AtomicUsize>);
impl Drop for Capability {
/// 最后强边移除时真正释放资源;根归还与 Rust 句柄复制不应增加此计数。
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
impl ObjectPayload for Capability {
/// Aster 载荷下转型入口,独立于宿主的名义类型注册。
fn as_any(&self) -> &dyn Any {
self
}
/// 为错误/诊断提供类别,不让测试依赖 Tessera 的类型名。
fn kind_name(&self) -> &'static str {
"test-capability"
}
}
/// 只依赖 Nexus/Aster 的假宿主;可在分配并登记根后故意失败,观察安装失败的收尾。
struct Host {
drops: Arc<AtomicUsize>,
fail: bool,
}
impl HostRegistration for Host {
type Installed = ObjectRef;
/// Nexus 调用注册接口,宿主向实际 globals 安装能力,返回借用身份供测试检查。
fn register(
&self,
vm: &mut Vm,
roots: &mut Vec<ObjectRef>,
globals: ObjectRef,
) -> Result<ObjectRef> {
// 先登记拥有根,后续字典安装或故意失败都不能丢掉清理责任。
let capability = vm.allocate(Capability(self.drops.clone()))?;
roots.push(capability);
// 错误发生在能力根创建之后,检验会话能清理半完成注册。
if self.fail {
bail!("host registration failed");
}
vm.dict_set(
globals,
Value::Text("capability".into()),
Value::Object(capability),
)?;
Ok(capability)
}
}
#[test]
/// 宿主通过接口注册后,全局真实持有同一能力;close 释放根和字典边,重复 close 无副作用。
fn host_registration_uses_the_owned_vm_and_cleans_its_resources() {
// 计数器不在 VM 内,资源销毁后仍可用于观察。
let drops = Arc::new(AtomicUsize::new(0));
// 空会话不暗中安装 ui 或任何宿主对象。
let mut runtime = VmSession::new().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
// 主环境拥有根由 Nexus 会话登记,宿主只收到借用句柄。
let globals = runtime.create_globals().unwrap();
// Installed 身份借用会话根,不能再把它当成独立拥有结果释放。
let capability = runtime
.register_host(&Host {
drops: drops.clone(),
fail: false,
})
.unwrap();
assert_eq!(
runtime
.vm()
.dict_get(globals, &Value::Text("capability".into()))
.unwrap(),
Some(Value::Object(capability))
);
assert_eq!(runtime.vm().ref_count(capability).unwrap(), 2);
runtime.close().unwrap();
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
assert_eq!(drops.load(Ordering::SeqCst), 1);
}
#[test]
/// 缺环境时不进入宿主;重复环境初始化不分配;宿主部分失败留下的根仍由会话 close 清理。
fn failed_registration_and_repeated_initialization_preserve_cleanup() {
// 假宿主每次实际分配一个可计数资源。
let drops = Arc::new(AtomicUsize::new(0));
// 没有 globals 的会话应在调用宿主之前拒绝注册。
let mut runtime = VmSession::new().unwrap();
assert!(
runtime
.register_host(&Host {
drops: drops.clone(),
fail: false
})
.is_err()
);
assert_eq!(runtime.vm().object_count(), 0);
runtime.create_globals().unwrap();
assert!(runtime.create_globals().is_err());
assert_eq!(runtime.vm().object_count(), 1);
assert!(
runtime
.register_host(&Host {
drops: drops.clone(),
fail: true
})
.is_err()
);
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
assert_eq!(drops.load(Ordering::SeqCst), 1);
}
#[test]
/// 脚本根保留原文跨度并按源序编译,后段读取前段建立的真实全局,不需要 UI 注册。
fn script_compilation_preserves_spans_and_shared_globals_without_ui() {
// 两个顶层交互片段,第二片段依赖前面的赋值名称。
let source = EndorReader::from_text("headless", "value = 2\nvalue + 3");
// Nexus 组织输入,词法/语法与 AST 节点继续由 Aster 提供。
let plan = nexus::source::parse(&source).unwrap();
assert_eq!(plan.roots().len(), 2);
assert!(plan.roots()[1].span().start >= "value = 2\n".len());
// 所有片段共享预算访问器,退出子树不重置累计节点数。
let mut budget = AstBudget::default();
for root in plan.roots() {
budget.visit_ast_root(root).unwrap();
}
assert!(budget.nodes() > 0);
// 空宿主名称集仍允许后续片段引用前段赋值,实际值由 VM 执行建立。
let templates = compile_plan(&source, &plan, Default::default()).unwrap();
// 一份 owning VM 和 globals 贯穿各片段,执行后归还每次返回的根。
let mut runtime = VmSession::new().unwrap();
let globals = runtime.create_globals().unwrap();
for (index, template) in templates.iter().enumerate() {
// 加载的代码根交给运行时清理,既不跨 VM 复用也不留下测试外根。
let code = template.load(runtime.vm_mut()).unwrap();
runtime.keep_root(code);
// 第一段赋值为 Nil,第二段求值应得到精确整数五。
let value = runtime
.vm_mut()
.execute_with_limits(code, globals, nexus::DEFAULT_LIMITS)
.unwrap();
if index == 1 {
assert_eq!(value, Value::Number(5_i64.into()));
}
runtime.vm_mut().release_value(value).unwrap();
}
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
assert!(nexus::evaluate("ui").is_err());
assert_eq!(nexus::evaluate("0.1 + 0.2 == 0.3").unwrap(), "true");
}
+193
View File
@@ -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);
}
+243
View File
@@ -0,0 +1,243 @@
//! 无 UI 的任务宿主回归:同键替换、资格变化和退出门闩必须由真实 VM/API 路径体现。
//! 测试不启动 GUI、文件读取或网络请求,宿主资格由普通对象属性提供。
use endor_core::{
CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef,
ObjectStore, TypeConstructor, Value, Vm, VmError,
};
use endorphin_nexus_runtime::{
VmSession,
tasks::{self, Scheduler, TaskHost},
};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
#[derive(Debug)]
/// 普通对象宿主只用属性保存作用域和资格,不知道 Block、Mount、Window 或 desktop。
struct PlainHost;
impl TaskHost for PlainHost {
/// 未提交过任务时返回 None;已有作用域必须是字典。
fn scope(&self, store: &ObjectStore, owner: ObjectRef) -> Result<Option<ObjectRef>, VmError> {
match store.get_attr(owner, "taskScope") {
Ok(Value::Object(scope)) => {
store.dict_items(scope)?;
Ok(Some(scope))
}
Err(VmError::AttributeNotFound(_)) => Ok(None),
Ok(_) => Err(VmError::InvalidArgument("invalid test scope")),
Err(error) => Err(error),
}
}
/// 由写屏障建立真实拥有边,测试结束时可交给 VM 正常回收。
fn install_scope(
&self,
cx: &mut NativeContext<'_>,
owner: ObjectRef,
scope: ObjectRef,
) -> Result<(), VmError> {
cx.set_attr(owner, "taskScope", Value::Object(scope))
}
/// 外部修改普通布尔字段即可撤销交付资格,不借用 Tessera 的任何模型。
fn eligible(
&self,
store: &ObjectStore,
owner: ObjectRef,
_context: ObjectRef,
) -> Result<bool, VmError> {
Ok(store.get_attr(owner, "eligible")? == Value::Bool(true))
}
/// 所有任务共享宿主注册的精确类型身份。
fn task_type(&self, store: &ObjectStore, context: ObjectRef) -> Result<ObjectRef, VmError> {
object(store.get_attr(context, "Task")?)
}
}
#[derive(Debug)]
/// VM 外的计数器观察真正回调次数,零参/Unit 契约与 after 要求一致。
struct Count(Arc<AtomicUsize>);
impl NativeCallable for Count {
/// 明确接受零个参数,不能依赖旧原生函数缺少元数据的兼容路径。
fn arity(&self) -> Option<CallArity> {
Some(CallArity::exact(0))
}
/// 每次真正执行递增一次,取消和状态查询不得触发它。
fn invoke(
&self,
_cx: &mut NativeContext<'_>,
_args: &[Value],
) -> Result<NativeResult, VmError> {
self.0.fetch_add(1, Ordering::SeqCst);
Ok(NativeResult::Return(Value::Nil))
}
}
/// 解码借用或拥有的对象值;此函数不改变根计数,调用方按来源管理拥有权。
fn object(value: Value) -> Result<ObjectRef, VmError> {
match value {
Value::Object(value) => Ok(value),
_ => Err(VmError::InvalidArgument("expected test object")),
}
}
/// 所有创建根交给 VmSession;api/context/owner 是会话根的借用身份。
fn setup() -> (
VmSession,
Scheduler,
ObjectRef,
ObjectRef,
ObjectRef,
Arc<AtomicUsize>,
) {
let mut runtime = VmSession::new().unwrap();
let types = runtime.vm_mut().bootstrap_types().unwrap();
runtime.keep_root(types.object);
runtime.keep_root(types.type_type);
let definition = runtime
.vm_mut()
.new_type("Task", types.object, TypeConstructor::Abstract)
.unwrap();
runtime.keep_root(definition);
let context = runtime.vm_mut().new_object().unwrap();
runtime.keep_root(context);
runtime
.vm_mut()
.set_attr(context, "Task", Value::Object(definition))
.unwrap();
let api = runtime.vm_mut().new_object().unwrap();
runtime.keep_root(api);
let owner = runtime.vm_mut().new_object().unwrap();
runtime.keep_root(owner);
runtime
.vm_mut()
.set_attr(owner, "eligible", Value::Bool(true))
.unwrap();
let calls = Arc::new(AtomicUsize::new(0));
let callback = runtime
.vm_mut()
.allocate(ContextNativeFunction::new(
"count",
Count(calls.clone()),
vec![],
))
.unwrap();
runtime.keep_root(callback);
let scheduler = runtime
.with_host(|vm, roots| tasks::install(vm, roots, api, context, Arc::new(PlainHost)))
.unwrap();
(runtime, scheduler, api, owner, callback, calls)
}
/// 通过安装的公开 API 创建零延时任务;返回根交给会话,避免旧 token 因替换而提前回收。
fn after(
runtime: &mut VmSession,
api: ObjectRef,
owner: ObjectRef,
callback: ObjectRef,
key: &str,
) -> ObjectRef {
let function = object(runtime.vm().get_attr(api, "after").unwrap()).unwrap();
let task = object(
runtime
.vm_mut()
.call(
function,
&[
Value::Object(owner),
Value::Text(key.into()),
Value::Number(0_i64.into()),
Value::Object(callback),
],
)
.unwrap(),
)
.unwrap();
runtime.keep_root(task);
task
}
/// 经真实类型方法绑定读取状态,不直接检查 Nexus 的私有 Task 载荷。
fn query(vm: &mut Vm, task: ObjectRef, name: &str) -> Value {
let bound = object(vm.bind_attr(task, name).unwrap()).unwrap();
let result = vm.call(bound, &[]);
vm.release(bound).unwrap();
result.unwrap()
}
#[test]
/// 替换旧 token 后只有新任务执行一次;终态 token 可继续查询,拥有字典已经清空。
fn same_key_replacement_only_delivers_the_new_identity() {
let (mut runtime, scheduler, api, owner, callback, calls) = setup();
let old = after(&mut runtime, api, owner, callback, "same");
let new = after(&mut runtime, api, owner, callback, "same");
assert_eq!(
query(runtime.vm_mut(), old, "status"),
Value::Text("cancelled".into())
);
// 取消被替换的旧 token 不得删除新任务的 owner/key 身份。
assert_eq!(query(runtime.vm_mut(), old, "cancel"), Value::Bool(false));
assert_eq!(query(runtime.vm_mut(), new, "active"), Value::Bool(true));
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 1);
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(
query(runtime.vm_mut(), new, "status"),
Value::Text("completed".into())
);
assert_eq!(query(runtime.vm_mut(), new, "result"), Value::Nil);
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 0);
let scope = PlainHost
.scope(runtime.vm().object_store(), owner)
.unwrap()
.unwrap();
assert!(
runtime
.vm()
.object_store()
.dict_items(scope)
.unwrap()
.is_empty()
);
scheduler.quiesce(runtime.vm_mut()).unwrap();
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
}
#[test]
/// 交付前撤销资格阻止回调,轮询执行取消;退出门闩在重新取得资格后仍拒绝提交。
fn host_lifecycle_and_shutdown_prevent_late_delivery() {
let (mut runtime, scheduler, api, owner, callback, calls) = setup();
let task = after(&mut runtime, api, owner, callback, "late");
runtime
.vm_mut()
.set_attr(owner, "eligible", Value::Bool(false))
.unwrap();
assert_eq!(query(runtime.vm_mut(), task, "active"), Value::Bool(false));
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 1);
assert_eq!(
query(runtime.vm_mut(), task, "status"),
Value::Text("cancelled".into())
);
assert_eq!(calls.load(Ordering::SeqCst), 0);
scheduler.quiesce(runtime.vm_mut()).unwrap();
runtime
.vm_mut()
.set_attr(owner, "eligible", Value::Bool(true))
.unwrap();
let function = object(runtime.vm().get_attr(api, "after").unwrap()).unwrap();
assert!(
runtime
.vm_mut()
.call(
function,
&[
Value::Object(owner),
Value::Text("forbidden".into()),
Value::Number(0_i64.into()),
Value::Object(callback),
]
)
.is_err()
);
runtime.close().unwrap();
assert_eq!(runtime.vm().object_count(), 0);
}