docs: explain graphics resources and runtime dispatch lifecycles
This commit is contained in:
+47
-14
@@ -1,9 +1,9 @@
|
||||
//! 区分完整 Module 与顶层 Script,并保留输入源码位置。
|
||||
//! 解析包装或片段拼接产生的 span 偏移要递归修正,保证诊断和 Sources 视图仍指向用户原始行列。
|
||||
//!
|
||||
//! Feed a source snapshot to Aster's existing module or interactive entry points.
|
||||
//! Statement syntax, tokens and ASTs all remain Aster-owned. The host only batches
|
||||
//! complete interactive inputs, just as a REPL feeds consecutive inputs to a VM.
|
||||
//! runtime::endor_host 的一次性 compile 和持久会话加载调用 parse,再按 roots 进行 AST 预算检查与编译。
|
||||
//! 语句、词法和 AST 定义属于 Aster;这里只把完整源码组织成 Module 或连续 Interactive 输入。
|
||||
//! 片段先用局部字节位置解析,shift_* 递归加回起点,编译错误和 Sources 浏览才能仍对应原文件。
|
||||
use anyhow::Result;
|
||||
use frontend::{
|
||||
ParseMode, SourceUnit, Span, TokenKind,
|
||||
@@ -12,41 +12,54 @@ use frontend::{
|
||||
|
||||
/// 待编译输入是完整模块还是顶层脚本;两者保留不同根结构但使用统一后续接口。
|
||||
pub enum SourcePlan {
|
||||
// 保留 Aster 完整模块根,后续作为一个编译/执行单元,不拆开函数或类的定义体。
|
||||
Module(AstRoot),
|
||||
// 顶层脚本按完整交互输入连续执行;各段仍共享所属运行时的全局环境,而非各建一个 VM。
|
||||
Script(Vec<AstRoot>),
|
||||
}
|
||||
|
||||
impl SourcePlan {
|
||||
/// 按输入计划返回需要编译的语法根,隐藏 Script 与 Module 组织差异。
|
||||
/// endor_host 的 AST 预算访问和 compile_plan 调用,借用统一根切片,不克隆 AST 或重新解析。
|
||||
pub fn roots(&self) -> &[AstRoot] {
|
||||
match self {
|
||||
// 单模块以单元素切片适配,让调用方不必维护两套遍历分支。
|
||||
Self::Module(root) => std::slice::from_ref(root),
|
||||
// 脚本直接保留原输入段顺序,声明和后续使用语句的先后关系不能重排。
|
||||
Self::Script(roots) => roots,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 优先解析完整模块,否则按可完成的交互输入分段为 Script,并将 AST/诊断位置映回原文。
|
||||
/// endor_host 执行入口调用,优先接受完整 Module,失败则按顶层换行候选边界拼出 Aster 可解析的交互输入。
|
||||
/// 模块解析失败本身不立即作为最终错误:普通顶层脚本本就需要走后面的 Interactive 解析路径。
|
||||
pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
// 完整模块优先;只有模块解析失败才退回连续交互输入模式,宿主不自行实现 Endor 语法。
|
||||
if let Ok(module) = frontend::parse_source_ast(source, ParseMode::Module) {
|
||||
// 模块成功就不再按行切分,避免破坏跨行声明与完整模块语义。
|
||||
return Ok(SourcePlan::Module(module));
|
||||
}
|
||||
// 一次词法分析获得原始字节 span,候选分段依赖 token 之间的实际换行而非直接按行切字符串。
|
||||
let tokens = frontend::lex_source(source)?;
|
||||
// 只保存已被 Aster 成功接受的交互根,失败候选不留下半棵 AST。
|
||||
let mut roots = Vec::new();
|
||||
// start 为当前待解析片段在原文件中的字节起点,仅在候选成功时前移。
|
||||
let mut start = 0;
|
||||
// 深度只是候选边界启发式;括号失配是否合法仍由 Aster 判定,不在宿主偷偷修正。
|
||||
let mut depth = 0_i64;
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
// 追踪圆/花括号嵌套,括号内换行不能直接结束输入;最终语法是否合法仍交给 Aster。
|
||||
match token.kind {
|
||||
// token 已由词法器识别,字符串/注释里的括号不会当作结构括号改变深度。
|
||||
TokenKind::LeftParen | TokenKind::LeftBrace => depth += 1,
|
||||
TokenKind::RightParen | TokenKind::RightBrace => depth -= 1,
|
||||
// 其他 token 不改变边界嵌套,不能靠普通字符扫描替代此判断。
|
||||
_ => {}
|
||||
}
|
||||
// token 尾为原文本字节位置,用它取与下一 token 之间的空白/注释区域查换行。
|
||||
let end = token.span.end;
|
||||
// 末尾 token 总是尝试解析;非末尾要求顶层换行,且下一 token 不像成员访问、调用或算术续接。
|
||||
let boundary = tokens.get(index + 1).is_none_or(|next| {
|
||||
// 尚在括号内,或下一 token 明显续接上个表达式时,不尝试提前提交当前交互片段。
|
||||
depth == 0
|
||||
&& source.text()[end..next.span.start].contains(['\r', '\n'])
|
||||
&& !matches!(
|
||||
@@ -60,11 +73,13 @@ pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
)
|
||||
});
|
||||
if !boundary {
|
||||
// 保留 start,之后尝试更长的片段;不是丢弃当前 token 对应源码。
|
||||
continue;
|
||||
}
|
||||
// 当前片段从上一次成功边界 start 开始,保留期间的空白与注释;解析器看到的是片段局部字节位置。
|
||||
match frontend::parse_ast(&source.text()[start..end], ParseMode::Interactive) {
|
||||
Ok(mut root) => {
|
||||
// Interactive 模式的成功根必须为 Interactive;违反是前端接口不变量错误。
|
||||
let AstRoot::Interactive(input) = &mut root else {
|
||||
unreachable!("interactive mode");
|
||||
};
|
||||
@@ -73,10 +88,9 @@ pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
roots.push(root);
|
||||
start = end;
|
||||
}
|
||||
// An incomplete interactive input can continue on the next line.
|
||||
// Only Aster decides whether its combined syntax is valid.
|
||||
// 错误恰在片段末尾且还有 token 时,视为可能未完成的交互输入,保持 start 不动继续拼接。
|
||||
Err(diagnostic) if index + 1 < tokens.len() && diagnostic.span.start == end - start => {
|
||||
// 只有“诊断正好指向片段末尾”才暂缓,下一候选会连同当前片段一起再交 Aster 解析。
|
||||
}
|
||||
Err(mut diagnostic) => {
|
||||
// 其他语法错误立即恢复原始偏移,再用 SourceUnit 添加原文件来源与行列诊断。
|
||||
@@ -87,20 +101,20 @@ pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
}
|
||||
// 空输入不能静默产生空计划;再次委托交互入口给出解析器自己的空输入诊断与来源。
|
||||
if roots.is_empty() {
|
||||
// Produce Aster's original empty-input diagnostic and provenance.
|
||||
// 不自造宿主错误字符串,保留前端对空输入的原始诊断和 SourceUnit 来源信息。
|
||||
frontend::parse_source_ast(source, ParseMode::Interactive)?;
|
||||
}
|
||||
Ok(SourcePlan::Script(roots))
|
||||
}
|
||||
|
||||
/// 为单个半开字节范围加回片段起始偏移,不处理其所属节点的子节点。
|
||||
/// 下方所有 shift_* 调用的基本操作,给单个半开字节范围加偏移,不递归、不改变源码内容。
|
||||
fn shift_span(span: &mut Span, offset: usize) {
|
||||
// span 采用原文本字节偏移,start/end 同增 offset 保持长度;不是按字符数或行数偏移。
|
||||
span.start += offset;
|
||||
span.end += offset;
|
||||
}
|
||||
|
||||
/// 递归调整对应语法节点的源码范围,保持片段解析后的错误位置仍指向原输入。
|
||||
/// parse 在接受一个 Interactive 根后调用,平移交互根范围,再把语句交给 shift_statement 递归。
|
||||
fn shift_input(input: &mut InteractiveInput, offset: usize) {
|
||||
shift_span(&mut input.span, offset);
|
||||
// 根范围之外,逐条语句递归处理所有内层节点,避免错误只在顶层位置正确。
|
||||
@@ -109,18 +123,21 @@ fn shift_input(input: &mut InteractiveInput, offset: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归调整对应语法节点的源码范围,保持片段解析后的错误位置仍指向原输入。
|
||||
/// shift_input/函数体/分支体的递归入口,按语句种类平移自己的范围和所有内嵌表达式/声明。
|
||||
fn shift_statement(statement: &mut Stmt, offset: usize) {
|
||||
shift_span(&mut statement.span, offset);
|
||||
match &mut statement.kind {
|
||||
StmtKind::If(branch) => {
|
||||
// If 节点、条件、then 块各有独立 span,平移外层 Stmt 不能自动更新它们。
|
||||
shift_span(&mut branch.span, offset);
|
||||
shift_expression(&mut branch.condition, offset);
|
||||
shift_span(&mut branch.body.span, offset);
|
||||
for s in &mut branch.body.statements {
|
||||
// then 内可能继续嵌套 if/while/声明,不能只调整第一层语句外框。
|
||||
shift_statement(s, offset);
|
||||
}
|
||||
if let Some(body) = &mut branch.otherwise {
|
||||
// else 可省略;存在时块范围和其中每条语句都使用同一个原片段偏移。
|
||||
shift_span(&mut body.span, offset);
|
||||
for s in &mut body.statements {
|
||||
shift_statement(s, offset);
|
||||
@@ -128,6 +145,7 @@ fn shift_statement(statement: &mut Stmt, offset: usize) {
|
||||
}
|
||||
}
|
||||
StmtKind::While(loop_) => {
|
||||
// while 条件和循环体均可含更深的调用/控制流,沿各自 AST 子结构递归而非重新扫描文本。
|
||||
shift_span(&mut loop_.span, offset);
|
||||
shift_expression(&mut loop_.condition, offset);
|
||||
shift_span(&mut loop_.body.span, offset);
|
||||
@@ -136,11 +154,13 @@ fn shift_statement(statement: &mut Stmt, offset: usize) {
|
||||
}
|
||||
}
|
||||
StmtKind::Binding(binding) => {
|
||||
// 新绑定独立保存名字和右值范围,诊断未定义符号时需要内部表达式位置正确。
|
||||
shift_span(&mut binding.span, offset);
|
||||
shift_span(&mut binding.name.span, offset);
|
||||
shift_expression(&mut binding.value, offset);
|
||||
}
|
||||
StmtKind::Assignment(assignment) => {
|
||||
// 赋值不同于声明,但同样保留名字与右值两个来源范围,不能仅平移整个语句。
|
||||
shift_span(&mut assignment.span, offset);
|
||||
shift_span(&mut assignment.name.span, offset);
|
||||
shift_expression(&mut assignment.value, offset);
|
||||
@@ -153,41 +173,49 @@ fn shift_statement(statement: &mut Stmt, offset: usize) {
|
||||
shift_expression(&mut assignment.value, offset);
|
||||
}
|
||||
StmtKind::Return(returned) => {
|
||||
// return 自身 span 必须平移;无返回表达式的 Unit 返回不能访问不存在的 value。
|
||||
shift_span(&mut returned.span, offset);
|
||||
if let Some(expression) = &mut returned.value {
|
||||
// 返回值可以是任意复合调用/算术表达式,继续下钻到全部名称和实参。
|
||||
shift_expression(expression, offset);
|
||||
}
|
||||
}
|
||||
// 表达式语句复用完整表达式递归,避免调用参数中的错误仍显示片段局部行列。
|
||||
StmtKind::Expression(expression) => shift_expression(expression, offset),
|
||||
// 顶层/局部声明转交类与函数专用入口,处理参数、类型名及函数体。
|
||||
StmtKind::Declaration(declaration) => shift_declaration(declaration, offset),
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归调整对应语法节点的源码范围,保持片段解析后的错误位置仍指向原输入。
|
||||
/// shift_statement 在声明语句中调用,平移 Decl 外层,再区分函数定义与类定义的内部位置。
|
||||
fn shift_declaration(declaration: &mut Decl, offset: usize) {
|
||||
shift_span(&mut declaration.span, offset);
|
||||
match &mut declaration.kind {
|
||||
// 普通函数和类方法使用相同函数结构,统一由 shift_function 平移签名和函数体。
|
||||
DeclKind::Function(function) => shift_function(function, offset),
|
||||
// 类的名称、基类、字段类型和方法均保存独立 span,不能仅移动声明外层范围。
|
||||
DeclKind::Class(class) => {
|
||||
shift_span(&mut class.span, offset);
|
||||
shift_span(&mut class.name.span, offset);
|
||||
if let Some(base) = &mut class.base {
|
||||
// 无显式基类时不新增默认基类 span,保留前端原始 AST 的可选结构。
|
||||
shift_span(&mut base.span, offset);
|
||||
}
|
||||
for field in &mut class.fields {
|
||||
// 字段节点整体、字段名、类型名分别保存位置,错误类型注解必须指回原文件。
|
||||
shift_span(&mut field.span, offset);
|
||||
shift_span(&mut field.name.span, offset);
|
||||
shift_span(&mut field.type_name.span, offset);
|
||||
}
|
||||
for method in &mut class.methods {
|
||||
// 方法体可能包含更多声明,沿同一套递归入口继续处理。
|
||||
shift_function(method, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归调整对应语法节点的源码范围,保持片段解析后的错误位置仍指向原输入。
|
||||
/// shift_declaration 调用,平移函数名、参数/返回注解和函数体,供编译器类型错误使用原输入坐标。
|
||||
fn shift_function(function: &mut frontend::ast::Function, offset: usize) {
|
||||
shift_span(&mut function.span, offset);
|
||||
shift_span(&mut function.name.span, offset);
|
||||
@@ -200,11 +228,12 @@ fn shift_function(function: &mut frontend::ast::Function, offset: usize) {
|
||||
}
|
||||
shift_span(&mut function.body.span, offset);
|
||||
for statement in &mut function.body.statements {
|
||||
// 函数体内每条语句继续按 kind 递归,不能用整体函数范围覆盖内部诊断。
|
||||
shift_statement(statement, offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归调整对应语法节点的源码范围,保持片段解析后的错误位置仍指向原输入。
|
||||
/// 语句/函数递归助手调用,平移表达式与名称成员的范围;语义值和运算符本身保持不变。
|
||||
fn shift_expression(expression: &mut Expr, offset: usize) {
|
||||
shift_span(&mut expression.span, offset);
|
||||
match &mut expression.kind {
|
||||
@@ -212,13 +241,16 @@ fn shift_expression(expression: &mut Expr, offset: usize) {
|
||||
ExprKind::Name(_) | ExprKind::Number(_) | ExprKind::String(_) => {}
|
||||
ExprKind::Symbol(name) => shift_span(&mut name.span, offset),
|
||||
ExprKind::Unary { operand, .. } | ExprKind::Await(operand) => {
|
||||
// unary 与 await 都只有一个子表达式,操作符来源已在外层表达式 span 覆盖。
|
||||
shift_expression(operand, offset)
|
||||
}
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
// 两侧都可能含复合表达式,不能只调整最终报错概率更高的右侧。
|
||||
shift_expression(left, offset);
|
||||
shift_expression(right, offset);
|
||||
}
|
||||
ExprKind::Member { object, name } => {
|
||||
// object 可能是调用返回值,name 则是独立标识符,分别调整两类来源。
|
||||
shift_expression(object, offset);
|
||||
shift_span(&mut name.span, offset);
|
||||
}
|
||||
@@ -226,6 +258,7 @@ fn shift_expression(expression: &mut Expr, offset: usize) {
|
||||
ExprKind::Call { callee, arguments } => {
|
||||
shift_expression(callee, offset);
|
||||
for argument in arguments {
|
||||
// 保持实参顺序和值不变,只平移每个实参树内部保存的字节位置。
|
||||
shift_expression(argument, offset);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! 托管事件与订阅的传播实现。Connection 持有回调引用,Event 保存目标、阶段与停止传播状态。
|
||||
//! 分发沿出现关系执行 capture → target → bubble,记录默认行为阻止状态;只有同一 VM 中的回调可以接触托管对象。
|
||||
//!
|
||||
//! Managed subscriptions and occurrence-specific propagation. A validated VM
|
||||
//! function sequences calls, so all handlers share one execution budget.
|
||||
//! bootstrap 调用 install 安装 Event/Subscription 控制方法;ui_bridge::calls 和 graphics/scene3d 指针适配调用 dispatch。
|
||||
//! dispatch 只快照路线并生成驱动,真正回调执行由 VM 调用 Delivery,再通过 Invoke 接回源处理器。
|
||||
//! vm_sequence::build 使整次传播共用同一执行预算;每次具体 Mount 是独立传播上下文,不从共享业务树猜父链。
|
||||
use crate::{block, mount::Mount, ui_bridge::attach_desktop_type};
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
||||
@@ -11,19 +12,21 @@ use endor_core::{
|
||||
|
||||
// 一次分发最多安排 10000 个处理器,另由共享 VM 驱动约束全部回调的总执行预算。
|
||||
const MAX_DELIVERIES: usize = 10_000;
|
||||
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
|
||||
/// 订阅检查、事件构造与传播分支共用的参数错误构造器,源诊断位置由外层 VM 调用栈提供。
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
|
||||
/// 检查订阅回调满足事件处理器调用契约,避免等到实际点击才暴露签名错误。
|
||||
/// ui_bridge::calls 安装 on/onClick 时调用,检查零参或单 Event 回调能力,不在此执行用户函数。
|
||||
pub fn validate_handler(
|
||||
store: &endor_core::ObjectStore,
|
||||
function: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
if !store.object(function)?.payload().is_function() {
|
||||
// 普通 Object 即使有 call 属性也不能作为这里的 Function 注册,避免实际分派才暴露类型错误。
|
||||
return Err(invalid("event handler must be a Function"));
|
||||
}
|
||||
// 元数据必须明确存在;不能把未知 arity 当作“随便传一个 Event 总能工作”。
|
||||
let arity = store
|
||||
.call_arity(function)?
|
||||
.ok_or(invalid("event handler requires positional metadata"))?;
|
||||
@@ -72,8 +75,11 @@ impl ObjectPayload for Event {
|
||||
#[derive(Debug, Clone)]
|
||||
/// 实际拥有回调引用的托管连接,挂在目标的订阅关系中参与 GC。
|
||||
pub struct Connection {
|
||||
// Block 的 subscriptions 强持 Connection,Connection 再强持 handler;取消时将这一强边置空。
|
||||
pub handler: Option<ObjectRef>,
|
||||
// 与 Event.kind 比较的精确事件字符串,不对事件名称做前缀或真值匹配。
|
||||
pub kind: String,
|
||||
// 区分捕获和非捕获队列;目标阶段两种队列仍共享一个传播组。
|
||||
pub capture: bool,
|
||||
}
|
||||
impl ObjectPayload for Connection {
|
||||
@@ -92,15 +98,16 @@ impl ObjectPayload for Connection {
|
||||
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(handler) = self.handler {
|
||||
// Aster GC 访问者只收到当前仍连接的处理器;None 不再保活旧回调及它捕获的业务对象。
|
||||
visit(handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A token never retains its target or callback. The Block owns the connection.
|
||||
#[derive(Debug)]
|
||||
/// 源代码可保留的订阅能力包装,用于取消对应连接。
|
||||
pub struct Subscription {
|
||||
// 事件 Connection 或属性 Binding 的弱引用;用户长期保留 token 不应反向保活目标和计算闭包。
|
||||
pub connection: WeakObjectRef,
|
||||
}
|
||||
impl ObjectPayload for Subscription {
|
||||
@@ -119,7 +126,7 @@ impl ObjectPayload for Subscription {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
/// 保存 owner、签名或操作枚举的原生方法适配器,统一由 VM 调用。
|
||||
/// install 的名义方法表选用的操作标签;TypedMethod 提供类型契约,Method 只执行对应状态变化/查询。
|
||||
enum Method {
|
||||
Stop,
|
||||
StopImmediate,
|
||||
@@ -134,17 +141,21 @@ impl NativeCallable for Method {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
/// 按操作读取或修改连接/传播状态;断开清除真实 handler/compute,停止标志写回同一 Event。
|
||||
/// TypedMethod::invoke 转交,按 receiver payload 查询/取消订阅,或更新当前事件传播控制标志。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
// 方法接收者仍在 args[0];不像 UiBridge 的 TypeMethod,这个包装没有提前把 owner 剥出来。
|
||||
let [Value::Object(owner)] = args else {
|
||||
return Err(invalid("event method receiver"));
|
||||
};
|
||||
// 取消/查询订阅和传播控制使用不同 payload,先按方法标签分流再进行受检查的向下转型。
|
||||
let result = match self {
|
||||
Self::Disconnect | Self::Connected => {
|
||||
// Subscription 不直接拥有 Connection,读弱身份后在当前 NativeContext 中临时升级。
|
||||
let weak = cx
|
||||
.store()
|
||||
.payload::<Subscription>(*owner, "Subscription")?
|
||||
.connection;
|
||||
// 已死亡连接正常得到 None,isConnected=false/disconnect 无动作,而不是新建连接。
|
||||
let connection = cx.upgrade(weak)?;
|
||||
// Subscription 同时包装事件 Connection 和属性 Binding;按 payload 类型清 handler 或 compute。
|
||||
let connected = if let Some(connection) = connection {
|
||||
@@ -155,10 +166,12 @@ impl NativeCallable for Method {
|
||||
.as_any()
|
||||
.is::<crate::binding::Binding>()
|
||||
{
|
||||
// 属性绑定和事件订阅复用同一种取消令牌,但 Binding 的真实强边字段是 compute。
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<crate::binding::Binding>(connection, "Binding")?
|
||||
.clone();
|
||||
// 返回查询的是操作前连接状态;disconnect 自己最后返回 Unit,不暴露该布尔。
|
||||
let connected = data.compute.is_some();
|
||||
// 取消切断真实强拥有边,外部仍可保留 token,但 token 弱引用本身不保活回调或目标。
|
||||
if matches!(self, Self::Disconnect) {
|
||||
@@ -167,10 +180,12 @@ impl NativeCallable for Method {
|
||||
}
|
||||
connected
|
||||
} else {
|
||||
// 其余合法令牌包装事件 Connection,不用 Binding 的字段布局读取它。
|
||||
let mut data = cx
|
||||
.store()
|
||||
.payload::<Connection>(connection, "Connection")?
|
||||
.clone();
|
||||
// handler=None 就是已断开,保留 Connection 对象本身不代表回调仍可执行。
|
||||
let connected = data.handler.is_some();
|
||||
if matches!(self, Self::Disconnect) {
|
||||
data.handler = None;
|
||||
@@ -179,24 +194,30 @@ impl NativeCallable for Method {
|
||||
connected
|
||||
}
|
||||
} else {
|
||||
// 弱目标已经死亡与主动断开都属于不再连接,查询不因此报过期对象错误。
|
||||
false
|
||||
};
|
||||
if matches!(self, Self::Disconnect) {
|
||||
// API 约定取消返回 Unit,只有 isConnected 返回前面采样到的布尔。
|
||||
Value::Nil
|
||||
} else {
|
||||
Value::Bool(connected)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// 传播标志属于 Event payload,复制后经 replace_payload 写回以保持 store 的写屏障。
|
||||
let mut event = cx.store().payload::<Event>(*owner, "Event")?.clone();
|
||||
if matches!(self, Self::Prevented) {
|
||||
// 只读查询不替换 payload,不制造一次虚假的事件变更。
|
||||
Value::Bool(event.prevented)
|
||||
} else {
|
||||
match self {
|
||||
Self::Stop | Self::StopImmediate => {
|
||||
// Stop 保留当前组的其余回调,Immediate 额外跳过同组后续 Delivery。
|
||||
event.stopped_at = Some(event.group);
|
||||
event.immediate |= matches!(self, Self::StopImmediate);
|
||||
}
|
||||
// 只记录阻止默认,不在本模块额外调用或取消某个 OS 默认动作。
|
||||
Self::Prevent => event.prevented = true,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
@@ -212,6 +233,7 @@ impl NativeCallable for Method {
|
||||
#[derive(Debug)]
|
||||
/// 安装到托管类型上的原生构造调用适配器。
|
||||
pub struct Constructor {
|
||||
// bootstrap 在 Event 类型/签名都建立后补入,VM 据此先检查 Type/kind/字段外壳。
|
||||
pub signature: Option<endor_core::CallSignature>,
|
||||
}
|
||||
impl NativeCallable for Constructor {
|
||||
@@ -224,8 +246,9 @@ impl NativeCallable for Constructor {
|
||||
Some(endor_core::CallArity::range(2, usize::MAX))
|
||||
}
|
||||
|
||||
/// 先验证事件子类字段数量与注解,再创建原生 Event 并填充声明字段,错误不得留下部分实例。
|
||||
/// VM 执行 Event/源子类 NativeTyped 构造器时调用,验证字段前不先分配业务 Event,避免非法字段副作用。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
// definition 是实际请求子类,kind 是唯一原生构造参数,其余后缀对应声明字段。
|
||||
let [Value::Object(definition), Value::Text(kind), values @ ..] = args else {
|
||||
return Err(invalid("Event requires an event kind"));
|
||||
};
|
||||
@@ -236,19 +259,22 @@ impl NativeCallable for Constructor {
|
||||
.fields()
|
||||
.to_vec();
|
||||
if fields.len() != values.len() {
|
||||
// 不用 zip 静默截断少/多实参,完整类型字段数量必须与输入后缀一致。
|
||||
return Err(invalid("incorrect Event field arguments"));
|
||||
}
|
||||
cx.store()
|
||||
.check_class_field_arguments(*definition, values)?;
|
||||
// 数量和类型都检查后才创建真实子类 Event;NativeContext 会清理未输出的临时根。
|
||||
let event = new_event(cx, *definition, kind)?;
|
||||
for (field, value) in fields.iter().zip(values) {
|
||||
// 用普通属性写入口初始化字段,保持对象引用和依赖记录受 VM 统一管理。
|
||||
cx.set_attr(event, &field.name, value.clone())?;
|
||||
}
|
||||
Ok(NativeResult::Return(Value::Object(event)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 建立本次分发拥有的托管 Event,保存目标、输入与传播控制状态。
|
||||
/// Event 构造器、click 和图形/三维指针适配调用,建立尚未分派的带名义身份事件;目标由 dispatch 填写。
|
||||
pub fn new_event(
|
||||
cx: &mut NativeContext<'_>,
|
||||
definition: ObjectRef,
|
||||
@@ -257,11 +283,13 @@ pub fn new_event(
|
||||
if kind.is_empty() || kind.len() > 128 {
|
||||
return Err(invalid("event kind must contain 1..128 UTF-8 bytes"));
|
||||
}
|
||||
// payload 默认标志与普通属性分开:停止/默认阻止在 payload,目标/阶段信息通过托管属性公开。
|
||||
let event = cx.allocate(Event::default())?;
|
||||
cx.attach_type(event, definition)?;
|
||||
cx.set_attr(event, "kind", Value::Text(kind.into()))?;
|
||||
// 新事件尚未递送,目标、出现与 hit 都为空;kind 保留输入种类,phase 初始 none。
|
||||
for name in ["target", "mount", "currentTarget", "currentMount", "hit"] {
|
||||
// 初始化明确的 nil,处理器读取未分派事件时不会因字段缺失而失败。
|
||||
cx.set_attr(event, name, Value::Nil)?;
|
||||
}
|
||||
cx.set_attr(event, "phase", Value::Text("none".into()))?;
|
||||
@@ -269,8 +297,9 @@ pub fn new_event(
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// 带事件类型签名和 owner 的原生方法包装。
|
||||
/// install 挂到 Event/Subscription 类型上的签名包装;实例 receiver 由 VM 方法绑定机制传入。
|
||||
struct TypedMethod {
|
||||
// 无状态操作标签,实际事件/订阅状态都在本次传入 receiver 的托管 payload 中。
|
||||
method: Method,
|
||||
signature: endor_core::CallSignature,
|
||||
}
|
||||
@@ -285,7 +314,7 @@ impl NativeCallable for TypedMethod {
|
||||
}
|
||||
}
|
||||
|
||||
/// 把本模块的类型、方法或能力注册到所属运行时上下文。
|
||||
/// ui_bridge::bootstrap 完成 Event/Subscription/Function 类型建立后调用,为两类对象安装控制与查询方法。
|
||||
pub fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
@@ -307,6 +336,7 @@ pub fn install(
|
||||
] {
|
||||
// isDefaultPrevented/isConnected 返回 Bool 且只读;控制传播和取消方法返回 Unit 并声明 Mutating。
|
||||
let query = matches!(method, Method::Prevented | Method::Connected);
|
||||
// callable 接一个隐式名义 receiver,查询返回 Bool/ReadOnly,修改返回 Unit/Mutating。
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
TypedMethod {
|
||||
@@ -314,10 +344,13 @@ pub fn install(
|
||||
signature: endor_core::CallSignature::exact(
|
||||
vec![endor_core::AnnotationType::Nominal(definition)],
|
||||
if query {
|
||||
// isDefaultPrevented/isConnected 的返回类型是布尔,不把“无连接”写成 nil。
|
||||
endor_core::AnnotationType::Bool
|
||||
} else {
|
||||
// 控制/取消操作没有业务返回值,VM 用 Unit 检查而非任意 Any。
|
||||
endor_core::AnnotationType::Unit
|
||||
},
|
||||
// 同一个标签同时决定调用效果,不能让断开连接冒充只读查询。
|
||||
if query {
|
||||
endor_core::CallEffect::ReadOnly
|
||||
} else {
|
||||
@@ -337,18 +370,27 @@ pub fn install(
|
||||
#[derive(Debug)]
|
||||
/// 本次递送选择的对象方法或显式订阅处理器。
|
||||
enum Handler {
|
||||
// 捕获 Connection 对象而非函数快照,前面回调 disconnect 后本项会重新观察 handler=None。
|
||||
Token(ObjectRef),
|
||||
// onClick 的旧式单处理器是本轮函数快照,不具有独立 Connection 令牌。
|
||||
Legacy(ObjectRef),
|
||||
// onEvent 从实际类型的方法表在轮到本项时解析,以保留继承/源覆盖。
|
||||
ObjectMethod,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 事件传播过程中将要调用的一项处理器及其阶段/目标上下文。
|
||||
struct Delivery {
|
||||
// 本轮事件由 captures 显式保活;payload 中的数值句柄本身不构成 VM 强边。
|
||||
event: ObjectRef,
|
||||
// 当前路径项的业务对象,不一定是最终 target;祖先捕获/冒泡也用相同适配器。
|
||||
owner: ObjectRef,
|
||||
// 该路径项的具体出现,页面上下文无 Mount 时为 None。
|
||||
mount: Option<ObjectRef>,
|
||||
// stopPropagation 的边界编号;目标捕获与非捕获共享组,其他出现/阶段递增。
|
||||
group: usize,
|
||||
// 对外公开的 capture/target/bubble 字符串,与 group 的内部停止规则分别保存。
|
||||
phase: &'static str,
|
||||
// 处理器的解析策略,决定是否需要临时取连接或补 receiver。
|
||||
handler: Handler,
|
||||
}
|
||||
impl NativeCallable for Delivery {
|
||||
@@ -357,13 +399,16 @@ impl NativeCallable for Delivery {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
/// 轮到该处理器时重查传播状态和连接是否仍有效,更新当前阶段/目标,再按真实回调 arity 发出 VM 调用。
|
||||
/// vm_sequence 驱动轮到本项时调用,重查停止/连接状态,再用 Invoke 交给同预算的真实处理器。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
// 不是快照整个传播开始时的标志,前一个回调产生的 stop 必须立刻影响当前项。
|
||||
let mut event = cx.store().payload::<Event>(self.event, "Event")?.clone();
|
||||
// 真正轮到处理器时重新读取传播状态,之前回调的 stop 操作立即影响后续项,无需重建序列。
|
||||
if event.immediate || event.stopped_at.is_some_and(|group| group != self.group) {
|
||||
// 跳过此项仍返回正常 Nil,让驱动继续推进到其他跳过项和最终 Finish 清理。
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
// 函数与参数前缀一起解析:对象协议需 receiver,独立处理器最初没有显式参数。
|
||||
let (function, mut arguments) = match self.handler {
|
||||
// 序列只捕获 Connection,不快照 handler;前面处理器取消它后,这里看到 None 并跳过。
|
||||
Handler::Token(token) => {
|
||||
@@ -372,6 +417,7 @@ impl NativeCallable for Delivery {
|
||||
.payload::<Connection>(token, "Connection")?
|
||||
.handler
|
||||
else {
|
||||
// 已断开连接不再调用旧 handler,即使驱动已经为它分配过 Delivery。
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
};
|
||||
(handler, vec![])
|
||||
@@ -379,9 +425,11 @@ impl NativeCallable for Delivery {
|
||||
Handler::Legacy(function) => (function, vec![]),
|
||||
// 对象协议在执行到该项时解析实际类型的 onEvent;显式 receiver 先放入实参向量。
|
||||
Handler::ObjectMethod => {
|
||||
// 动态源子类的 onEvent 可以不同于基类默认空实现,不能在安装时固定函数。
|
||||
let Some(definition) = cx.store().type_of(self.owner)? else {
|
||||
return Err(invalid("untyped event target"));
|
||||
};
|
||||
// 按类型继承查方法,缺少协议方法是契约错误,不降级忽略对象事件能力。
|
||||
let function = cx
|
||||
.store()
|
||||
.lookup_method(definition, "onEvent")?
|
||||
@@ -406,6 +454,7 @@ impl NativeCallable for Delivery {
|
||||
.call_arity(function)?
|
||||
.is_some_and(|arity| arity.accepts(1))
|
||||
{
|
||||
// 单 Event 回调优先;仅真正不接受一参但接受零参的便捷处理器才不追加事件。
|
||||
arguments.push(Value::Object(self.event));
|
||||
}
|
||||
Ok(NativeResult::Invoke {
|
||||
@@ -423,8 +472,9 @@ impl NativeCallable for Finish {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
/// 正常序列结束时清除活跃派发守卫与当前上下文,保留 target/prevented 并返回实际 Event,允许后续重用。
|
||||
/// vm_sequence 在所有 Delivery 之后调用,清理当前阶段/守卫并返回最终 Event,供调用方读取默认阻止状态。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
// 保留事件最终 prevented 等标志,不用 Event::default 抹掉这一轮处理结果。
|
||||
let mut event = cx.store().payload::<Event>(self.0, "Event")?.clone();
|
||||
// 正常序列结束清递送标记与当前上下文,保留原始 target/mount 和 prevented 供调用方读取。
|
||||
event.dispatch = None;
|
||||
@@ -436,10 +486,8 @@ impl NativeCallable for Finish {
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot the selected occurrence's route and listener order. Disconnection
|
||||
/// before a listener's turn skips it; newly registered listeners wait for the
|
||||
/// next dispatch. A code event without a Mount visits only its target object.
|
||||
/// 快照 Mount 路径和订阅顺序,构造共享预算的 capture/target/bubble 驱动并返回 VM 续调。
|
||||
/// ui_bridge::calls 的 click/dispatch 及指针适配调用,构造本轮路线/处理顺序,再返回 VM 驱动续调。
|
||||
/// 无 Mount 的代码事件只访问 owner,不猜测共享对象位于哪个窗口;新订阅不加入本轮,取消可立即跳过旧项。
|
||||
pub fn dispatch(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
@@ -447,13 +495,16 @@ pub fn dispatch(
|
||||
mount: Option<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<NativeResult, VmError> {
|
||||
// 先检查真实 Event payload,复制是为了稍后重置传播标志并经写屏障写回。
|
||||
let mut event = cx.store().payload::<Event>(event_ref, "Event")?.clone();
|
||||
// 只有 guard 仍存活才禁止重入;此前分发失败但 guard 已释放时,不让旧弱身份永久锁住 Event。
|
||||
if let Some(weak) = event.dispatch
|
||||
&& cx.upgrade(weak)?.is_some()
|
||||
{
|
||||
// 同 Event 不可重入分发;若上轮驱动已因失败释放,弱 guard 失效则允许重新使用。
|
||||
return Err(invalid("Event is already being dispatched"));
|
||||
}
|
||||
// kind 可以是源程序改过的普通属性,所以每次 dispatch 都重新验证实际字符串和长度。
|
||||
let Value::Text(kind) = cx.store().get_attr(event_ref, "kind")? else {
|
||||
return Err(invalid("Event kind must be text"));
|
||||
};
|
||||
@@ -463,21 +514,26 @@ pub fn dispatch(
|
||||
// 路线由目标向外保存。无 Mount 的代码事件只访问目标对象,不猜测共享 Block 属于哪个出现。
|
||||
let mut route = vec![(owner, mount)];
|
||||
if let Some(mount) = mount {
|
||||
// 克隆出现 payload 后沿其 parent/page 弱边构建路径,和 Block.children 的业务组成分开。
|
||||
let target = cx.store().payload::<Mount>(mount, "Mount")?.clone();
|
||||
// 传入 Mount 必须仍挂接且确实展示 owner;同一 Block 的另一个出现不能替代该上下文。
|
||||
if !target.mounted || target.block != owner {
|
||||
return Err(invalid("event context does not belong to this Block"));
|
||||
}
|
||||
// parent 是下一祖先弱身份,目标先放进 seen,防止父链回到自身。
|
||||
let mut parent = target.parent;
|
||||
// 沿弱 parent 链构建本轮路径快照,检查死亡祖先、脱离与环;不通过 Block 业务孩子关系反推祖先。
|
||||
let mut seen = std::collections::HashSet::from([mount]);
|
||||
while let Some(weak) = parent {
|
||||
// NativeContext 跟踪升级根,驱动 captures 将保留真正需要的祖先直到本轮执行结束。
|
||||
let ancestor = cx
|
||||
.upgrade(weak)?
|
||||
.ok_or(invalid("event route has expired"))?;
|
||||
if !seen.insert(ancestor) {
|
||||
// 循环父链不能让宿主构造无限驱动,遇重复身份立即拒绝。
|
||||
return Err(invalid("cyclic event route"));
|
||||
}
|
||||
// 祖先存在还不够,必须仍挂载,不能把历史出现关系当成当前传播路径。
|
||||
let data = cx.store().payload::<Mount>(ancestor, "Mount")?;
|
||||
if !data.mounted {
|
||||
return Err(invalid("event route is detached"));
|
||||
@@ -487,15 +543,17 @@ pub fn dispatch(
|
||||
}
|
||||
// 出现祖先之外再加入 Page 上下文,页面本身无 currentMount;弱页已失效则拒绝该旧路线。
|
||||
if let Some(weak) = target.page {
|
||||
// 页面属于传播最外层语义目标,但没有它自己的内容 Mount,所以 route 中配 None。
|
||||
let page = cx.upgrade(weak)?.ok_or(invalid("event Page has expired"))?;
|
||||
route.push((page, None));
|
||||
}
|
||||
}
|
||||
// 所有递送和 Finish 显式捕获 guard,Event 只弱引用它;驱动完成/失败释放后 guard 自动结束本轮资格。
|
||||
let guard = cx.new_object()?;
|
||||
// 按最终递送顺序存临时 callable,vm_sequence::build 随后让它们成为驱动常量强边。
|
||||
let mut calls = Vec::new();
|
||||
// 每个出现/阶段有自己的停止边界;同业务对象多次出现也不能共用一个 group。
|
||||
let mut group = 0;
|
||||
// Each occurrence is its own propagation group, even for shared Blocks.
|
||||
// 先从最外层向目标递送捕获,再从目标向外递送非捕获;目标两次遍历都标记 phase=target。
|
||||
let traversal = route
|
||||
.iter()
|
||||
@@ -509,15 +567,19 @@ pub fn dispatch(
|
||||
.map(|(index, entry)| (index, entry, false)),
|
||||
);
|
||||
for (index, &(block, current_mount), capture) in traversal {
|
||||
// block 可能是共享转发别名,解析到实际 Data 后读取本轮回调/订阅列表。
|
||||
let (_, data) = block::resolve(cx.store(), block)?;
|
||||
// 此路径项的候选处理顺序,稍后逐项包装成独立 Delivery。
|
||||
let mut handlers = Vec::new();
|
||||
// 本轮先快照符合事件 kind 与 capture 的订阅顺序;回调期间新注册的连接不进入当前分发。
|
||||
for token in &data.subscriptions {
|
||||
// subscriptions 保存的是 Connection 而非用户持有的 Subscription 令牌。
|
||||
let token_data = cx.store().payload::<Connection>(*token, "Connection")?;
|
||||
if token_data.handler.is_some()
|
||||
&& token_data.kind == kind
|
||||
&& token_data.capture == capture
|
||||
{
|
||||
// 这里只快照连接身份,handler 的存活在真正执行 Delivery 时再次读取。
|
||||
handlers.push(Handler::Token(*token));
|
||||
}
|
||||
}
|
||||
@@ -527,22 +589,28 @@ pub fn dispatch(
|
||||
if kind == "click"
|
||||
&& let Some(handler) = data.click
|
||||
{
|
||||
// 旧式 onClick 仅匹配 click 且只在非捕获阶段执行,不变成所有事件通用监听器。
|
||||
handlers.push(Handler::Legacy(handler));
|
||||
}
|
||||
}
|
||||
for handler in handlers {
|
||||
if calls.len() >= MAX_DELIVERIES {
|
||||
// 总量包括所有祖先和阶段,不能让每个节点各用 10000 额度放大一次分发。
|
||||
return Err(invalid("event delivery budget exceeded"));
|
||||
}
|
||||
// 每一项显式保活本轮 Event、guard、目标和可选 Mount/连接;不能仅靠 Rust ObjectRef 值当 GC 根。
|
||||
let mut captures = vec![event_ref, guard, block];
|
||||
if let Some(mount) = current_mount {
|
||||
// captures 保留这一具体出现,不能只保留业务 Block 丢掉几何/祖先上下文。
|
||||
captures.push(mount);
|
||||
}
|
||||
match handler {
|
||||
// Connection 或旧函数必须有真实托管强边,Rust 枚举里的句柄数值不保活它们。
|
||||
Handler::Token(token) | Handler::Legacy(token) => captures.push(token),
|
||||
// 对象方法在轮到时查找,owner 已在 captures,不提前强持某个可能被覆盖的函数。
|
||||
Handler::ObjectMethod => {}
|
||||
}
|
||||
// 分配一个零参步骤;真实用户函数的 receiver/Event 参数由 Delivery::invoke 再决定。
|
||||
let function = cx.allocate(ContextNativeFunction::new(
|
||||
"event delivery",
|
||||
Delivery {
|
||||
@@ -551,10 +619,13 @@ pub fn dispatch(
|
||||
mount: current_mount,
|
||||
group,
|
||||
phase: if index == 0 {
|
||||
// 路线 index=0 始终是最终目标,目标捕获/非捕获都对外显示 target。
|
||||
"target"
|
||||
} else if capture {
|
||||
// 从外层向目标的祖先遍历显示 capture。
|
||||
"capture"
|
||||
} else {
|
||||
// 从目标向外层的祖先遍历显示 bubble。
|
||||
"bubble"
|
||||
},
|
||||
handler,
|
||||
@@ -564,13 +635,12 @@ pub fn dispatch(
|
||||
attach_desktop_type(cx, function, "Function", desktop)?;
|
||||
calls.push(function);
|
||||
}
|
||||
// Capture and bubble at the target are one group: stopPropagation at
|
||||
// target capture still permits other target listeners.
|
||||
// 目标捕获后不递增 group,使 stopPropagation 仍允许目标非捕获处理器;其他路径/阶段则隔离为新组。
|
||||
if index != 0 || !capture {
|
||||
group += 1;
|
||||
}
|
||||
}
|
||||
// Finish 也捕获 guard,保证即使没有任何用户监听器,整次驱动仍维持活跃分发资格到结束。
|
||||
let finish = cx.allocate(ContextNativeFunction::new(
|
||||
"event finish",
|
||||
Finish(event_ref),
|
||||
@@ -578,6 +648,7 @@ pub fn dispatch(
|
||||
))?;
|
||||
// 无论传播是否被停止,Finish 都作为序列最后一项执行,它不受 Delivery 的 stopped 判定影响。
|
||||
calls.push(finish);
|
||||
// 驱动常量池拥有完整顺序,全部处理器共用调用者 VM 的预算,不能逐个 vm.call 重置额度。
|
||||
let driver = crate::vm_sequence::build(cx, calls, "<event dispatch>", desktop)?;
|
||||
event.dispatch = Some(cx.store().downgrade(guard)?);
|
||||
event.group = 0;
|
||||
@@ -592,6 +663,7 @@ pub fn dispatch(
|
||||
"mount",
|
||||
mount.map(Value::Object).unwrap_or(Value::Nil),
|
||||
)?;
|
||||
// 仅委托驱动,不在本 Rust 调用栈递归执行用户回调;VM 后续负责返回最终 Event。
|
||||
Ok(NativeResult::Invoke {
|
||||
function: driver,
|
||||
arguments: vec![],
|
||||
|
||||
+89
-14
@@ -2,7 +2,9 @@
|
||||
//! 连续相机和滚动输入出队时可更新帧版本,但不改变捕获目标和所属 VM;离散点击仍保留严格的过期帧语义。
|
||||
//! 生产端只合并相同目标的相邻绝对指针采样;有序动作是边界。relay 直接进入串行 worker,后台等待确认。
|
||||
//!
|
||||
//! Native input transport. Frame/mount identities and optional logical pointer positions cross to the VM worker.
|
||||
//! shell::app 建立 Client 并发送捕获到的 Input;Client 后台 relay 经 api::RuntimeControl::dispatch_native 交给 worker。
|
||||
//! HTTP 路由也反序列化同一 Input 并调用 validate,但不会走原生 relay 的连续输入版本刷新。
|
||||
//! 这里只合并同目标相邻 pointermove 的绝对采样;滚动/相机的增量逐条保留,不能用最后一个覆盖累计移动。
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
@@ -15,9 +17,11 @@ use winit::event_loop::EventLoopProxy;
|
||||
#[serde(deny_unknown_fields)]
|
||||
/// 拖放目标窗口、目标布局版本和插入位置,源标签身份由外层 Input 保存。
|
||||
pub struct TabDrop {
|
||||
// 目标原生资源 ID,不是 GUI 标签索引或 Page 托管句柄。
|
||||
pub window: u64,
|
||||
// 事件所依据的已发布布局版本,由执行端校验过期帧;原生连续手势有单独刷新逻辑。
|
||||
pub layout_version: u64,
|
||||
// 移除前标签序列中的插入缝位置;同窗口向后移动时 dispatch_tab 会做一次下标修正。
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
@@ -26,40 +30,48 @@ pub struct TabDrop {
|
||||
/// 原生或 HTTP 输入的纯数据报文;身份与坐标必须同时通过 worker 和能力校验。
|
||||
pub struct Input {
|
||||
#[serde(default = "default_window")]
|
||||
// 省略仅为兼容旧 HTTP 报文,显式 0 永远无效;原生客户端始终记录真实捕获窗口。
|
||||
pub window: u64,
|
||||
// 产生事件的运行时会话;重载后即使窗口或 Mount 数值相同也不能沿用旧事件。
|
||||
pub session: u64,
|
||||
// 产生输入时所见帧的几何版本;同会话内也不能把旧坐标直接用到任意新几何。
|
||||
pub layout_version: u64,
|
||||
// 捕获的具体出现身份;页面级相机事件使用零,独立视口相机事件要求非零。
|
||||
pub mount: u64,
|
||||
// 分派标签:click/scroll/相机/标签/工具等语义由 validate 与 UiBridge::dispatch 分工检查。
|
||||
pub kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
// 事件位置或缩放锚点;click 与 press_point 配对,具体坐标语义由事件 kind 决定。
|
||||
pub point: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
// 高层 click 的按下点,与 point 的释放点一起让 source_hit 确认同一个出现被点击。
|
||||
pub press_point: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
// 平移/滚动增量,或缩放的 [倍率,0];不能无差别接受任意事件携带该字段。
|
||||
pub delta: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
// 仅 tab-drop 可携带,源端身份仍由外层 window/layout_version/mount 指定。
|
||||
pub tab_drop: Option<TabDrop>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
// 拆标签的新窗口位置是屏幕坐标,与页面局部 point 分开;允许多屏环境负坐标。
|
||||
pub screen_position: Option<[i32; 2]>,
|
||||
}
|
||||
|
||||
/// 返回默认主窗口身份,供省略窗口字段的兼容输入使用。
|
||||
/// serde 在旧报文缺 window 时调用,返回主资源 ID;不会把显式零值改写成合法窗口。
|
||||
fn default_window() -> u64 {
|
||||
crate::window::MAIN_WINDOW
|
||||
}
|
||||
|
||||
impl Input {
|
||||
/// 按事件种类核对可携带字段、坐标范围和 Mount 是否为零;不替代执行端的会话/能力校验。
|
||||
/// API 路由和 UiBridge 分派前调用,验证报文结构;不读取 VM/发布文档,不能证明 session/Mount 仍有效。
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
if self.window == 0 {
|
||||
// 资源身份零保留为非法值,避免丢失 window 的错误报文误投当前窗口。
|
||||
return Err("window identity must be nonzero");
|
||||
}
|
||||
// 标签跨窗口放置仅接受目标元信息;禁止同时夹带指针/滚动/屏幕位置,避免混用两套操作。
|
||||
if self.kind == "tab-drop" {
|
||||
// 缺目标就没有可解释的插入窗口/位置,不从 point 或其他字段推断落点。
|
||||
let Some(target) = &self.tab_drop else {
|
||||
return Err("tab-drop requires target metadata");
|
||||
};
|
||||
@@ -70,12 +82,14 @@ impl Input {
|
||||
|| self.delta.is_some()
|
||||
|| self.screen_position.is_some()
|
||||
{
|
||||
// 拖放用纯目标元数据,不接受与滚动/点击/拆窗定位混合的多义信封。
|
||||
return Err("invalid tab drop metadata");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// 非 tab-drop 不得携带目标窗口信息,即使其他字段恰好合法也拒绝。
|
||||
if self.tab_drop.is_some() {
|
||||
// 非拖放报文即使 kind 本身合法,也不能夹带被另一层意外消费的重排指令。
|
||||
return Err("tab_drop is only accepted for tab-drop");
|
||||
}
|
||||
// 屏幕位置只服务 tab-detach 的新窗口定位,允许负数以支持左侧/上方显示器,但限制绝对范围。
|
||||
@@ -101,10 +115,12 @@ impl Input {
|
||||
let viewport = self.kind.starts_with("viewport-") || self.kind.starts_with("scene-");
|
||||
// 所有相机操作必须带有限、有界的增量;point 在非缩放操作可省略。
|
||||
let valid_delta = self.delta.is_some_and(|delta| {
|
||||
// 两个增量分量都要有限,不能只验证 zoom 会使用的第一分量而遗漏非法第二分量。
|
||||
delta
|
||||
.iter()
|
||||
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
|
||||
});
|
||||
// 非缩放手势可无锚点;存在时仍限制坐标,局部视口可负以支持捕获拖出边界。
|
||||
let valid_point = self.point.is_none_or(|point| {
|
||||
point
|
||||
.iter()
|
||||
@@ -120,6 +136,7 @@ impl Input {
|
||||
|| self.press_point.is_some()
|
||||
|| self.screen_position.is_some()
|
||||
{
|
||||
// 页面相机 mount 必为零,局部视口必非零,防止把同一增量套到两种目标空间。
|
||||
return Err("invalid page camera input");
|
||||
}
|
||||
// 缩放必须给锚点并使用正倍率 0.1..=10;第二分量必须为零,不把缩放与二维平移混合编码。
|
||||
@@ -129,6 +146,7 @@ impl Input {
|
||||
.delta
|
||||
.is_none_or(|delta| !(0.1..=10.0).contains(&delta[0]) || delta[1] != 0.0))
|
||||
{
|
||||
// 这里仅检查倍率/锚点格式;锚点是否仍在实际视口内由 page_input 结合几何检查。
|
||||
return Err("page-zoom requires an anchor and positive scale factor");
|
||||
}
|
||||
return Ok(());
|
||||
@@ -144,6 +162,7 @@ impl Input {
|
||||
.iter()
|
||||
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0) =>
|
||||
{
|
||||
// 滚动只接点+增量,具体可消费方向、裁剪和嵌套链仍在桥接/滚动模块决定。
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("scroll requires point and finite delta, with no press_point"),
|
||||
@@ -153,6 +172,7 @@ impl Input {
|
||||
self.kind.as_str(),
|
||||
"pointermove" | "pointerdown" | "pointerup" | "pointerleave" | "pointercancel"
|
||||
) {
|
||||
// 原始 pointer 报文要求一个明确目标和绝对位置,不允许夹带 click 的成对按下点或增量。
|
||||
return if self.mount != 0
|
||||
&& self.press_point.is_none()
|
||||
&& self.delta.is_none()
|
||||
@@ -161,17 +181,21 @@ impl Input {
|
||||
.point
|
||||
.is_some_and(|p| p.iter().all(|v| v.is_finite() && v.abs() <= 1_000_000.))
|
||||
{
|
||||
// 格式合法后还需检查挂载和 pointer_events;此处不把任意 Mount 变成可交互目标。
|
||||
Ok(())
|
||||
} else {
|
||||
// 错误字段或越界坐标统一拒绝,不替发送方删字段修复成另一个事件。
|
||||
Err("pointer event requires finite point and target")
|
||||
};
|
||||
}
|
||||
if self.delta.is_some() {
|
||||
// 到这里相机与滚动路径都已返回,其余离散操作不得再消费 delta。
|
||||
return Err("delta is only accepted for scroll input");
|
||||
}
|
||||
// 无指针坐标的离散事件可通过此结构校验;若有指针信息,必须是 click 的按下/释放成对坐标。
|
||||
// 这里不做完整 kind 白名单授权,具体操作仍由后续分发层检查。
|
||||
match (self.point, self.press_point) {
|
||||
// 无坐标的 focus/标签等离散动作交后续 kind 白名单与对象能力检查。
|
||||
(None, None) => Ok(()),
|
||||
(Some(point), Some(press))
|
||||
if self.kind == "click"
|
||||
@@ -180,6 +204,7 @@ impl Input {
|
||||
.chain(press)
|
||||
.all(|value| value.is_finite() && value.abs() <= 1_000_000.0) =>
|
||||
{
|
||||
// click 必须同时带两个有效端点,避免只在释放点命中就触发按下在别处的按钮。
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("pointer click requires finite press/release coordinates"),
|
||||
@@ -187,29 +212,37 @@ impl Input {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded producer-side coalescing preserves action barriers while the relay
|
||||
/// waits for a VM acknowledgement. Motion cannot fill the queue by itself.
|
||||
/// Client 生产端与 relay 共用的有界状态;只保留尚未提交 worker 的 Input,不包含 VM 对象。
|
||||
struct Queue {
|
||||
// 相邻同目标绝对移动可在队尾覆盖;其他动作是序列屏障,不能越过它们合并采样。
|
||||
items: VecDeque<Input>,
|
||||
// 统计活 Client,而非 Arc 总强引用;后台 relay 自己持 Arc 也不能阻止最后生产者关闭队列。
|
||||
senders: usize,
|
||||
// 最后生产者释放后置位,receive 醒来退出,不再尝试分派已无人负责的旧输入。
|
||||
closed: bool,
|
||||
}
|
||||
/// 队列锁与条件变量的共享入口,Client 只短暂加锁,后台等待不占用 GUI 事件循环。
|
||||
struct Inbox {
|
||||
queue: Mutex<Queue>,
|
||||
ready: Condvar,
|
||||
}
|
||||
/// shell::app 持有的原生输入发送句柄;后台 relay 负责串行等待 worker 确认,GUI 不等待 VM 执行。
|
||||
pub struct Client(Arc<Inbox>);
|
||||
impl Clone for Client {
|
||||
/// GUI 多个生产者复制句柄时同步增加逻辑生产者数,保证 Drop 不把仍在用的队列提前关闭。
|
||||
fn clone(&self) -> Self {
|
||||
self.0.queue.lock().unwrap().senders += 1;
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
/// 原生生产者离开时减少计数;最后一个关闭、清空并唤醒 relay,不因 relay 自己的 Arc 而挂住线程。
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut q) = self.0.queue.lock() {
|
||||
// 锁内计数/关闭与 send/enqueue 互斥,关闭后不留下新的待发报文。
|
||||
q.senders -= 1;
|
||||
if q.senders == 0 {
|
||||
// 退出丢弃尚未发送输入,不用旧会话的残留交互拖延窗口关闭。
|
||||
q.closed = true;
|
||||
q.items.clear();
|
||||
self.0.ready.notify_all();
|
||||
@@ -217,37 +250,44 @@ impl Drop for Client {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Client::send 在锁内调用,最多保留 64 条,队尾同目标 pointermove 可覆盖成最新绝对采样。
|
||||
fn enqueue(queue: &mut VecDeque<Input>, input: Input) -> bool {
|
||||
if input.kind == "pointermove"
|
||||
&& let Some(last) = queue.back_mut()
|
||||
&& last.kind == "pointermove"
|
||||
&& (last.window, last.session, last.mount) == (input.window, input.session, input.mount)
|
||||
{
|
||||
// 只覆盖紧邻且同窗/同会话/同 Mount 的移动;按下/抬起或换目标都成为不可跨越的屏障。
|
||||
*last = input;
|
||||
return true;
|
||||
}
|
||||
if queue.len() >= 64 {
|
||||
// 容量检查在可合并路径之后,因此单一连续移动不会因同类采样填满队列。
|
||||
return false;
|
||||
}
|
||||
queue.push_back(input);
|
||||
true
|
||||
}
|
||||
impl Inbox {
|
||||
/// relay 的接收循环调用,条件变量等待新事件或关闭,唤醒后再次检查以处理虚假唤醒。
|
||||
fn receive(&self) -> Option<Input> {
|
||||
// 锁损坏视为关闭,不尝试从不可靠队列恢复一条可能重复的输入。
|
||||
let mut q = self.queue.lock().ok()?;
|
||||
while q.items.is_empty() && !q.closed {
|
||||
// wait 原子放锁并等待;GUI 生产者可入队,通知后重新取得同一状态锁。
|
||||
q = self.ready.wait(q).ok()?;
|
||||
}
|
||||
if q.closed { None } else { q.items.pop_front() }
|
||||
}
|
||||
}
|
||||
impl Client {
|
||||
/// 建立容量 64 的发送队列和单个后台中继线程,事件交给原生 VM worker;线程创建失败则返回错误。
|
||||
/// shell::app 初始化时调用,创建有界 Inbox 与单个 relay;RuntimeControl 直达 worker,不绕 HTTP 回环。
|
||||
pub fn new(
|
||||
proxy: EventLoopProxy<crate::app::AppEvent>,
|
||||
namespace: Arc<RwLock<crate::document::NamespaceState>>,
|
||||
control: crate::api::RuntimeControl,
|
||||
) -> anyhow::Result<Self> {
|
||||
// 初始生产者就是返回的 Client;receiver 的 Arc 不计入 senders,避免接收线程自保活。
|
||||
let inbox = Arc::new(Inbox {
|
||||
queue: Mutex::new(Queue {
|
||||
items: VecDeque::new(),
|
||||
@@ -256,19 +296,24 @@ impl Client {
|
||||
}),
|
||||
ready: Condvar::new(),
|
||||
});
|
||||
// move 闭包拥有接收 Arc 与发布状态只读入口,线程不取得 VM 所有权。
|
||||
let receiver = inbox.clone();
|
||||
thread::Builder::new()
|
||||
.name("tessera-native-events".into())
|
||||
.spawn(move || {
|
||||
while let Some(mut input) = receiver.receive() {
|
||||
// 每条输入出队时再看最新权威发布帧,连续采样不沿用排队前已经过时的布局版本。
|
||||
if let Ok(current) = namespace.read() {
|
||||
if !refresh_continuous_input(&mut input, ¤t) {
|
||||
// 目标消失/换会话时丢弃,不能把旧手势重定向到同位置的新出现。
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// 共享发布状态不可读时不分派缺乏校验的输入,等待下一条正常事件。
|
||||
continue;
|
||||
}
|
||||
if let Err(error) = control.dispatch_native(input) {
|
||||
// worker 回执错误通过原生事件循环呈现诊断,不直接操作窗口或执行源回调。
|
||||
let _ = proxy.send_event(crate::app::AppEvent::RuntimeFailed {
|
||||
message: error.to_string(),
|
||||
});
|
||||
@@ -277,26 +322,27 @@ impl Client {
|
||||
})?;
|
||||
Ok(Self(inbox))
|
||||
}
|
||||
/// 非阻塞尝试入队;成功仅代表队列接收,满队列或后台线程关闭返回 false。
|
||||
/// shell::app 捕获输入时调用,非阻塞入队/合并后通知 relay;true 不表示 VM 已执行或帧已发布。
|
||||
pub fn send(&self, input: Input) -> bool {
|
||||
// 锁内仅处理纯数据队列,不把 worker 回执等待放在 GUI 路径。
|
||||
let Ok(mut q) = self.0.queue.lock() else {
|
||||
return false;
|
||||
};
|
||||
if q.closed {
|
||||
return false;
|
||||
}
|
||||
// enqueue 的覆盖合并也算接收成功,relay 会读取最终最新样本。
|
||||
let queued = enqueue(&mut q.items, input);
|
||||
if queued {
|
||||
// 单 relay 只需唤醒一个等待者;关闭路径用 notify_all 保证退出不遗留等待。
|
||||
self.0.ready.notify_one();
|
||||
}
|
||||
queued
|
||||
}
|
||||
}
|
||||
|
||||
// Native gestures retain the captured Mount across publications. Refresh only
|
||||
// the version at dequeue, never session, window or target. HTTP callers and
|
||||
// discrete actions still receive strict stale-frame rejection.
|
||||
/// 连续手势出队时只更新有效目标的帧版本;保留原 session、窗口和 Mount,离散事件不自动重试。
|
||||
/// Client relay 出队时调用,仅给指定类别的原生输入追随同目标新帧版本;不修改捕获目标和会话身份。
|
||||
/// HTTP 调用不走这个入口;click/标签等其余动作直接保留旧版本,后面仍会严格拒绝过期帧。
|
||||
pub(crate) fn refresh_continuous_input(
|
||||
input: &mut Input,
|
||||
current: &crate::document::NamespaceState,
|
||||
@@ -315,6 +361,7 @@ pub(crate) fn refresh_continuous_input(
|
||||
| "pointerleave"
|
||||
| "pointercancel"
|
||||
) {
|
||||
// 未列入可追随类别的输入既不丢弃也不改写,在执行端按原几何版本验证。
|
||||
return true;
|
||||
}
|
||||
// 选取事件原窗口的权威帧;窗口已经消失时丢弃,不能把手势改投主窗口。
|
||||
@@ -328,6 +375,7 @@ pub(crate) fn refresh_continuous_input(
|
||||
.map(|document| &document.frame)
|
||||
};
|
||||
let Some(frame) = frame else {
|
||||
// 原窗口不再有权威帧,不能改选 current/main 去继续应用相机或指针动作。
|
||||
return false;
|
||||
};
|
||||
// 必须仍属同一运行时会话、帧无故障且原捕获 Mount 具备对应能力,才可更新布局版本。
|
||||
@@ -337,16 +385,21 @@ pub(crate) fn refresh_continuous_input(
|
||||
|| !frame.mounts.iter().any(|mount| {
|
||||
mount.id == input.mount
|
||||
&& if input.kind.starts_with("viewport-") {
|
||||
// 独立二维相机只要求原 Mount 仍为 CanvasViewport。
|
||||
mount.canvas_viewport
|
||||
} else if input.kind.starts_with("scene-") {
|
||||
// 3D 还需相机控制器,禁用控制器后旧手势不能继续改模型。
|
||||
mount.scene3d_viewport && mount.camera_controls
|
||||
} else if input.kind.starts_with("pointer") {
|
||||
// 原始指针必须仍有相应订阅能力,外框存在不足以证明可以继续接收。
|
||||
mount.pointer_events
|
||||
} else {
|
||||
// 剩余唯一可追随类别是 scroll,需保持滚动能力。
|
||||
mount.scroll.is_some()
|
||||
}
|
||||
})
|
||||
{
|
||||
// 保留会话/目标边界,任一权威身份或能力不匹配都不能仅更新版本后继续发送。
|
||||
return false;
|
||||
}
|
||||
// 只追随新版本,不改 session/window/mount,不重选目标;每条排队增量仍独立发送。
|
||||
@@ -358,12 +411,14 @@ pub(crate) fn refresh_continuous_input(
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
/// 重复消费旧帧捕获的连续 pan,允许刷新到当前版本且保留每条 delta;离散 click 不改版本,会话/目标替换拒绝手势。
|
||||
/// Rust 测试框架调用:用真实持久 VM 反复分派旧帧 pan,验证版本追随不丢增量也不越过会话/目标边界。
|
||||
fn queued_native_pan_keeps_each_delta_and_rejects_replaced_targets() {
|
||||
// 建立可观测 camera.x 的最小场景,输入目标从实际发布帧选出,不硬编码出现 ID。
|
||||
let (mut session, document) = crate::endor_host::ReplSession::load(
|
||||
"view=CanvasViewport(200,100,Scene2D(RectBlock(20,20,0)))\npage=Page()\npage.render(view)",
|
||||
"app.main", 1, 912,
|
||||
).unwrap();
|
||||
// 找真实 CanvasViewport 出现,确保 refresh_continuous_input 的能力判定有实际帧数据。
|
||||
let mount = document
|
||||
.frame
|
||||
.mounts
|
||||
@@ -371,6 +426,7 @@ mod tests {
|
||||
.find(|mount| mount.canvas_viewport)
|
||||
.unwrap()
|
||||
.id;
|
||||
// 捕获初始版本的固定输入,后面每轮都克隆它,模拟输入生产速度超过刷新速度的队列。
|
||||
let original = Input {
|
||||
window: 1,
|
||||
session: 912,
|
||||
@@ -383,6 +439,7 @@ mod tests {
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
};
|
||||
// current 表示 relay 每次出队时能读到的最新共享文档,不直接借用 VM 当前内部草稿。
|
||||
let mut current = crate::document::NamespaceState {
|
||||
runtime_session: 912,
|
||||
document,
|
||||
@@ -390,6 +447,7 @@ mod tests {
|
||||
};
|
||||
// 反复从旧帧原始手势克隆输入,验证每条增量都被刷新版本并累计,12×3 应得到 36。
|
||||
for _ in 0..12 {
|
||||
// 每轮都从最旧版本重建输入,只有 refresh 的行为能让后续 11 条继续有效。
|
||||
let mut queued = original.clone();
|
||||
assert!(refresh_continuous_input(&mut queued, ¤t));
|
||||
current.document = session.dispatch(&queued).unwrap().document.unwrap();
|
||||
@@ -399,26 +457,33 @@ mod tests {
|
||||
"36"
|
||||
);
|
||||
// 离散点击不得自动刷新版本;随后验证会话替换和目标移除都会拒绝连续手势。
|
||||
// 同一信封改成离散 click,应只通过“不改写”快路,不享受连续手势的版本追随。
|
||||
let mut click = original.clone();
|
||||
click.kind = "click".into();
|
||||
assert!(refresh_continuous_input(&mut click, ¤t));
|
||||
assert_eq!(click.layout_version, original.layout_version);
|
||||
// 模拟整程序替换:数字窗口/Mount 即使相同,旧 runtime_session 仍必须使手势失效。
|
||||
current.runtime_session = 913;
|
||||
assert!(!refresh_continuous_input(&mut original.clone(), ¤t));
|
||||
current.runtime_session = 912;
|
||||
// 恢复原会话但删掉目标,证明能力/目标检查不只依赖 session 相等。
|
||||
current.document.frame.mounts.clear();
|
||||
assert!(!refresh_continuous_input(&mut original.clone(), ¤t));
|
||||
}
|
||||
#[test]
|
||||
/// 对 tab-drop 元数据、位置上限与 tab-detach 桌面坐标逐项改坏,检查辅助字段只在对应事件类型和预算内合法。
|
||||
/// Rust 测试框架调用,逐项破坏合法拖放报文,验证种类与辅助字段绑定、标签上限及多屏坐标范围。
|
||||
fn drop_metadata_is_scoped_to_its_event_kind_and_bounded() {
|
||||
// 从完整合法 JSON 起步,后面的每次修改只触发一种目标限制,避免无关字段同时掩盖失败原因。
|
||||
let mut input:Input=serde_json::from_str(r#"{"window":1,"session":1,"layout_version":2,"mount":3,"kind":"tab-drop","tab_drop":{"window":2,"layout_version":4,"index":1}}"#).unwrap();
|
||||
assert!(input.validate().is_ok());
|
||||
// tab_drop 元数据不可由普通 click 夹带,否则某层可能意外消费成跨窗口移动。
|
||||
input.kind = "click".into();
|
||||
assert!(input.validate().is_err());
|
||||
input.kind = "tab-drop".into();
|
||||
// 数字 65 超过 MAX_PAGES=64 的结构上界,不需要真实 VM 窗口即可拒绝。
|
||||
input.tab_drop.as_mut().unwrap().index = 65;
|
||||
assert!(input.validate().is_err());
|
||||
// 拆窗使用另一种辅助元数据,先去掉 tab_drop,再验证负屏幕坐标合法但极值不合法。
|
||||
input.kind = "tab-detach".into();
|
||||
input.tab_drop = None;
|
||||
input.screen_position = Some([-400, 200]);
|
||||
@@ -428,13 +493,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 旧 JSON 未带 window 时默认主窗口以保持兼容;显式 window=0 仍是非法资源,不能当成默认值。
|
||||
/// Rust 测试框架调用,区分 serde 的缺字段默认与明确传零,保证兼容不掩盖非法资源身份。
|
||||
fn legacy_event_window_defaults_but_zero_is_never_a_resource() {
|
||||
// 故意省略 window,检查反序列化确实调用 default_window,而非字段初始零值。
|
||||
let mut input: Input =
|
||||
serde_json::from_str(r#"{"session":1,"layout_version":2,"mount":3,"kind":"focus"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(input.window, crate::window::MAIN_WINDOW);
|
||||
assert!(input.validate().is_ok());
|
||||
// 显式修改为零必须拒绝,不能再次触发 default_window 纠正成主窗口。
|
||||
input.window = 0;
|
||||
assert!(input.validate().is_err());
|
||||
}
|
||||
@@ -444,28 +511,36 @@ mod tests {
|
||||
mod coalescing_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
/// Rust 测试框架调用,验证生产端高频绝对移动可合并,动作顺序和跨窗口目标切换仍保持屏障。
|
||||
fn producer_side_motion_coalescing_keeps_action_and_target_boundaries() {
|
||||
// 默认主窗口、固定 session/Mount 的原始绝对位置采样,供后续复制成不同动作。
|
||||
let template: Input = serde_json::from_str(
|
||||
r#"{"session":1,"layout_version":1,"mount":2,"kind":"pointermove","point":[0,0]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
// 直接测试 enqueue 的纯队列规则,不启动 relay 或 VM,避免异步消费影响可观察顺序。
|
||||
let mut q = VecDeque::new();
|
||||
for i in 0..1000 {
|
||||
// 即使远超容量 64,相邻同目标 pointermove 也应持续覆盖唯一队尾项。
|
||||
let mut sample = template.clone();
|
||||
sample.point = Some([i as f32, 0.]);
|
||||
assert!(enqueue(&mut q, sample));
|
||||
}
|
||||
assert_eq!(q.len(), 1);
|
||||
assert_eq!(q[0].point.unwrap()[0], 999.);
|
||||
// down 是离散动作屏障,不能被下一次移动覆盖或跨过。
|
||||
let mut down = template.clone();
|
||||
down.kind = "pointerdown".into();
|
||||
enqueue(&mut q, down);
|
||||
// 新移动只能形成 down 后的一项,不能合并回 down 前的旧移动。
|
||||
let mut moved = template.clone();
|
||||
moved.point = Some([1200., 0.]);
|
||||
enqueue(&mut q, moved);
|
||||
// up 再次切开动作序列,保证处理器观察先按下、后移动、再抬起。
|
||||
let mut up = template.clone();
|
||||
up.kind = "pointerup".into();
|
||||
enqueue(&mut q, up);
|
||||
// 相同 session/Mount 但换窗口也必须单独成项,目标比较不能漏掉 window。
|
||||
let mut other = template;
|
||||
other.window = 2;
|
||||
enqueue(&mut q, other);
|
||||
|
||||
+52
-14
@@ -2,7 +2,9 @@
|
||||
//! Lease 由托管任务拥有,释放会撤销交付资格并取消可取消的后台工作;已经完成的结果还要由 VM worker 检查归属后才能交付。
|
||||
//! 并发、队列、读取字节数、超时和 URL 协议均有边界,避免 provider 绕过运行时资源限制。
|
||||
//!
|
||||
//! Background providers carry plain data and weak task identities, never a VM.
|
||||
//! runtime::tasks 为 readText/fetchText 创建 Task 时调用 Provider::submit,并把返回 Lease 放进 Task payload。
|
||||
//! Scheduler 轮询 Provider::take_ready 后在 owning VM 中核验弱身份、owner/key 与取消状态,再调用源回调。
|
||||
//! 所有 Provider 共用一个全进程有界线程池;每个运行时仍有自己的结果邮箱与租约额度,不互读 Task 堆。
|
||||
use endor_core::{VmError, WeakObjectRef};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -22,13 +24,17 @@ use std::{
|
||||
const MAX_TEXT: usize = 1024 * 1024;
|
||||
// 每个运行时的租约额度,独立于全进程 4 个执行线程和 64 项工作队列。
|
||||
const MAX_ACTIVE: usize = 16;
|
||||
// 全进程实际执行 OS I/O 的线程数;排队不等于已占一个执行线程。
|
||||
const WORKERS: usize = 4;
|
||||
// 工作队列全局上限,try_send 失败直接反馈给提交方,不让 VM 阻塞等空位。
|
||||
const QUEUE: usize = 64;
|
||||
// 成功/失败都只传字符串;不能把 VmError 内部可能关联的托管值或 VM 句柄送入后台线程。
|
||||
type Completion = Result<String, String>;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
/// provider 共享的就绪结果与并发计数;内容只有纯数据和弱任务身份。
|
||||
struct Shared {
|
||||
// worker 写入、take_ready 排空,Lease::drop 也会移除本任务的晚到/未取结果。
|
||||
ready: Mutex<HashMap<WeakObjectRef, Completion>>,
|
||||
// 统计当前活租约而非正在执行的 OS 操作;完成结果被取走前,租约仍可能占用名额。
|
||||
active: AtomicUsize,
|
||||
@@ -36,16 +42,18 @@ struct Shared {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// 某个运行时拥有的后台 provider 能力,负责提交和取走完成结果。
|
||||
pub struct Provider {
|
||||
// Arc 可供后台 Job 访问邮箱,不代表 Job 拥有 Task 或能延长交付租约。
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
#[derive(Debug, Default)]
|
||||
/// 后台工作取消标记与可取消子进程,不拥有托管 VM。
|
||||
struct Control {
|
||||
// Release/Acquire 传播取消资格;最终写邮箱时还需在 ready 锁内再次检查。
|
||||
cancelled: AtomicBool,
|
||||
process: Mutex<Option<Child>>,
|
||||
}
|
||||
impl Control {
|
||||
/// 撤销当前操作的后续交付资格,并执行对应取消清理。
|
||||
/// Lease 析构调用,可在 VM/租约线程执行;只撤资格/kill,不在调用线程 wait 进程退出。
|
||||
fn cancel(&self) {
|
||||
// 先撤销结果交付资格,再尝试终止当前子进程;文件读取无法用此标记中断,只能丢弃晚到结果。
|
||||
self.cancelled.store(true, Ordering::Release);
|
||||
@@ -61,15 +69,19 @@ impl Control {
|
||||
#[derive(Debug)]
|
||||
/// 后台工作种类及其纯文本参数,源调用的类型检查在提交前完成。
|
||||
pub enum Request {
|
||||
// 本地路径已在任务创建时做类型/长度校验,worker 再检查实际文件类型和大小。
|
||||
ReadText(String),
|
||||
// URL 会由 fetch_text 再验证 HTTP(S)/authority,传输不用 shell 解释。
|
||||
FetchText(String),
|
||||
}
|
||||
/// Only Task payloads own this lease. Provider threads hold plain control data.
|
||||
#[derive(Debug)]
|
||||
/// 仅托管 Task 拥有的交付租约;释放它会取消后台资格并清理晚到结果。
|
||||
pub struct Lease {
|
||||
// 归还名额与移除结果所需共享状态;不持有任务本体,避免后台根反向保活源程序。
|
||||
shared: Arc<Shared>,
|
||||
// 带代际的弱身份用于邮箱键,Task 死亡后不能让旧结果命中复用槽位的新任务。
|
||||
task: WeakObjectRef,
|
||||
// 取消后台进程/晚到交付的纯原生控制对象,后台 Job 只共享它而不共享 Lease。
|
||||
control: Arc<Control>,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
@@ -78,6 +90,7 @@ impl Drop for Lease {
|
||||
// 租约释放立即取消交付资格;后台 OS 读取即使稍后结束,也不能再次唤醒旧 Task。
|
||||
self.control.cancel();
|
||||
if let Ok(mut ready) = self.shared.ready.lock() {
|
||||
// 删除已到邮箱的结果;worker 同锁复查 cancelled,所以取消之后也不能重新留下结果。
|
||||
ready.remove(&self.task);
|
||||
}
|
||||
// Lease 包在 Arc 中,只有最后一个拥有者释放才析构并归还一次额度;Job 不持有 Lease。
|
||||
@@ -86,13 +99,17 @@ impl Drop for Lease {
|
||||
}
|
||||
/// 线程池队列中的纯数据工作,关联弱任务身份、控制和共享完成表。
|
||||
struct Job {
|
||||
// 操作种类及参数只含拥有字符串,不借用 VM 对象属性或源参数切片。
|
||||
request: Request,
|
||||
// 只用于交付结果地址,后台从不尝试升级弱引用。
|
||||
task: WeakObjectRef,
|
||||
// 共享取消状态/进程槽,让租约销毁可终止传输;Job 不持 Lease,因此不阻止取消。
|
||||
control: Arc<Control>,
|
||||
// 结果写入对应 Provider 的 mailbox,不把不同运行时结果混入一个全局表。
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
impl Provider {
|
||||
/// 检查并发额度并取得任务 Lease,再把纯数据工作放入有界线程池队列。
|
||||
/// tasks 的 I/O 创建路径调用,原子预占额度、建立 RAII Lease 并非阻塞入队,返回交付资格而非执行结果。
|
||||
pub fn submit(
|
||||
&self,
|
||||
task: WeakObjectRef,
|
||||
@@ -104,6 +121,7 @@ impl Provider {
|
||||
self.shared
|
||||
.active
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |active| {
|
||||
// replacing 只放宽一次替换的瞬时名额,不为普通提交永久提升每运行时上限。
|
||||
(active < MAX_ACTIVE + usize::from(replacing)).then_some(active + 1)
|
||||
})
|
||||
.map_err(|_| VmError::ExecutionLimit("16 I/O tasks per runtime"))?;
|
||||
@@ -113,6 +131,7 @@ impl Provider {
|
||||
task,
|
||||
control: Arc::new(Control::default()),
|
||||
});
|
||||
// 池初始化也可能失败;lease 已建立,任何后续 ? 都会归还预占额度。
|
||||
let sender = pool().map_err(|_| VmError::InvalidArgument("I/O provider unavailable"))?;
|
||||
// 非阻塞入队,不让调用 VM 等待后台吞吐;Job 只带参数、弱任务身份和原生取消/结果状态。
|
||||
sender
|
||||
@@ -125,7 +144,7 @@ impl Provider {
|
||||
.map_err(|_| VmError::ExecutionLimit("I/O provider queue full or unavailable"))?;
|
||||
Ok(lease)
|
||||
}
|
||||
/// 一次取走当前邮箱内全部 (弱任务身份, 纯文本结果),实际托管交付仍由 VM worker 校验后执行。
|
||||
/// Scheduler::poll 在 VM worker 调用,排空此 Provider 的已就绪纯数据,不在邮箱锁中执行源回调。
|
||||
// 一次 drain 所有已就绪结果;移走纯数据不代表任务仍可交付,VM worker 还需检查弱身份和归属。
|
||||
pub fn take_ready(&self) -> Result<Vec<(WeakObjectRef, Completion)>, VmError> {
|
||||
Ok(self
|
||||
@@ -137,14 +156,17 @@ impl Provider {
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
/// 懒初始化共享工作线程和有界任务队列;初始化失败反馈给提交方。
|
||||
/// Provider::submit 调用,懒初始化全进程线程池;返回借用的 SyncSender,不为每个 VM 新建 I/O 线程。
|
||||
fn pool() -> Result<&'static SyncSender<Job>, &'static str> {
|
||||
// 全进程只初始化一次,初始化失败也会记住失败结果;后续 submit 返回 unavailable,不反复创建线程。
|
||||
static POOL: OnceLock<Result<SyncSender<Job>, String>> = OnceLock::new();
|
||||
POOL.get_or_init(|| {
|
||||
// 队列只承载 Job;容量限制排队任务,不代替 Provider 自己的 MAX_ACTIVE 租约预算。
|
||||
let (sender, receiver) = sync_channel::<Job>(QUEUE);
|
||||
// std Receiver 不可 Clone,短锁共享接收端;拿到一个 Job 后放锁再并行执行 I/O。
|
||||
let receiver = Arc::new(Mutex::new(receiver));
|
||||
for index in 0..WORKERS {
|
||||
// 每线程持接收端 Arc,不持任何 Provider/Task 的租约,空闲时阻塞 recv 而非轮询。
|
||||
let receiver = receiver.clone();
|
||||
thread::Builder::new()
|
||||
.name(format!("tessera-io-{index}"))
|
||||
@@ -153,15 +175,18 @@ fn pool() -> Result<&'static SyncSender<Job>, &'static str> {
|
||||
// std mpsc Receiver 通过 Mutex 共享;锁只覆盖取任务,实际 I/O 在离开该 match 后并行执行。
|
||||
let job = match receiver.lock() {
|
||||
Ok(receiver) => receiver.recv(),
|
||||
// 接收锁损坏时终止该线程,不在不可靠队列状态上继续读任务。
|
||||
Err(_) => break,
|
||||
};
|
||||
let Ok(job) = job else {
|
||||
// 所有 sender 已断开就退出;这不是一个可重试的临时“队列为空”。
|
||||
break;
|
||||
};
|
||||
// 执行前先跳过已取消队列项,避免启动无用文件读取或 curl。
|
||||
if job.control.cancelled.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
// 只进行原生文件/HTTP 操作,失败也编码成纯文本 Completion,留给 VM 线程交付。
|
||||
let result = match &job.request {
|
||||
Request::ReadText(path) => read_text(path),
|
||||
Request::FetchText(url) => fetch_text(url, &job.control),
|
||||
@@ -170,6 +195,7 @@ fn pool() -> Result<&'static SyncSender<Job>, &'static str> {
|
||||
if let Ok(mut ready) = job.shared.ready.lock()
|
||||
&& !job.control.cancelled.load(Ordering::Acquire)
|
||||
{
|
||||
// 与 Lease::drop 用同一 ready 锁封住取消/插入竞争,晚到结果不能重新激活旧 Task。
|
||||
ready.insert(job.task, result);
|
||||
}
|
||||
}
|
||||
@@ -181,7 +207,7 @@ fn pool() -> Result<&'static SyncSender<Job>, &'static str> {
|
||||
.as_ref()
|
||||
.map_err(|_| "I/O provider unavailable")
|
||||
}
|
||||
/// 读取受字节上限限制的 UTF-8 文件内容,错误作为任务结果交付。
|
||||
/// pool 的 ReadText 分支在后台调用,返回受字节预算限制的 UTF-8 文本或可交付错误字符串。
|
||||
fn read_text(path: &str) -> Completion {
|
||||
// 先按路径检查普通文件和已知长度,及早拒绝目录/超大源;实际打开后还会复核文件类型。
|
||||
let metadata = std::fs::metadata(path).map_err(|error| error.to_string())?;
|
||||
@@ -191,6 +217,7 @@ fn read_text(path: &str) -> Completion {
|
||||
if metadata.len() > MAX_TEXT as u64 {
|
||||
return Err("text source exceeds 1 MiB".into());
|
||||
}
|
||||
// 路径检查与打开之间可能变化,所以打开后再次检查句柄实际指向的对象类型。
|
||||
let file = File::open(path).map_err(|error| error.to_string())?;
|
||||
if !file
|
||||
.metadata()
|
||||
@@ -199,6 +226,7 @@ fn read_text(path: &str) -> Completion {
|
||||
{
|
||||
return Err("text source must be a regular file".into());
|
||||
}
|
||||
// 原始字节最后才严格转 UTF-8,不用有损替换悄悄改写用户文件内容。
|
||||
let mut bytes = Vec::new();
|
||||
// 再用流读取硬上限检测增长中的文件:多读一个字节即可判断超限,不能只依赖之前 metadata 长度。
|
||||
file.take(MAX_TEXT as u64 + 1)
|
||||
@@ -210,15 +238,15 @@ fn read_text(path: &str) -> Completion {
|
||||
String::from_utf8(bytes).map_err(|_| "text source must be UTF-8".into())
|
||||
}
|
||||
|
||||
/// No shell interpretation, curlrc, URL globbing, or non-HTTP redirects.
|
||||
/// Authentication/custom headers are deliberately outside this text GET API.
|
||||
/// 检查网络请求的 URL 协议、长度与凭据等约束,拒绝不受支持的输入。
|
||||
/// tasks 创建 fetchText 与 fetch_text 真正传输前都会调用,拒绝错误协议、过长 URL、控制字符和 userinfo。
|
||||
/// 这是受限文本 GET 接口的基本格式检查,不负责完整 URL 规范化,也不声明网络地址访问授权。
|
||||
pub fn valid_url(url: &str) -> bool {
|
||||
// 控制字符必须在写 curl config 前拒绝,否则换行等可能破坏单个 url 配置项边界。
|
||||
if url.len() > 8192 || url.chars().any(char::is_control) {
|
||||
return false;
|
||||
}
|
||||
let Some((scheme, rest)) = url.split_once("://") else {
|
||||
// 只接受有显式 scheme 的 URL,不让 curl 猜协议或把路径当作另一类资源地址。
|
||||
return false;
|
||||
};
|
||||
if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
|
||||
@@ -230,8 +258,7 @@ pub fn valid_url(url: &str) -> bool {
|
||||
!authority.is_empty() && !authority.contains('@') && !authority.chars().any(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Created only on an I/O worker. All early exits kill and reap the child.
|
||||
/// 子进程作用域收尾保护,避免取消/失败路径遗留未回收进程。
|
||||
/// fetch_text 仅在 I/O worker 上创建的清理守卫;任何提前返回都取走、kill/wait 尚未回收的子进程。
|
||||
struct Reaper<'a>(&'a Control);
|
||||
impl Drop for Reaper<'_> {
|
||||
/// 取走残留 curl 子进程后尝试 kill/wait,保证失败或取消路径也回收进程,且不持控制锁等待。
|
||||
@@ -244,15 +271,18 @@ impl Drop for Reaper<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// 在取消、超时、协议和大小限制下取得 HTTP 文本;不把网络执行放在 VM 线程。
|
||||
/// pool 的 FetchText 分支调用,用系统 curl 做有界 HTTP GET;所有等待与进程回收都发生在后台线程。
|
||||
fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
if !valid_url(url) {
|
||||
return Err("invalid HTTP(S) URL".into());
|
||||
}
|
||||
#[cfg(unix)]
|
||||
// Unix 固定系统路径,不从用户 PATH 选择任意同名可执行文件。
|
||||
let executable = "/usr/bin/curl";
|
||||
#[cfg(not(unix))]
|
||||
// 非 Unix 使用系统环境可解析的 curl.exe,找不到时反馈明确的传输不可用错误。
|
||||
let executable = "curl.exe";
|
||||
// 参数数组直接交给进程 API,URL 另外经 stdin 配置传入,全程不经 shell 拼接。
|
||||
let mut child = Command::new(executable)
|
||||
// --disable 放首项关闭 curlrc,--globoff 禁用 URL 展开,首次请求与重定向均限制 HTTP(S)。
|
||||
// 限制重定向数、连接/总超时和下载大小;--compressed 后仍会用下面字节读取上限限制解压文本。
|
||||
@@ -287,26 +317,30 @@ fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
.spawn()
|
||||
.map_err(|_| "HTTP transport unavailable: system curl is required".to_owned())?;
|
||||
// 取走管道后把 Child 放入共享 Control,取消线程可随时 kill;Reaper 覆盖其后的所有提前返回。
|
||||
// 管道配置是上方 spawn 的内部前提,take 后分别归配置写入和正文读取负责。
|
||||
let mut input = child.stdin.take().expect("piped stdin");
|
||||
// 取走 stdout 后 Child 仍可放入共享进程槽供取消线程 kill。
|
||||
let output = child.stdout.take().expect("piped stdout");
|
||||
match control.process.lock() {
|
||||
Ok(mut slot) => *slot = Some(child),
|
||||
Err(_) => {
|
||||
// 尚未安装 Reaper 且不能存入共享槽,当前线程必须亲自 kill/wait 清理已启动子进程。
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("HTTP process lock poisoned".into());
|
||||
}
|
||||
}
|
||||
// 从这里起即使写配置/读正文/解析状态失败,也会通过 Drop 回收进程而不留下僵尸。
|
||||
let _reaper = Reaper(control);
|
||||
if control.cancelled.load(Ordering::Acquire) {
|
||||
return Err("request cancelled".into());
|
||||
}
|
||||
// URL stays out of process arguments. Reject controls before config escaping.
|
||||
// URL 经 curl 配置的引号/反斜杠转义后走 stdin,避免出现在进程参数;这里不经过 shell。
|
||||
let escaped = url.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
writeln!(input, "url = \"{escaped}\"").map_err(|_| "HTTP transport input failed".to_owned())?;
|
||||
// 关闭 stdin 表示配置结束,否则 curl 可能继续等待输入,无法开始/完成请求。
|
||||
drop(input);
|
||||
// stdout 同时含正文与 curl --write-out 状态尾,预算须为尾部保留四字节。
|
||||
let mut bytes = Vec::new();
|
||||
output
|
||||
// 预留结尾换行和三位状态码共 4 字节,再额外读 1 字节探测正文超限。
|
||||
@@ -318,10 +352,12 @@ fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
}
|
||||
// 读完输出后用 try_wait 检查退出;等待间隔先释放 process 锁,让其他线程仍可取消进程。
|
||||
let status = loop {
|
||||
// 短暂持锁查询 child 状态;睡眠前释放槽锁,让 Lease::drop 仍可及时 kill。
|
||||
let mut slot = control
|
||||
.process
|
||||
.lock()
|
||||
.map_err(|_| "HTTP process lock poisoned".to_owned())?;
|
||||
// 槽内 Child 在本请求结束前应存在;缺项是状态错误,不继续对另一进程等待。
|
||||
let child = slot.as_mut().ok_or("HTTP process missing")?;
|
||||
if let Some(status) = child
|
||||
.try_wait()
|
||||
@@ -335,6 +371,7 @@ fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
thread::sleep(Duration::from_millis(2));
|
||||
};
|
||||
if control.cancelled.load(Ordering::Acquire) {
|
||||
// 完成传输并不自动取得交付资格,取消优先于刚读到的正常 HTTP 返回值。
|
||||
return Err("request cancelled".into());
|
||||
}
|
||||
// --write-out 的末尾四字节应是换行加三位状态码;checked_sub 处理空/短输出,不直接倒数切片。
|
||||
@@ -351,6 +388,7 @@ fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
return Err(format!("HTTP {code}"));
|
||||
}
|
||||
if !status.success() {
|
||||
// 区分 curl 的超时/大小错误,其余保留退出码供诊断;信号终止没有普通退出码。
|
||||
return Err(match status.code() {
|
||||
Some(28) => "HTTP request timed out".into(),
|
||||
Some(63) => "HTTP text exceeds 1 MiB".into(),
|
||||
|
||||
+43
-12
@@ -1,7 +1,10 @@
|
||||
//! 构造共享 VM 调用序列与同帧循环驱动的字节码。
|
||||
//! 用托管函数串联步骤,避免为每个布局节点反复创建独立解释器调用;重复驱动会保留同一个执行帧和预算域。
|
||||
//!
|
||||
//! Validated call sequences share the current VM budget and explicit frames.
|
||||
//! mount::synchronize 与 event_dispatch::dispatch 用 build 串起生命周期/事件回调。
|
||||
//! source_layout/source_paint 用 repeat_call 循环推进出现位置,并用 collect_and_continue 收集单次源调用结果。
|
||||
//! 本模块只生成驱动字节码和托管函数,不在 Rust 中自行解释语句,也不替调用方重置 VM 预算。
|
||||
//! 原生调用返回 Invoke 后,VM 在既有帧循环中执行驱动,因此可挂起工作仍有明确的 owning VM。
|
||||
use endor_core::{
|
||||
CodeLayout, EndorCode, EndorCodeObject, Instruction, NativeContext, ObjectRef, Opcode, Value,
|
||||
VmError,
|
||||
@@ -10,6 +13,7 @@ use endor_core::{
|
||||
/// 将零参数调用列表编成一个托管驱动,按输入顺序执行,返回最后一次调用的值。
|
||||
/// 空列表返回 Nil。所有调用都在调用者的 VM 预算内运行,避免宿主逐个调用时重置预算。
|
||||
/// name 用于诊断位置;desktop 用来给生成函数挂接桌面 Function 类型。
|
||||
/// 调用者是 Mount 生命周期同步和事件路由;返回值是驱动函数身份,不是已经执行完的最后结果。
|
||||
pub fn build(
|
||||
cx: &mut NativeContext<'_>,
|
||||
calls: Vec<ObjectRef>,
|
||||
@@ -18,13 +22,17 @@ pub fn build(
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 每个函数放入常量池。LoadConst/PushNull/Call 组成零参数调用,
|
||||
// 中间结果由 PopTop 丢弃;最后结果留在栈顶交给 ReturnValue。
|
||||
// 每个中间调用至多四条指令,额外空间覆盖空序列和 ReturnValue;只是预留容量,不是指令预算。
|
||||
let mut instructions = Vec::with_capacity(calls.len() * 4 + 2);
|
||||
// 常量池强持有每个 callable,驱动存活期间不依赖调用方的 Rust Vec 保活。
|
||||
let mut constants: Vec<Value> = calls.into_iter().map(Value::Object).collect();
|
||||
for index in 0..constants.len() {
|
||||
// LoadConst 放函数,PushNull 建立 VM Call 所需前缀,Call 0 执行无显式实参的回调。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32));
|
||||
instructions.push(Instruction::simple(Opcode::PushNull));
|
||||
instructions.push(Instruction::new(Opcode::Call, 0));
|
||||
if index + 1 != constants.len() {
|
||||
// 只丢中间结果,避免把最后一个结果也弹掉而让 ReturnValue 面对空栈。
|
||||
instructions.push(Instruction::simple(Opcode::PopTop));
|
||||
}
|
||||
}
|
||||
@@ -34,18 +42,21 @@ pub fn build(
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
}
|
||||
instructions.push(Instruction::simple(Opcode::ReturnValue));
|
||||
// 编码阶段校验字节码布局,诊断位置使用宿主 name 而不是伪造用户源码行列。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, "<tessera>", 1);
|
||||
// NativeContext 暂持代码根,输出函数会通过托管边继续拥有代码与常量。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 驱动只读取常量,无需共享用户字典,空私有 globals 不污染 REPL 或主模块。
|
||||
let globals = cx.new_dict()?;
|
||||
// 函数作为本次原生调用的输出被提升,其余临时拥有根由 NativeContext 退出时释放。
|
||||
let driver = cx.new_function(name, code, globals)?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, driver, "Function", desktop)?;
|
||||
Ok(driver)
|
||||
}
|
||||
|
||||
/// A fixed-size driver. Each callback returns whether another occurrence is
|
||||
/// needed; delegated source calls and all iterations share this VM budget.
|
||||
/// 构造重复调用同一托管函数的驱动,保持共享参数与引用生命周期。
|
||||
/// source_layout/source_paint 安装一轮出现遍历时调用,生成固定大小的重复驱动,不按节点数展开字节码。
|
||||
/// callback 每次返回 Bool,false 退出;同帧回跳让所有出现和委托源函数共用当前 VM 的执行预算。
|
||||
pub fn repeat_call(
|
||||
cx: &mut NativeContext<'_>,
|
||||
callback: ObjectRef,
|
||||
@@ -60,6 +71,7 @@ pub fn repeat_call(
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
];
|
||||
repeat_while(&mut instructions)?;
|
||||
// 条件已由 PopJumpIfFalse 消费;退出时重新装 Nil,不能把最后条件冒充业务返回值。
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
@@ -73,9 +85,8 @@ pub fn repeat_call(
|
||||
)
|
||||
}
|
||||
|
||||
/// Prepare only the current occurrence, collect its result, then continue the
|
||||
/// outer driver. The helper frame and its managed captures die before the next.
|
||||
/// 将一步调用结果收集到驱动状态,再安排下一步调用。
|
||||
/// source_layout/source_paint 的推进回调调用,为当前出现生成“调用源方法→collector 收结果→返回 true”的助手。
|
||||
/// 每次只捕获当前源函数/实参,不预先为全部节点建立助手帧;外层重复驱动再决定下一次出现。
|
||||
pub fn collect_and_continue(
|
||||
cx: &mut NativeContext<'_>,
|
||||
collector: ObjectRef,
|
||||
@@ -86,10 +97,13 @@ pub fn collect_and_continue(
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 常量布局固定为 collector、function、各实参、true。
|
||||
// 先把 collector 的调用前缀压栈,再执行 function,使其返回值直接成为 collector 的唯一实参。
|
||||
// count 同时确定 Call 的显式参数数和 true 常量的池位置,不能把 collector 的一参计入它。
|
||||
let count = arguments.len();
|
||||
// 先保存两个 callable,再追加业务实参;这份强边关系使源调用挂起期间输入仍可达。
|
||||
let mut constants = vec![Value::Object(collector), Value::Object(function)];
|
||||
constants.extend(arguments);
|
||||
constants.push(Value::Bool(true));
|
||||
// 先压 collector 的调用前缀,再压 function 的调用前缀;内部返回值自然成为外部单一实参。
|
||||
let mut instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
@@ -97,6 +111,7 @@ pub fn collect_and_continue(
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
];
|
||||
for index in 0..count {
|
||||
// 参数常量从 2 开始,0/1 已被 collector/function 占用,保持源方法原始实参顺序。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32 + 2));
|
||||
}
|
||||
// 收集器返回值不参与外层调度;丢弃后返回 true,通知重复驱动继续取下一项。
|
||||
@@ -110,7 +125,7 @@ pub fn collect_and_continue(
|
||||
driver(cx, instructions, constants, name, desktop)
|
||||
}
|
||||
|
||||
/// 建立承载整个步骤序列的托管函数,使续体可以在同一个 VM 帧中恢复。
|
||||
/// repeat_call/collect_and_continue 的共同分配助手,把已组装指令与常量变成有宿主 Function 类型的 callable。
|
||||
fn driver(
|
||||
cx: &mut NativeContext<'_>,
|
||||
instructions: Vec<Instruction>,
|
||||
@@ -118,34 +133,42 @@ fn driver(
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 编码常量池与指令后带上宿主诊断位置;字节码有效性由 Aster 的代码构造接口检查。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, "<tessera>", 1);
|
||||
// NativeContext 跟踪临时代码根;函数的 trace 边持有代码,不能只靠 Rust ObjectRef 数值保活。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 生成驱动不查用户名字,私有 globals 隔离它的空命名环境。
|
||||
let globals = cx.new_dict()?;
|
||||
// 返回函数根由原生输出机制提升,代码和 globals 的临时根在域结束后可安全清理。
|
||||
let function = cx.new_function(name, code, globals)?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, function, "Function", desktop)?;
|
||||
Ok(function)
|
||||
}
|
||||
|
||||
/// Consume the condition on the stack: true repeats this same frame from zero,
|
||||
/// false falls through. Operand widths include EXTENDED_ARG code units.
|
||||
/// 构造由继续条件决定是否再执行一轮的同帧循环。
|
||||
/// repeat_call 和本模块测试调用,在现有指令尾部追加消费 Bool 条件的分支与回跳。
|
||||
/// true 回到本驱动偏移零,false 跳过回跳指令;不新建调用帧,因此不会用递归栈模拟循环。
|
||||
pub fn repeat_while(instructions: &mut Vec<Instruction>) -> Result<(), VmError> {
|
||||
// 跳转单位是编码后的双字节 code unit,不是 Instruction 数量。
|
||||
// 大操作数会生成 EXTENDED_ARG,因此必须编码后计算实际长度。
|
||||
let body = Instruction::encode_all(instructions)?.len() / 2;
|
||||
// 先用最短零操作数估计回跳宽度,下面迭代直到最终操作数与编码宽度自洽。
|
||||
let mut back = Instruction::new(Opcode::JumpBackward, 0);
|
||||
// 回跳距离包含自身宽度;而距离变大又可能扩大自身编码宽度。
|
||||
// 迭代到宽度/距离一致后,false 跳过回跳指令,true 回到整个驱动的起点。
|
||||
loop {
|
||||
// units 是当前回跳指令实际占用的 code unit,可能因 EXTENDED_ARG 大于一。
|
||||
let units = Instruction::encode_all(&[back])?.len() / 2;
|
||||
// 距离覆盖原 body、一个条件分支和回跳自身;目标为开头,不是仅回到上一个 Call。
|
||||
let distance = u32::try_from(body + 1 + units)
|
||||
.map_err(|_| VmError::ExecutionLimit("layout bytecode"))?;
|
||||
if back.argument == distance {
|
||||
// 已收敛时 false 跳过 units 个单元,true 落到 JumpBackward 回到开头。
|
||||
instructions.push(Instruction::new(Opcode::PopJumpIfFalse, units as u32));
|
||||
instructions.push(back);
|
||||
return Ok(());
|
||||
}
|
||||
// 更新操作数后再次编码量宽度;不能只计算一次,跨 255 等边界可能新增 EXTENDED_ARG。
|
||||
back.argument = distance;
|
||||
}
|
||||
}
|
||||
@@ -155,11 +178,12 @@ mod tests {
|
||||
use super::*;
|
||||
use endor_core::{ExecutionLimits, Vm};
|
||||
#[test]
|
||||
/// 生成超过单字节跳距的循环,false 条件正常返回,true 条件只耗尽指令预算而非一帧预算;释放后对象数归零。
|
||||
/// Rust 测试框架调用,构造大于单字节跳距的循环,分别验证退出、指令预算及无泄漏清理。
|
||||
fn repeated_bytecode_handles_extended_operands_and_keeps_one_frame() {
|
||||
// 300 个 Nop 强制跨越单字节跳转距离:false 应正常退出;true 应耗尽指令预算,
|
||||
// 而非耗尽帧预算,从而验证循环确实复用同一个执行帧。
|
||||
for condition in [false, true] {
|
||||
// Nop 扩大 body 编码长度,与实际布局节点数量无关,直接覆盖回跳扩展操作数的边界。
|
||||
let mut instructions = vec![Instruction::simple(Opcode::Nop); 300];
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
repeat_while(&mut instructions).unwrap();
|
||||
@@ -167,15 +191,20 @@ mod tests {
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
// 条件从常量池读取,false 分支跳过回跳后装入 Nil 并正常返回。
|
||||
let code = EndorCode::from_instructions(
|
||||
&instructions,
|
||||
vec![Value::Bool(condition), Value::Nil],
|
||||
CodeLayout::default(),
|
||||
)
|
||||
.unwrap();
|
||||
// 每种条件独立 VM,统计回收时不受另一轮遗留对象影响。
|
||||
let mut vm = Vm::new().unwrap();
|
||||
// 将纯代码值注册到 VM,执行结束后显式释放此拥有根。
|
||||
let code = vm.new_code(code).unwrap();
|
||||
// 空全局字典满足执行接口,不引入额外用户对象。
|
||||
let globals = vm.new_dict().unwrap();
|
||||
// 故意只允许一帧:如果实现递归重复而非同帧跳转,会得到错误的帧数耗尽。
|
||||
let result = vm.execute_with_limits(
|
||||
code,
|
||||
globals,
|
||||
@@ -185,11 +214,13 @@ mod tests {
|
||||
},
|
||||
);
|
||||
if condition {
|
||||
// true 永不自然退出,应耗尽 instructions 而非 frames,证明循环复用了同一帧。
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(VmError::ExecutionLimit("instructions"))
|
||||
));
|
||||
} else {
|
||||
// false 只走一次 body 然后返回 Nil,证明分支跳过长度包含完整扩展回跳指令。
|
||||
assert_eq!(result.unwrap(), Value::Nil);
|
||||
}
|
||||
vm.release(code).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user