merge: resolve manuscript conflicts with latest main comments

This commit is contained in:
2026-11-12 11:11:00 +08:00
123 changed files with 2699 additions and 253 deletions
+36 -2
View File
@@ -34,6 +34,7 @@ use crate::{
endor_host,
};
// 只监听 IPv4 回环固定端口,接口用于本进程原生输入和本机 agent,不是对外网络服务器。
pub const API_ADDRESS: &str = "127.0.0.1:4737";
const MAX_CODE_SIZE: u64 = endor_host::MAX_SOURCE_BYTES as u64;
type Notify = Arc<dyn Fn() + Send + Sync>;
@@ -87,12 +88,14 @@ impl RuntimeControl {
/// 只发出一次退出请求,唤醒 worker 执行清理,并通过完成句柄通知原生循环。
pub fn request_shutdown(&self) -> bool {
// 原子标志合并重复退出请求;已请求直接返回 true,不在 GUI 线程重复排队清理。
if self.requested.swap(true, Ordering::AcqRel) {
return true;
}
if self.sender.try_send(()).is_ok() {
true
} else {
// 控制队列不可用时回滚请求标志,允许调用方识别失败并再次尝试,而非永远卡在假退出状态。
self.requested.store(false, Ordering::Release);
false
}
@@ -106,6 +109,7 @@ impl RuntimeControl {
let (lock, ready) = &*self.completion;
let result = lock.lock().ok()?;
let (result, _) = ready
// 条件变量处理虚假唤醒,直到完成槽非空或超时;返回 None 也可能来自锁中毒,不能当作清理成功。
.wait_timeout_while(result, timeout, |result| result.is_none())
.ok()?;
result.clone()
@@ -138,11 +142,12 @@ struct BuildRequest {
submission: u64,
}
/// 建立本模块的执行/服务上下文,并把后续推进交给返回的句柄或驱动。
/// 绑定回环 API,启动请求接收与单 VM worker,返回活动日志及一次性退出控制句柄。
pub fn start(
namespace: Arc<RwLock<NamespaceState>>,
proxy: EventLoopProxy<AppEvent>,
) -> Result<(Activity, RuntimeControl)> {
// 退出控制仅需一个消息槽,正常执行请求另走容量8队列,避免工作排满后无法通知关闭。
let (sender, receiver) = sync_channel(1);
let control = RuntimeControl {
sender,
@@ -156,6 +161,7 @@ pub fn start(
control: control.clone(),
proxy: proxy.clone(),
};
// 绑定失败在启动阶段反馈,不能假装本机 API 可用;后台通知仅发送 GUI 事件,不直接画窗口。
let server = Server::http(API_ADDRESS)
.map_err(|error| anyhow::anyhow!(error))
.with_context(|| format!("bind Tessera API to {API_ADDRESS}"))?;
@@ -203,6 +209,7 @@ fn start_server_observed(
shutdown: Option<Shutdown>,
native_port: Option<Arc<OnceLock<SyncSender<BuildRequest>>>>,
) -> Result<thread::JoinHandle<()>> {
// HTTP 接收与 VM 执行分离,最多8个排队请求;源代码只在单个 endor-worker 中操作 VM。
let (sender, receiver) = sync_channel::<BuildRequest>(8);
if let Some(native_port) = native_port {
native_port
@@ -218,11 +225,13 @@ fn start_server_observed(
.name("tessera-endor-worker".into())
.spawn(move || {
let mut worker = Worker::default();
// 分片请求跨循环保留原 HTTP 请求和继续句柄;同一时刻只推进一个有未完成 VM 执行的输入。
let mut pending: Option<(BuildRequest, PendingRequest)> = None;
loop {
if let Some(shutdown) = &shutdown
&& shutdown.receiver.try_recv().is_ok()
{
// 退出优先于下一量子:先撤去待响应请求,再由 shutdown_runtime 清理 VM 续体与生命周期资源。
if let Some((job, input)) = pending.take() {
drop(input);
let _ = job
@@ -230,12 +239,14 @@ fn start_server_observed(
.respond(error_response(StatusCode(503), "application is exiting"));
}
let outcome = worker.shutdown_runtime();
// 排队请求全部明确回应503,不能留着客户端无期限等待已经停止的执行线程。
while let Ok(job) = receiver.try_recv() {
let _ = job
.request
.respond(error_response(StatusCode(503), "application is exiting"));
}
if let Ok(mut current) = worker_namespace.write() {
// 撤销所有帧的会话/焦点与原生命令,让 GUI 不再把旧资源当成仍可执行的活域。
current.runtime_session = 0;
current.window_commands.clear();
current.document.frame.session = 0;
@@ -249,6 +260,7 @@ fn start_server_observed(
let (lock, ready) = &*shutdown.control.completion;
if let Ok(mut result) = lock.lock() {
*result = Some(outcome.clone());
// 先在锁内保存清理结果再唤醒等待者,同时用 AppEvent 通知原生事件循环退出,两条路径复用同一 outcome。
ready.notify_all();
}
let _ = shutdown.proxy.send_event(AppEvent::ShutdownComplete {
@@ -256,6 +268,7 @@ fn start_server_observed(
});
break;
}
// 分片只让出线程,不并行执行后续输入;当前请求完成才回应并处理下一队列项。
if let Some((job, input)) = pending.take() {
match worker.resume_request(&job, input, &worker_namespace, &worker_notify) {
RequestProgress::Pending(input) => {
@@ -271,6 +284,7 @@ fn start_server_observed(
}
continue;
}
// 空闲输入边界先推进视口刷新与任务,待执行刷新/协作任务时零等待,否则最多100ms检查一次。
worker.refresh_viewport(&worker_namespace, &worker_notify);
let wait = if worker.repl.as_ref().is_some_and(|(_, runtime)| {
runtime.has_pending_refresh() || runtime.has_cooperative_tasks()
@@ -306,6 +320,7 @@ fn start_server_observed(
&& current.runtime_session != runtime.id
})
}) {
// 当前持久域同时失去 submission 和 runtime_session 归属时退役;不能仅因源码请求排队就误删仍权威的旧域。
worker.repl = None;
}
if wait.is_zero() {
@@ -323,6 +338,7 @@ fn start_server_observed(
if exiting
.as_ref()
.is_some_and(|flag| flag.load(Ordering::Acquire))
// 退出后拒绝写入/执行路由,GET 与 OPTIONS 仍可读取最近发布值或探测接口。
&& !matches!(request.method(), Method::Get | Method::Options)
{
let _ =
@@ -378,8 +394,9 @@ struct ObservedRequest {
notify: Notify,
}
impl ObservedRequest {
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
/// 从请求提取允许观察的头部与显示来源,创建活动记录并通知工具界面。
fn new(inner: Request, activity: Activity, notify: Notify) -> Self {
// 活动观察只保留 Content-Type/Length;X-Tessera-Origin 仅判来源标签,不把任意认证头复制进工具日志。
let headers = inner
.headers()
.iter()
@@ -387,6 +404,7 @@ impl ObservedRequest {
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
// console 标记只是显示来源,不提供权限,也不改变 VM 执行语义。
let origin = if inner
.headers()
.iter()
@@ -421,7 +439,9 @@ impl ObservedRequest {
let status = response.status_code();
let headers = response.headers().to_vec();
let length = response.data_length();
// 响应正文本已在内存 Cursor,记录预览后用原 status/headers/reader/length 重建响应,不消费正文内容。
let reader = response.into_reader();
// 记录的是已构造响应,即使后面 socket 发送失败也已结束活动记录,不能据此声称客户端成功接收。
self.activity.lock().unwrap().finish(
self.id,
status.0,
@@ -462,6 +482,7 @@ fn handle(
) {
let request = ObservedRequest::new(request, activity.clone(), observer_notify.clone());
let method = request.method().clone();
// 路由匹配去掉查询串,namespace 从固定路径提取;不把 query 当作命名空间或源代码。
let path = request
.url()
.split('?')
@@ -472,6 +493,7 @@ fn handle(
let evaluation = namespace_from_route(&path, "/evaluate");
let repl = namespace_from_route(&path, "/repl");
let event = namespace_from_route(&path, "/events");
// PUT/code 完整替换,POST 在 events/repl/evaluate 中分类,DELETE/repl 是持久会话重置;其他交给资源读取/清空路径。
let route = if method == Method::Put {
namespace_from_path(&path).map(|name| (name, RequestKind::Code))
} else if method == Method::Post {
@@ -524,6 +546,7 @@ fn code_request(
);
}
// GET 返回最近成功发布的 source 而非正在排队的输入,并通过头部暴露 revision/session/window/layout 及逻辑视口。
if method == Method::Get {
let mut response = text(
StatusCode(200),
@@ -578,6 +601,7 @@ fn code_request(
);
return response;
}
// 释放读锁后才申请写锁,避免同一线程持读锁升级为写锁死锁;修改结束也先解锁再发送 GUI 通知。
drop(current);
match method {
@@ -620,6 +644,7 @@ fn submit(
return;
}
};
// 读取成功后才保存受限活动正文预览;超长或非法 UTF-8 请求不会进入执行队列。
request.record_body(&source);
let Ok(mut current) = namespace.write() else {
let _ = request.respond(error_response(
@@ -632,6 +657,7 @@ fn submit(
let _ = request.respond(error_response(StatusCode(404), "namespace is not active"));
return;
}
// 仅完整 Code 请求分配新 submission,事件/REPL/表达式继承当前身份,保留共享域输入顺序。
let submission = match if kind == RequestKind::Code {
current.next_submission()
} else {
@@ -651,6 +677,7 @@ fn submit(
namespace: addressed.into(),
submission,
};
// 持 namespace 写锁完成入队和接受身份更新;worker 提交使用同一锁,保证接受与发布之间没有竞态窗口。
match sender.try_send(job) {
// A rejected queue entry never invalidates accepted work. The worker
// uses this same lock when committing, so publication is atomic.
@@ -659,6 +686,7 @@ fn submit(
current.submission = submission;
}
}
// 队列拒绝时不推进 submission,所以已经接受的旧工作不会因为本次失败请求而失去发布资格。
Err(TrySendError::Full(job)) => {
let _ = job
.request
@@ -684,6 +712,7 @@ fn superseded(submission: u64) -> Response<std::io::Cursor<Vec<u8>>> {
/// 从固定路由格式提取命名空间,避免把不匹配的路径当作代码资源。
fn namespace_from_route<'a>(path: &'a str, suffix: &str) -> Option<&'a str> {
// 同时检查前后缀且命名空间非空、无额外斜杠;不做模糊路径前缀匹配。
path.strip_prefix("/v1/namespaces/")?
.strip_suffix(suffix)
.filter(|namespace| !namespace.is_empty() && !namespace.contains('/'))
@@ -701,6 +730,8 @@ fn read_code(request: &mut Request) -> Result<String> {
{
anyhow::bail!("code exceeds the 1 MiB limit");
}
// 已知 Content-Length 先预拒绝,再在流上最多读上限+1;防止缺失/不实长度绕过容量限制。
// read_to_string 要求 UTF-8,不用有损替换改变用户源码。
let mut code = String::new();
request
.as_reader()
@@ -717,6 +748,7 @@ fn read_code(request: &mut Request) -> Result<String> {
fn compile_error(error: anyhow::Error) -> Response<std::io::Cursor<Vec<u8>>> {
let mut diagnostic =
serde_json::json!({ "severity": "error", "message": format!("{error:#}") });
// 有 SourceDiagnostic 才附行/列和半开字节范围;其他运行时错误仍保留完整错误链消息,不编造源码位置。
if let Some(source) = error.downcast_ref::<frontend::SourceDiagnostic>() {
diagnostic["line"] = source.location.line.into();
diagnostic["column"] = source.location.column.into();
@@ -756,6 +788,7 @@ fn markdown(status: StatusCode, value: String) -> Response<std::io::Cursor<Vec<u
/// 以明确的内容类型和状态码构造响应,并应用本机 API 的公共响应头。
fn text(status: StatusCode, value: &str, content_type: &str) -> Response<std::io::Cursor<Vec<u8>>> {
// 公共响应头只允许固定本机 Origin/方法/头名,非通配任意来源;这些头不替代回环绑定与路由校验。
let mut response = Response::from_string(value).with_status_code(status);
add_header(&mut response, "Content-Type", content_type);
add_header(
@@ -778,6 +811,7 @@ fn text(status: StatusCode, value: &str, content_type: &str) -> Response<std::io
/// 向响应追加经过 HTTP 库检查的头字段,不直接拼接未验证的原始报文。
fn add_header(response: &mut Response<std::io::Cursor<Vec<u8>>>, name: &str, value: &str) {
// 由 HTTP 库验证字段格式,非法头被忽略,不把未校验字符拼进原始响应报文。
if let Ok(header) = Header::from_bytes(name, value) {
response.add_header(header);
}