Own asynchronous timer tasks in the managed object lifecycle
Verify Tessera GUI / verify (push) Failing after 7m26s
Verify Tessera GUI / verify (push) Failing after 7m26s
This commit is contained in:
@@ -186,7 +186,7 @@ Events use `block.on("click", callback)` or `block.on("click", callback, "captur
|
||||
|
||||
Event methods `stopPropagation()`, `stopImmediatePropagation()`, `preventDefault()` and `isDefaultPrevented()` control delivery or report cancellation; there is currently no additional host default action to cancel. stopPropagation permits remaining listeners on the current occurrence, while the immediate variant stops them too. Listener order is snapshotted at dispatch start; disconnection before a listener's turn skips it, new connections wait for the next dispatch. The existing onClick setter remains a single compatibility callback, called after other non-capture listeners on that Block. All handlers share the VM call budget, with an explicit 10000-delivery limit that reports failure instead of truncating propagation. Reentrant dispatch of the same active Event is rejected; a completed Event can be reused. See [events.endor](examples/events.endor).
|
||||
|
||||
Visual objects also inherit `onMount(self, mount)` and `onUnmount(self, mount)` no-op methods, which source subclasses can override. Notifications occur once per actual occurrence transition: parents before children when attaching, children before parents when detaching. Updating text, color or geometry keeps an existing Mount and does not remount it. Shared content keeps its Block identity when replaced; hooks describe Mount attachment rather than each mutation of that content. Replacing a container child or switching Page produces the appropriate occurrence transitions, even when two Pages display the same root object. This currently covers the active presentation; native tab/window lifecycle is still pending.
|
||||
Visual objects also inherit `onMount(self, mount)` and `onUnmount(self, mount)` no-op methods, which source subclasses can override. Notifications occur once per actual occurrence transition: parents before children when attaching, children before parents when detaching. Updating text, color or geometry keeps an existing Mount and does not remount it. Shared content keeps its Block identity when replaced; hooks describe Mount attachment rather than each mutation of that content. Replacing a container child or switching Page produces the appropriate occurrence transitions, even when two Pages display the same root object. Mount lifecycle follows the active presentation in each native window.
|
||||
|
||||
Mount synchronization queues hooks after links and geometry are coherent. Hooks execute outside the session lock, under one VM budget per batch, after the source input or native event and before final publication. They may update objects or containers; resulting layout/notification work settles before a complete frame is published. A scalar Console result is evaluated before these deferred hooks. The rendering work budget explicitly fails on non-converging feedback. A hook failure after mount mutation stops that runtime and retains its previously displayed frame; failed PUT candidates preserve the old runtime. Hooks are never invoked by GC or by discarding an execution domain.
|
||||
|
||||
@@ -397,3 +397,46 @@ See [function-types.endor](examples/function-types.endor) for actual Endor sourc
|
||||
This adds no static inference, field-write checks, override variance, generics,
|
||||
effect typing or common native-signature metadata. Native APIs continue to validate
|
||||
their arguments and results at their own boundaries.
|
||||
|
||||
|
||||
### Owner-managed asynchronous tasks
|
||||
|
||||
`ui.after(owner, key, milliseconds, callback)` returns a managed `Task` and runs
|
||||
its zero-argument callback on the existing VM worker after the monotonic deadline.
|
||||
The callback must return Unit. Delay is an integer from 0 to 86,400,000 ms; zero
|
||||
means a later worker turn. The worker currently polls at up to 100-ms idle intervals,
|
||||
so deadlines are minimum delays rather than exact timing guarantees. No timer thread
|
||||
reads or changes VM objects. Ready work shares the same heap as code and native events;
|
||||
bindings, lifecycle and all affected windows settle before publishing a new frame.
|
||||
|
||||
Owners can be Blocks, attached Mounts, open Pages, live Windows, or ordinary objects
|
||||
with attribute storage. Use `ui` for application lifetime. Each owner owns a traced
|
||||
task scope, and tasks trace callbacks/captures. The scheduler and task-to-owner link
|
||||
are weak. Hidden but still-referenced objects keep updating; keeping a task token
|
||||
alone does not keep its owner alive unless the callback explicitly captures it.
|
||||
A source function's normal global environment remains a managed capture.
|
||||
|
||||
The same owner/key supersedes its previous pending task, using the actual managed
|
||||
task identity as the request generation. `task.cancel()` cancels pending work and
|
||||
returns whether it was active. `task.active()` queries eligibility; `task.status()`
|
||||
returns pending/running/completed/cancelled/failed. Cancellation and completion drop
|
||||
the callback and remove the owner slot, including when the caller retained the Task.
|
||||
Already running synchronous callbacks finish before the next input can be processed.
|
||||
|
||||
Closing a Page cancels its tasks and its Mount tasks immediately, including closing
|
||||
and reopening in one input. Switching away or replacing content cancels detached
|
||||
Mount tasks; Page and ordinary Block tasks remain. Moving a Page between windows
|
||||
preserves Page tasks and cancels old Mount tasks. Closing a Window cancels its tasks
|
||||
and the Pages it owns. Reset, DELETE and successful program replacement discard the
|
||||
old scheduler with its VM; the worker validates submission/runtime generation before
|
||||
publication, so stale work cannot update the new heap. A failed replacement keeps
|
||||
the previous runtime and its tasks. Callback errors stop the shared runtime, cancel
|
||||
remaining tasks and preserve the last valid picture; completed writes do not roll back.
|
||||
Scheduling/cancelling in read-only render/binding calls is rejected.
|
||||
|
||||
Limits are 64 pending tasks per owner, 1024 per runtime, and 64 ready callbacks per
|
||||
worker poll, each with 128 frames/100,000 instructions. Remaining ready work stays
|
||||
pending for later polls. This is currently a timer provider and task-lifecycle
|
||||
foundation; network/file providers, await/coroutines and interrupting a blocked
|
||||
native callback are not implemented. See [owned-tasks.endor](examples/owned-tasks.endor)
|
||||
for real Endor code and native buttons.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
class Actions {
|
||||
owner: Object
|
||||
state: Object
|
||||
function complete(self: Actions): Unit { self.state.increment() }
|
||||
function schedule(self: Actions, event: Event): Unit {
|
||||
ui.after(self.owner, "load", 1500, self.complete)
|
||||
}
|
||||
}
|
||||
state = ui.state(0)
|
||||
hidden = TextBlock("这个 Block 没有挂载,也能拥有任务")
|
||||
page = Page()
|
||||
page.title = "任务生命周期"
|
||||
pageActions = Actions(page, state)
|
||||
blockActions = Actions(hidden, state)
|
||||
appActions = Actions(ui, state)
|
||||
pageButton = Button("Page 任务:关闭 Tab 会取消")
|
||||
blockButton = Button("隐藏 Block 任务:关闭 Tab 仍继续")
|
||||
appButton = Button("应用任务:关闭 Tab 仍继续")
|
||||
pageConnection = pageButton.on("click", pageActions.schedule)
|
||||
blockConnection = blockButton.on("click", blockActions.schedule)
|
||||
appConnection = appButton.on("click", appActions.schedule)
|
||||
page.render(Column(24, 16, TextBlock("1.5 秒后更新同一个状态对象;重复点击只保留最新任务"), ui.textOf(state, "value"), pageButton, blockButton, appButton))
|
||||
initial = ui.after(ui, "initial", 500, appActions.complete)
|
||||
ui.window().setTitle("Owned Tasks")
|
||||
+5
-4
@@ -3,9 +3,9 @@
|
||||
| Module | Responsibility |
|
||||
| --- | --- |
|
||||
| main.rs | Native window event loop, namespace state and API startup |
|
||||
| api.rs | Code CRUD, live Console/reset and compatibility evaluation endpoints, worker-owned session, request observation, coalesced native viewport updates and diagnostics |
|
||||
| api.rs | Code CRUD, live Console/reset and compatibility evaluation endpoints, worker-owned session, request observation, coalesced native viewport/background-task updates, epoch checks and diagnostics |
|
||||
| activity.rs | Bounded in-memory HTTP exchanges with marked previews and allowlisted request headers |
|
||||
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
|
||||
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, asynchronous completion/fault boundaries, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
|
||||
| endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot |
|
||||
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, configured unified Function classification and source annotation checks, tab registry, Page lifecycle/navigation and immutable frame extraction |
|
||||
| binding.rs | Target-owned managed property bindings, weak Subscription tokens, read-only compute and borrowed dependency/output caches |
|
||||
@@ -16,6 +16,7 @@
|
||||
| event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver |
|
||||
| protocols.rs | Register explicit Visual/EventTarget/Children/Presentable managed traits and native type declarations |
|
||||
| presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work |
|
||||
| tasks.rs | Managed owner scopes and callbacks, weak timer index, request-key replacement, lifecycle cancellation and budgeted worker delivery |
|
||||
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation and opaque published Page identities |
|
||||
| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards and coalesced GUI projections |
|
||||
| vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop |
|
||||
@@ -25,7 +26,7 @@
|
||||
| native_visual.rs | Managed native visual protocol queries with occurrence validation, value conversion and bounded results |
|
||||
| object_list.rs | Traced indexed results shared by Mount queries and visual protocol results |
|
||||
| layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets |
|
||||
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation and display commands |
|
||||
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation, single-line fault banner (full cause retained in Frame) and display commands |
|
||||
| app.rs | Window events, logical viewport publication, redraw and system widget pointer/keyboard/IME routing |
|
||||
| clipboard.rs | UTF-8 macOS clipboard adapter independent of Finder locale, with strict decoding and surfaced errors |
|
||||
| system_ui/ | Host-only management widget library: stable IDs, interaction, theme and reusable control drawing |
|
||||
@@ -57,7 +58,7 @@ contain only immutable native data.
|
||||
Tests in api.rs execute real HTTP CRUD, persistent Console/reset/PUT isolation and a controlled queued-PUT/DELETE race
|
||||
without opening a window. Tests in endor_host.rs cover lifecycle, direct script and
|
||||
module entry, page methods, multiline inputs, original source ranges, malformed input,
|
||||
entry checks, source function annotation/function identity and REPL class redefinition, budgets, failure preservation, live object identity, explicit rendering,
|
||||
owner/task cancellation, hidden-object delivery, stale request and callback failure, entry checks, source function annotation/function identity and REPL class redefinition, budgets, failure preservation, live object identity, explicit rendering,
|
||||
compile-before-execute behavior and stale-result invalidation. They
|
||||
run only in remote CI. Font tests in text.rs and software_renderer.rs cover real
|
||||
advances, multiline height, fractional scaling, CJK fallback, grapheme-safe fitting,
|
||||
|
||||
+58
-10
@@ -531,13 +531,15 @@ impl Worker {
|
||||
self.repl = None;
|
||||
return;
|
||||
}
|
||||
if runtime.is_faulted() {
|
||||
return;
|
||||
}
|
||||
let id = runtime.id;
|
||||
let result = catch_unwind(AssertUnwindSafe(|| -> Result<_> {
|
||||
let document = runtime.resize_windows(&viewports)?;
|
||||
Ok((document, runtime.take_window_commands()?))
|
||||
if runtime.is_faulted() {
|
||||
runtime.poll_tasks()?;
|
||||
return Ok((None, Vec::new()));
|
||||
}
|
||||
let resized = runtime.resize_windows(&viewports)?;
|
||||
let completed = runtime.poll_tasks()?;
|
||||
Ok((completed.or(resized), runtime.take_window_commands()?))
|
||||
}));
|
||||
let mut current = match namespace.write() {
|
||||
Ok(current) => current,
|
||||
@@ -563,7 +565,7 @@ impl Worker {
|
||||
failure => {
|
||||
let mut document = current.document.clone();
|
||||
document.frame.fault = Some(match failure {
|
||||
Ok(Err(error)) => format!("Viewport update failed: {error:#}")
|
||||
Ok(Err(error)) => format!("Runtime background update failed: {error:#}")
|
||||
.chars()
|
||||
.take(1024)
|
||||
.collect(),
|
||||
@@ -571,7 +573,7 @@ impl Worker {
|
||||
self.repl = None;
|
||||
current.runtime_session = 0;
|
||||
current.window_commands.clear();
|
||||
"Runtime discarded after an internal viewport failure".into()
|
||||
"Runtime discarded after an internal background failure".into()
|
||||
}
|
||||
});
|
||||
for view in document.windows.values_mut() {
|
||||
@@ -777,7 +779,13 @@ impl Worker {
|
||||
Ok(Err(error)) => {
|
||||
if event.is_some() || faulted {
|
||||
let mut document = current.document.clone();
|
||||
let fault: String = format!("{error:#}").chars().take(1024).collect();
|
||||
// Preserve the first failure of this VM; subsequent
|
||||
// rejected Console input must not hide the callback cause.
|
||||
// A preserved picture from another generation is unrelated.
|
||||
let fault = (document.frame.session == id)
|
||||
.then(|| document.frame.fault.clone())
|
||||
.flatten()
|
||||
.unwrap_or_else(|| format!("{error:#}").chars().take(1024).collect());
|
||||
document.frame.fault = Some(fault.clone());
|
||||
for view in document.windows.values_mut() {
|
||||
view.frame.fault = Some(fault.clone());
|
||||
@@ -1032,7 +1040,7 @@ host executions, not a complete untrusted-code sandbox or a process-isolation de
|
||||
|
||||
## Managed visual types
|
||||
|
||||
`Object`, `Type`, `Function`, `Block`, `ContainerBlock`, `TextBlock`, `RectBlock`,
|
||||
`Object`, `Type`, `Function`, `Task`, `Block`, `ContainerBlock`, `TextBlock`, `RectBlock`,
|
||||
`Spacer`, `Row`, `Column`, `Button`, `Page`, `Mount`, and `Event` are managed nominal
|
||||
Type objects. Use `page = Page()` and `label = TextBlock("Hello")` in Endor source.
|
||||
The existing ui constructors return these same typed objects. `page.type`,
|
||||
@@ -1045,7 +1053,7 @@ are dynamically selected through self. Concrete native visual subclasses reuse r
|
||||
|
||||
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Existing-window drag/drop, release-point placement and full application-exit notifications remain pending.
|
||||
|
||||
Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. General constraint negotiation, wrapping and scrolling remain pending.
|
||||
Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. General constraint negotiation and text wrapping remain pending; ScrollBlock scrolling is described below.
|
||||
|
||||
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
|
||||
|
||||
@@ -1053,6 +1061,8 @@ ScrollBlock(width,height,child) is a ContainerBlock with managed viewport dimens
|
||||
|
||||
Native wheel POST /events uses kind scroll with the normal window/session/layout_version, a scrollable mount ID, point=[x,y], delta=[dx,dy], and no press_point. Deltas are signed finite logical pixels within +/-1000000; positive moves toward the end of content. Other kinds must omit delta. Native Shift+wheel maps to horizontal. The host checks the active committed frame, target attachment and clipped viewport before invoking Mount.scrollBy. These fields are transport metadata; source code uses the Endor methods above.
|
||||
|
||||
ui.after(owner,key,milliseconds,callback) returns Task. The zero-argument callback runs on the owning VM worker after at least the integer 0..86400000 ms delay and must return Unit. Idle polling can add up to 100 ms; execution load may delay delivery further. Task.cancel/active/status expose cancellation, eligibility and pending/running/completed/cancelled/failed state. One owner/key replaces the prior pending task. Owner scopes and callback captures are managed strong edges; scheduler and owner links are weak. ui is an application owner. Hidden live objects continue; Page close cancels its and its Mount tasks, even close/reopen within one input. Page movement preserves Page tasks but replaces Mounts. Window close cancels its Pages/tasks; reset/DELETE/program replacement discard old scheduler/VM and generation checks reject stale publication. Failed PUT preserves old tasks. Callback failure stops the domain and cancels remaining tasks; earlier writes do not roll back. Read-only rendering cannot schedule/cancel. Limits: 64 pending per owner, 1024 per runtime, 64 delivered per poll, 128 frames/100000 instructions per callback. Providers currently support timers; network/file providers and await are pending.
|
||||
|
||||
Source function parameter annotations are checked before the body and return annotations before returning. Object accepts any live value; Unit accepts nil; Number, String/Text and Bool match scalar kinds. Function includes source/native functions and bound methods, while callable class definitions remain Type. View is a compatibility alias for Block. Other names resolve actual Type/Trait objects in the function's globals then captured builtins at each call. The method's own class uses the receiver's actual owning definition, preserving old bound methods after REPL redefinition. Other type names are not frozen at definition. UnknownAnnotation and TypeMismatch report failures; bad returns do not roll back earlier writes. No static inference, field-write validation, override variance, generic or effect typing is provided.
|
||||
|
||||
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; source parameter/return annotations are checked at invocation. Native signature metadata, field-write and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
|
||||
@@ -1281,6 +1291,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_failure_preserves_its_cause_after_rejected_console_input() {
|
||||
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
|
||||
let namespace = Arc::new(RwLock::new(NamespaceState::default()));
|
||||
let api = start_server(server.clone(), namespace.clone(), Arc::new(|| {})).unwrap();
|
||||
let client = TestServer {
|
||||
address: server.server_addr().to_ip().unwrap(),
|
||||
server,
|
||||
api: Some(api),
|
||||
};
|
||||
let source = r#"class Failure {
|
||||
function stop(self: Failure): Unit { ui.window().resize(0,600) }
|
||||
}
|
||||
failure=Failure()
|
||||
page=Page()
|
||||
page.render(TextBlock("preserved"))
|
||||
task=ui.after(ui,"failure",0,failure.stop)"#;
|
||||
let result = client.request("PUT", "/v1/namespaces/app.main/code", source);
|
||||
assert_eq!(result.0, 200, "{}", result.2);
|
||||
let repl = "/v1/namespaces/app.main/repl";
|
||||
assert_eq!(client.request("POST", repl, "42").0, 422);
|
||||
let fault = namespace
|
||||
.read()
|
||||
.unwrap()
|
||||
.document
|
||||
.frame
|
||||
.fault
|
||||
.clone()
|
||||
.unwrap();
|
||||
assert!(fault.contains("window size"), "{fault}");
|
||||
assert!(fault.contains("stop"), "{fault}");
|
||||
assert_eq!(client.request("POST", repl, "42").0, 422);
|
||||
assert_eq!(
|
||||
namespace.read().unwrap().document.frame.fault.as_ref(),
|
||||
Some(&fault)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_keeps_memory_until_reset_or_complete_put_without_erasing_the_page() {
|
||||
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
|
||||
|
||||
+10
-2
@@ -38,10 +38,11 @@ pub enum Kind {
|
||||
|
||||
/// The VM owns the Block -> Cell -> Data relationship. Shared assignment
|
||||
/// changes the Cell to point at another Block, retaining the original identity.
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Block {
|
||||
pub state: ObjectRef,
|
||||
pub page: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
}
|
||||
|
||||
impl ObjectPayload for Block {
|
||||
@@ -88,6 +89,9 @@ impl ObjectPayload for Block {
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
visit(self.state);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
}
|
||||
fn assignment_cell(
|
||||
&self,
|
||||
@@ -203,7 +207,11 @@ pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef,
|
||||
data.properties = Some(properties);
|
||||
let data = cx.allocate(data)?;
|
||||
let state = cx.new_cell(Some(Value::Object(data)))?;
|
||||
cx.allocate(Block { state, page })
|
||||
cx.allocate(Block {
|
||||
state,
|
||||
page,
|
||||
tasks: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Borrowed final data; forwarding is part of the managed graph, never an Arc
|
||||
|
||||
+1
-1
@@ -263,7 +263,7 @@ impl RenderDocument {
|
||||
RenderCommand::Text {
|
||||
x: 12.0,
|
||||
y: 8.0,
|
||||
value: format!("运行已停止:{error}"),
|
||||
value: format!("运行已停止:{}", error.lines().next().unwrap_or_default()),
|
||||
size: 1,
|
||||
color: "#A32D25".into(),
|
||||
}
|
||||
|
||||
@@ -604,6 +604,37 @@ impl ReplSession {
|
||||
result
|
||||
}
|
||||
|
||||
/// Deliver ready work on the owning VM worker, never from the GUI or a
|
||||
/// provider thread. A failed callback stops the same shared fault domain.
|
||||
pub fn poll_tasks(&mut self) -> Result<Option<RenderDocument>> {
|
||||
if self.faulted {
|
||||
if self.bridge.cancel_tasks(&mut self.candidate.vm)? > 0 {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
let mut completed = false;
|
||||
let result = (|| {
|
||||
if self.bridge.poll_tasks(&mut self.candidate.vm)? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
completed = true;
|
||||
self.refresh_document()
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.faulted = true;
|
||||
self.bridge.cancel_tasks(&mut self.candidate.vm)?;
|
||||
self.take_window_commands()?;
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
}
|
||||
if completed || result.is_err() {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn take_window_commands(&self) -> Result<Vec<crate::window::Command>> {
|
||||
self.bridge.take_window_commands(&self.candidate.vm)
|
||||
}
|
||||
@@ -955,6 +986,183 @@ mod tests {
|
||||
const EXAMPLE: &str = include_str!("../examples/hello.endor");
|
||||
const PAGE: &str = include_str!("../examples/page.endor");
|
||||
|
||||
#[test]
|
||||
fn owned_tasks_replace_cancel_and_update_unmounted_objects() {
|
||||
let source = r#"class Action {
|
||||
state: Object
|
||||
value: Number
|
||||
function apply(self: Action): Unit { self.state.value = self.value }
|
||||
}
|
||||
state = ui.state(0)
|
||||
hidden = TextBlock("not mounted")
|
||||
first = Action(state, 1)
|
||||
latest = Action(state, 2)
|
||||
page = Page()
|
||||
page.render(ui.textOf(state,"value"))
|
||||
old = ui.after(hidden,"load",0,first.apply)
|
||||
next = ui.after(hidden,"load",0,latest.apply)"#;
|
||||
let (mut session, _) = ReplSession::load(source, "app.main", 1, 190).unwrap();
|
||||
assert_eq!(
|
||||
session.execute("old.status()", "app.main").unwrap().value,
|
||||
"\"cancelled\""
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("state.value", "app.main").unwrap().value,
|
||||
"0"
|
||||
);
|
||||
assert!(session.poll_tasks().unwrap().is_some());
|
||||
assert_eq!(
|
||||
session.execute("state.value", "app.main").unwrap().value,
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("next.status()", "app.main").unwrap().value,
|
||||
"\"completed\""
|
||||
);
|
||||
session
|
||||
.execute(
|
||||
"cancelled=ui.after(ui,\"cancel\",0,first.apply) cancelled.cancel()",
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
session.poll_tasks().unwrap();
|
||||
assert_eq!(
|
||||
session.execute("state.value", "app.main").unwrap().value,
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("cancelled.active()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_and_mount_tasks_cancel_while_block_and_app_owners_continue() {
|
||||
let source = r#"class Action {
|
||||
state: Object
|
||||
function apply(self: Action): Unit { self.state.increment() }
|
||||
}
|
||||
state=ui.state(0)
|
||||
action=Action(state)
|
||||
leaf=TextBlock("owner")
|
||||
page=Page()
|
||||
page.render(leaf)"#;
|
||||
let (mut session, _) = ReplSession::load(source, "app.main", 1, 191).unwrap();
|
||||
session
|
||||
.execute(
|
||||
r#"held=leaf.mounts().at(0)
|
||||
pageTask=ui.after(page,"page",0,action.apply)
|
||||
mountTask=ui.after(held,"mount",0,action.apply)
|
||||
blockTask=ui.after(leaf,"block",0,action.apply)
|
||||
appTask=ui.after(ui,"app",0,action.apply)
|
||||
page.close()
|
||||
page.open()"#,
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
for name in ["pageTask", "mountTask"] {
|
||||
assert_eq!(
|
||||
session
|
||||
.execute(&format!("{name}.status()"), "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"\"cancelled\""
|
||||
);
|
||||
}
|
||||
session.poll_tasks().unwrap();
|
||||
assert_eq!(
|
||||
session.execute("state.value", "app.main").unwrap().value,
|
||||
"2"
|
||||
);
|
||||
// Moving a Page preserves its scope; the replaced Mount is cancelled.
|
||||
session
|
||||
.execute(
|
||||
r#"moving=ui.after(page,"move",0,action.apply)
|
||||
oldMount=leaf.mounts().at(0)
|
||||
oldMountTask=ui.after(oldMount,"move",0,action.apply)
|
||||
other=page.detachToWindow()"#,
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("oldMountTask.status()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"\"cancelled\""
|
||||
);
|
||||
session.poll_tasks().unwrap();
|
||||
assert_eq!(
|
||||
session.execute("state.value", "app.main").unwrap().value,
|
||||
"3"
|
||||
);
|
||||
session
|
||||
.execute(
|
||||
"closing=ui.after(other,\"close\",0,action.apply) other.close()",
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
session.poll_tasks().unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("closing.status()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"\"cancelled\""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_task_scope_is_collectable_and_callback_failure_stops_remaining_work() {
|
||||
let source = r#"class Action {
|
||||
state: Object
|
||||
function apply(self: Action): Unit { self.state.increment() }
|
||||
function fail(self: Action): Unit { ui.window().resize(0,600) }
|
||||
}
|
||||
function orphan(): Task {
|
||||
let owner=TextBlock("temporary")
|
||||
return ui.after(owner,"temporary",0,ui.window().focus)
|
||||
}
|
||||
state=ui.state(0)
|
||||
action=Action(state)
|
||||
page=Page()
|
||||
page.render(TextBlock("preserve"))
|
||||
token=orphan()"#;
|
||||
let (mut session, _) = ReplSession::load(source, "app.main", 1, 192).unwrap();
|
||||
assert_eq!(
|
||||
session.execute("token.active()", "app.main").unwrap().value,
|
||||
"false"
|
||||
);
|
||||
session.poll_tasks().unwrap();
|
||||
assert_eq!(
|
||||
session.execute("token.status()", "app.main").unwrap().value,
|
||||
"\"cancelled\""
|
||||
);
|
||||
session.execute("broken=ui.after(ui,\"fail\",0,action.fail) later=ui.after(ui,\"later\",0,action.apply)","app.main").unwrap();
|
||||
assert!(session.poll_tasks().is_err());
|
||||
assert!(session.is_faulted());
|
||||
let globals = session.candidate.globals.unwrap();
|
||||
let state = match session
|
||||
.candidate
|
||||
.vm
|
||||
.dict_get(globals, &Value::Text("state".into()))
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
{
|
||||
Value::Object(state) => state,
|
||||
_ => panic!("state object"),
|
||||
};
|
||||
assert_eq!(
|
||||
session.candidate.vm.get_attr(state, "value").unwrap(),
|
||||
Value::Number(0.into())
|
||||
);
|
||||
assert!(session.poll_tasks().unwrap().is_none());
|
||||
assert!(session.execute("42", "app.main").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_annotations_classify_functions_and_reject_before_body() {
|
||||
let (mut session, _) = ReplSession::load(
|
||||
|
||||
@@ -28,6 +28,7 @@ mod source_paint;
|
||||
mod sources;
|
||||
mod system_ui;
|
||||
mod tabs;
|
||||
mod tasks;
|
||||
mod text;
|
||||
mod ui_bridge;
|
||||
mod vm_sequence;
|
||||
|
||||
@@ -21,6 +21,7 @@ pub struct Mount {
|
||||
pub scroll_offset: [f32; 2],
|
||||
pub version: u64,
|
||||
pub mounted: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
// Private derived scratch, installed before the read-only layout call and
|
||||
// cleared by geometry commit. It contains no managed references or roots.
|
||||
pub layout: Option<Arc<Mutex<crate::layout::Context>>>,
|
||||
@@ -41,6 +42,9 @@ impl ObjectPayload for Mount {
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
visit(self.block);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +324,7 @@ impl NativeCallable for Sync {
|
||||
scroll_offset: [0.0, 0.0],
|
||||
version: self.frame.layout_version,
|
||||
mounted: true,
|
||||
tasks: None,
|
||||
layout: None,
|
||||
})?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
|
||||
@@ -361,6 +366,7 @@ impl NativeCallable for Sync {
|
||||
id.map(|id| cx.store().downgrade(objects[&id])).transpose()
|
||||
};
|
||||
let mount = Mount {
|
||||
tasks: cx.store().payload::<Mount>(object, "Mount")?.tasks,
|
||||
block: blocks[&geometry.block_id],
|
||||
page,
|
||||
parent: link(geometry.parent)?,
|
||||
@@ -418,6 +424,7 @@ impl NativeCallable for Sync {
|
||||
&& objects.get(id) != Some(&object)
|
||||
{
|
||||
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
|
||||
crate::tasks::cancel_owner(cx, object)?;
|
||||
mount.mounted = false;
|
||||
mount.layout = None;
|
||||
mount.parent = None;
|
||||
|
||||
+566
@@ -0,0 +1,566 @@
|
||||
//! Owner-managed asynchronous work. Only weak identities enter the scheduler;
|
||||
//! callbacks and scopes are ordinary traced edges in the Aster object graph.
|
||||
use std::{
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
||||
ObjectStore, Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
|
||||
use crate::{block::Block, mount::Mount, ui_bridge::desktop_type, window::ManagedWindow};
|
||||
|
||||
const SCOPE: &str = "\0tessera.tasks";
|
||||
const MAX_TASKS: usize = 1024;
|
||||
const MAX_OWNER_TASKS: usize = 64;
|
||||
const MAX_READY: usize = 64;
|
||||
|
||||
type Index = Arc<Mutex<Vec<WeakObjectRef>>>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum State {
|
||||
Pending,
|
||||
Running,
|
||||
Completed,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
impl State {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pending => "pending",
|
||||
Self::Running => "running",
|
||||
Self::Completed => "completed",
|
||||
Self::Cancelled => "cancelled",
|
||||
Self::Failed => "failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Task {
|
||||
owner: WeakObjectRef,
|
||||
key: String,
|
||||
due: Instant,
|
||||
callback: Option<ObjectRef>,
|
||||
state: State,
|
||||
}
|
||||
impl ObjectPayload for Task {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"tessera-task"
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(callback) = self.callback {
|
||||
visit(callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn object(value: &Value) -> Result<ObjectRef, VmError> {
|
||||
match value {
|
||||
Value::Object(object) => Ok(*object),
|
||||
_ => Err(invalid("task owner and callback must be managed objects")),
|
||||
}
|
||||
}
|
||||
fn scope(store: &ObjectStore, owner: ObjectRef) -> Result<Option<ObjectRef>, VmError> {
|
||||
let payload = store.object(owner)?.payload();
|
||||
if let Some(value) = payload.as_any().downcast_ref::<Block>() {
|
||||
return Ok(value.tasks);
|
||||
}
|
||||
if let Some(value) = payload.as_any().downcast_ref::<Mount>() {
|
||||
return Ok(value.tasks);
|
||||
}
|
||||
if let Some(value) = payload.as_any().downcast_ref::<ManagedWindow>() {
|
||||
return Ok(value.tasks);
|
||||
}
|
||||
match store.get_attr(owner, SCOPE) {
|
||||
Ok(Value::Object(scope)) => {
|
||||
// Validate even the private host field before using it as an owner edge.
|
||||
store.dict_items(scope)?;
|
||||
Ok(Some(scope))
|
||||
}
|
||||
Err(VmError::AttributeNotFound(_)) => Ok(None),
|
||||
Ok(_) => Err(invalid("invalid task scope")),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
fn install_scope(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
scope: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
let payload = cx.store().object(owner)?.payload();
|
||||
if let Some(value) = payload.as_any().downcast_ref::<Block>() {
|
||||
let mut value = value.clone();
|
||||
value.tasks = Some(scope);
|
||||
return cx.replace_payload(owner, value);
|
||||
}
|
||||
if let Some(value) = payload.as_any().downcast_ref::<Mount>() {
|
||||
let mut value = value.clone();
|
||||
value.tasks = Some(scope);
|
||||
return cx.replace_payload(owner, value);
|
||||
}
|
||||
if let Some(value) = payload.as_any().downcast_ref::<ManagedWindow>() {
|
||||
let mut value = value.clone();
|
||||
value.tasks = Some(scope);
|
||||
return cx.replace_payload(owner, value);
|
||||
}
|
||||
cx.set_attr(owner, SCOPE, Value::Object(scope))
|
||||
}
|
||||
fn eligible(store: &ObjectStore, owner: ObjectRef, desktop: ObjectRef) -> Result<bool, VmError> {
|
||||
let payload = store.object(owner)?.payload();
|
||||
if let Some(mount) = payload.as_any().downcast_ref::<Mount>() {
|
||||
if !mount.mounted {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(page) = mount.page {
|
||||
// No retained root is needed for this synchronous borrowed lookup.
|
||||
let windows = object(&store.get_attr(desktop, "windows")?)?;
|
||||
for (_, value) in store.dict_items(windows)? {
|
||||
for candidate in crate::window::pages(store, object(value)?)? {
|
||||
if store.downgrade(*candidate)? == page {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(window) = payload.as_any().downcast_ref::<ManagedWindow>() {
|
||||
return Ok(!window.closed);
|
||||
}
|
||||
if payload
|
||||
.as_any()
|
||||
.downcast_ref::<Block>()
|
||||
.is_some_and(|block| block.page)
|
||||
{
|
||||
let windows = object(&store.get_attr(desktop, "windows")?)?;
|
||||
for (_, value) in store.dict_items(windows)? {
|
||||
let window = object(value)?;
|
||||
if crate::window::pages(store, window)?.contains(&owner) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn current(
|
||||
store: &ObjectStore,
|
||||
owner: ObjectRef,
|
||||
reference: ObjectRef,
|
||||
task: &Task,
|
||||
) -> Result<bool, VmError> {
|
||||
Ok(match scope(store, owner)? {
|
||||
Some(scope) => {
|
||||
store.dict_get(scope, &Value::Text(task.key.clone()))? == Some(Value::Object(reference))
|
||||
}
|
||||
None => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Called at the actual close/detach boundary, including close-then-reopen in
|
||||
/// one language input. A later appearance never revives these identities.
|
||||
pub fn cancel_owner(cx: &mut NativeContext<'_>, owner: ObjectRef) -> Result<(), VmError> {
|
||||
let Some(scope) = scope(cx.store(), owner)? else {
|
||||
return Ok(());
|
||||
};
|
||||
for (key, value) in cx.store().dict_items(scope)?.to_vec() {
|
||||
let reference = object(&value)?;
|
||||
let mut task = cx.store().payload::<Task>(reference, "Task")?.clone();
|
||||
if task.state == State::Pending {
|
||||
task.state = State::Cancelled;
|
||||
task.callback = None;
|
||||
cx.replace_payload(reference, task)?;
|
||||
}
|
||||
cx.dict_delete(scope, &key)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct After {
|
||||
index: Index,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for After {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"asynchronous work is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let [owner, key, delay, callback] = args else {
|
||||
return Err(invalid(
|
||||
"ui.after requires owner, key, milliseconds and callback",
|
||||
));
|
||||
};
|
||||
let owner = object(owner)?;
|
||||
let callback = object(callback)?;
|
||||
if !cx.store().object(callback)?.payload().is_function() {
|
||||
return Err(invalid("task callback must be a Function"));
|
||||
}
|
||||
if cx
|
||||
.store()
|
||||
.positional_parameter_count(callback)?
|
||||
.is_some_and(|count| count != 0)
|
||||
{
|
||||
return Err(invalid("task callback requires zero unbound parameters"));
|
||||
}
|
||||
let Value::Text(key) = key else {
|
||||
return Err(invalid("task key must be text"));
|
||||
};
|
||||
if key.is_empty() || key.len() > 128 || key.chars().any(char::is_control) {
|
||||
return Err(invalid("invalid task key"));
|
||||
}
|
||||
let Value::Number(delay) = delay else {
|
||||
return Err(invalid(
|
||||
"task delay must be an integer number of milliseconds",
|
||||
));
|
||||
};
|
||||
let milliseconds = delay
|
||||
.as_i64()
|
||||
.filter(|delay| (0..=86_400_000).contains(delay))
|
||||
.ok_or(invalid(
|
||||
"task delay must be 0..86400000 integer milliseconds",
|
||||
))?;
|
||||
if !eligible(cx.store(), owner, self.desktop)? {
|
||||
return Err(invalid("task owner is closed or detached"));
|
||||
}
|
||||
let existing_scope = scope(cx.store(), owner)?;
|
||||
let previous = existing_scope
|
||||
.map(|scope| cx.store().dict_get(scope, &Value::Text(key.clone())))
|
||||
.transpose()?
|
||||
.flatten()
|
||||
.map(|value| object(&value))
|
||||
.transpose()?;
|
||||
let mut index = self
|
||||
.index
|
||||
.lock()
|
||||
.map_err(|_| invalid("task index poisoned"))?;
|
||||
let mut live = Vec::new();
|
||||
for weak in index.iter().copied() {
|
||||
if let Some(task) = cx.upgrade(weak)?
|
||||
&& cx.store().payload::<Task>(task, "Task")?.state == State::Pending
|
||||
{
|
||||
live.push(weak);
|
||||
}
|
||||
}
|
||||
if live.len() >= MAX_TASKS && previous.is_none() {
|
||||
return Err(VmError::ExecutionLimit("1024 pending tasks per runtime"));
|
||||
}
|
||||
if let Some(scope) = existing_scope
|
||||
&& cx.store().dict_items(scope)?.len() >= MAX_OWNER_TASKS
|
||||
&& previous.is_none()
|
||||
{
|
||||
return Err(VmError::ExecutionLimit("64 pending tasks per owner"));
|
||||
}
|
||||
let task = cx.allocate(Task {
|
||||
owner: cx.store().downgrade(owner)?,
|
||||
key: key.clone(),
|
||||
due: Instant::now()
|
||||
.checked_add(Duration::from_millis(milliseconds as u64))
|
||||
.ok_or(invalid("task deadline overflow"))?,
|
||||
callback: Some(callback),
|
||||
state: State::Pending,
|
||||
})?;
|
||||
cx.attach_type(task, desktop_type(cx.store(), "Task", self.desktop)?)?;
|
||||
let task_scope = if let Some(scope) = existing_scope {
|
||||
scope
|
||||
} else {
|
||||
let scope = cx.new_dict()?;
|
||||
install_scope(cx, owner, scope)?;
|
||||
scope
|
||||
};
|
||||
// Publish the new identity before invalidating the old result. Nothing
|
||||
// external is dispatched until the worker accepts this VM generation.
|
||||
let previous_weak = previous.map(|old| cx.store().downgrade(old)).transpose()?;
|
||||
if let Some(weak) = previous_weak {
|
||||
cx.upgrade(weak)?;
|
||||
}
|
||||
cx.dict_set(task_scope, Value::Text(key.clone()), Value::Object(task))?;
|
||||
if let Some(previous) = previous {
|
||||
// The replacement above can release the old Task's last owner edge.
|
||||
// Preserve it through the replacement even without a saved token.
|
||||
if cx.store().object(previous).is_ok() {
|
||||
let mut old = cx.store().payload::<Task>(previous, "Task")?.clone();
|
||||
if old.state == State::Pending {
|
||||
old.state = State::Cancelled;
|
||||
old.callback = None;
|
||||
cx.replace_payload(previous, old)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let weak = cx.store().downgrade(task)?;
|
||||
live.retain(|old| Some(*old) != previous_weak);
|
||||
live.push(weak);
|
||||
*index = live;
|
||||
Ok(NativeResult::Return(Value::Object(task)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Query {
|
||||
Cancel,
|
||||
Status,
|
||||
Active,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Method {
|
||||
query: Query,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Method {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [value] = args else {
|
||||
return Err(invalid("Task methods accept no arguments"));
|
||||
};
|
||||
let reference = object(value)?;
|
||||
let mut task = cx.store().payload::<Task>(reference, "Task")?.clone();
|
||||
let pending = task.state == State::Pending;
|
||||
let owner = if pending {
|
||||
cx.upgrade(task.owner)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let active = if let Some(owner) = owner {
|
||||
eligible(cx.store(), owner, self.desktop)?
|
||||
&& current(cx.store(), owner, reference, &task)?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let value = match self.query {
|
||||
Query::Status => Value::Text(
|
||||
if pending && !active {
|
||||
State::Cancelled.name()
|
||||
} else {
|
||||
task.state.name()
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
Query::Active => Value::Bool(active),
|
||||
Query::Cancel => {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"task cancellation is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
if pending {
|
||||
task.state = State::Cancelled;
|
||||
task.callback = None;
|
||||
cx.replace_payload(reference, task.clone())?;
|
||||
if let Some(owner) = owner
|
||||
&& current(cx.store(), owner, reference, &task)?
|
||||
&& let Some(scope) = scope(cx.store(), owner)?
|
||||
{
|
||||
cx.dict_delete(scope, &Value::Text(task.key))?;
|
||||
}
|
||||
}
|
||||
Value::Bool(pending && active)
|
||||
}
|
||||
};
|
||||
Ok(NativeResult::Return(value))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
index: Index,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl Scheduler {
|
||||
/// Mutation boundaries collect unreachable owner/callback cycles before
|
||||
/// this weak lookup. Idle timer polling does not rescan the entire heap.
|
||||
pub fn poll(&self, vm: &mut Vm) -> Result<usize> {
|
||||
let snapshot = self
|
||||
.index
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("task index poisoned"))?
|
||||
.clone();
|
||||
let now = Instant::now();
|
||||
let mut work = 0;
|
||||
for weak in snapshot {
|
||||
let Some(reference) = vm.upgrade(weak)? else {
|
||||
continue;
|
||||
};
|
||||
let result = (|| -> Result<()> {
|
||||
let task = vm.payload::<Task>(reference, "Task")?.clone();
|
||||
if task.state != State::Pending {
|
||||
return Ok(());
|
||||
}
|
||||
let owner = vm.upgrade(task.owner)?;
|
||||
let result = (|| -> Result<()> {
|
||||
let active = if let Some(owner) = owner {
|
||||
eligible(vm.object_store(), owner, self.desktop)?
|
||||
&& current(vm.object_store(), owner, reference, &task)?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !active {
|
||||
work += 1;
|
||||
return finish(vm, reference, State::Cancelled);
|
||||
}
|
||||
if task.due > now || work >= MAX_READY {
|
||||
return Ok(());
|
||||
}
|
||||
work += 1;
|
||||
let callback = task
|
||||
.callback
|
||||
.ok_or_else(|| anyhow::anyhow!("pending task has no callback"))?;
|
||||
let mut running = task.clone();
|
||||
running.state = State::Running;
|
||||
vm.replace_payload(reference, running)?;
|
||||
let result = vm
|
||||
.call_with_limits(
|
||||
callback,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 100_000,
|
||||
},
|
||||
)
|
||||
.map_err(|error| crate::endor_host::runtime_error(vm, error));
|
||||
match result {
|
||||
Ok(value) => {
|
||||
let unit = matches!(value, Value::Nil);
|
||||
vm.release_value(value)?;
|
||||
finish(
|
||||
vm,
|
||||
reference,
|
||||
if unit {
|
||||
State::Completed
|
||||
} else {
|
||||
State::Failed
|
||||
},
|
||||
)?;
|
||||
if !unit {
|
||||
bail!("asynchronous callback must return Unit");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
finish(vm, reference, State::Failed)?;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
})();
|
||||
if let Some(owner) = owner {
|
||||
vm.release(owner)?;
|
||||
}
|
||||
result
|
||||
})();
|
||||
vm.release(reference)?;
|
||||
result?;
|
||||
}
|
||||
self.prune(vm)?;
|
||||
Ok(work)
|
||||
}
|
||||
pub fn cancel_all(&self, vm: &mut Vm) -> Result<usize> {
|
||||
let snapshot = self
|
||||
.index
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("task index poisoned"))?
|
||||
.clone();
|
||||
for weak in snapshot {
|
||||
if let Some(task) = vm.upgrade(weak)? {
|
||||
let result = finish(vm, task, State::Cancelled);
|
||||
vm.release(task)?;
|
||||
result?;
|
||||
}
|
||||
}
|
||||
let mut index = self
|
||||
.index
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("task index poisoned"))?;
|
||||
let count = index.len();
|
||||
index.clear();
|
||||
Ok(count)
|
||||
}
|
||||
fn prune(&self, vm: &mut Vm) -> Result<()> {
|
||||
let mut index = self
|
||||
.index
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("task index poisoned"))?;
|
||||
let mut live = Vec::new();
|
||||
for weak in index.iter().copied() {
|
||||
if let Some(task) = vm.upgrade(weak)? {
|
||||
let pending = vm
|
||||
.payload::<Task>(task, "Task")
|
||||
.map(|task| task.state == State::Pending);
|
||||
vm.release(task)?;
|
||||
if pending? {
|
||||
live.push(weak);
|
||||
}
|
||||
}
|
||||
}
|
||||
*index = live;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn finish(vm: &mut Vm, reference: ObjectRef, state: State) -> Result<()> {
|
||||
let mut task = vm.payload::<Task>(reference, "Task")?.clone();
|
||||
if !matches!(task.state, State::Pending | State::Running) {
|
||||
return Ok(());
|
||||
}
|
||||
task.state = state;
|
||||
task.callback = None;
|
||||
vm.replace_payload(reference, task.clone())?;
|
||||
if let Some(owner) = vm.upgrade(task.owner)? {
|
||||
let result = (|| -> Result<()> {
|
||||
if current(vm.object_store(), owner, reference, &task)?
|
||||
&& let Some(scope) = scope(vm.object_store(), owner)?
|
||||
{
|
||||
vm.dict_delete(scope, &Value::Text(task.key))?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
vm.release(owner)?;
|
||||
result?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
ui: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<Scheduler> {
|
||||
let index = Arc::new(Mutex::new(Vec::new()));
|
||||
let definition = desktop_type(vm.object_store(), "Task", desktop)?;
|
||||
let after = vm.allocate(ContextNativeFunction::new(
|
||||
"after",
|
||||
After {
|
||||
index: index.clone(),
|
||||
desktop,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(after);
|
||||
vm.set_attr(ui, "after", Value::Object(after))?;
|
||||
for (name, query) in [
|
||||
("cancel", Query::Cancel),
|
||||
("status", Query::Status),
|
||||
("active", Query::Active),
|
||||
] {
|
||||
let method = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
Method { query, desktop },
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(method);
|
||||
vm.define_method(definition, name, method)?;
|
||||
}
|
||||
Ok(Scheduler { index, desktop })
|
||||
}
|
||||
+26
-1
@@ -39,6 +39,7 @@ pub const TYPE_NAMES: &[&str] = &[
|
||||
"Mount",
|
||||
"Event",
|
||||
"Subscription",
|
||||
"Task",
|
||||
"ObjectList",
|
||||
"Constraints",
|
||||
"MeasureResult",
|
||||
@@ -1312,11 +1313,26 @@ impl NativeCallable for Function {
|
||||
data.children.clear();
|
||||
}
|
||||
Close => {
|
||||
crate::tasks::cancel_owner(cx, owner)?;
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
if let Some(id) = page_window(cx.store(), &state, owner)? {
|
||||
// Closing the tab ends its presentation even if source
|
||||
// reopens it before the next layout can detach the Mounts.
|
||||
let page = cx.store().downgrade(owner)?;
|
||||
for weak in state.presentations[&id].mounts.ordered() {
|
||||
if let Some(mount) = cx.upgrade(weak)?
|
||||
&& cx
|
||||
.store()
|
||||
.payload::<crate::mount::Mount>(mount, "Mount")?
|
||||
.page
|
||||
== Some(page)
|
||||
{
|
||||
crate::tasks::cancel_owner(cx, mount)?;
|
||||
}
|
||||
}
|
||||
remove_page(
|
||||
cx,
|
||||
state
|
||||
@@ -1402,6 +1418,7 @@ impl NativeCallable for Function {
|
||||
pub struct UiBridge {
|
||||
pub ui: ObjectRef,
|
||||
session: Shared,
|
||||
tasks: crate::tasks::Scheduler,
|
||||
}
|
||||
|
||||
fn project_tabs(
|
||||
@@ -1444,6 +1461,12 @@ fn project_tabs(
|
||||
}
|
||||
|
||||
impl UiBridge {
|
||||
pub fn poll_tasks(&self, vm: &mut Vm) -> Result<usize> {
|
||||
self.tasks.poll(vm)
|
||||
}
|
||||
pub fn cancel_tasks(&self, vm: &mut Vm) -> Result<usize> {
|
||||
self.tasks.cancel_all(vm)
|
||||
}
|
||||
pub fn window_ids(&self) -> Result<Vec<u64>> {
|
||||
let state = self
|
||||
.session
|
||||
@@ -2272,6 +2295,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
("Mount", "Object", None),
|
||||
("Event", "Object", Some("event")),
|
||||
("Subscription", "Object", None),
|
||||
("Task", "Object", None),
|
||||
("ObjectList", "Object", Some("object-list")),
|
||||
] {
|
||||
let base = object(Some(&vm.get_attr(ui, base_name)?))?;
|
||||
@@ -2455,7 +2479,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?;
|
||||
crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?;
|
||||
crate::protocols::install(vm, roots, desktop, ui)?;
|
||||
Ok(UiBridge { ui, session })
|
||||
let tasks = crate::tasks::install(vm, roots, ui, desktop)?;
|
||||
Ok(UiBridge { ui, session, tasks })
|
||||
}
|
||||
|
||||
fn attach_named_type(
|
||||
|
||||
@@ -38,6 +38,7 @@ pub struct ManagedWindow {
|
||||
pub id: u64,
|
||||
pub desktop: ObjectRef,
|
||||
pub closed: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
tabs: ObjectRef,
|
||||
pages: Vec<ObjectRef>,
|
||||
sequence: u64,
|
||||
@@ -60,6 +61,9 @@ impl ObjectPayload for ManagedWindow {
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
visit(self.desktop);
|
||||
if let Some(tasks) = self.tasks {
|
||||
visit(tasks);
|
||||
}
|
||||
visit(self.tabs);
|
||||
for page in &self.pages {
|
||||
visit(*page);
|
||||
@@ -285,6 +289,7 @@ pub fn install(
|
||||
id: MAIN_WINDOW,
|
||||
desktop,
|
||||
closed: false,
|
||||
tasks: None,
|
||||
tabs,
|
||||
pages: Vec::new(),
|
||||
sequence: 0,
|
||||
@@ -327,6 +332,7 @@ pub fn create(
|
||||
id,
|
||||
desktop,
|
||||
closed: false,
|
||||
tasks: None,
|
||||
tabs,
|
||||
pages: Vec::new(),
|
||||
sequence: 0,
|
||||
@@ -354,7 +360,9 @@ pub fn close(cx: &mut NativeContext<'_>, window: ObjectRef) -> Result<(), VmErro
|
||||
if data.closed {
|
||||
return Ok(());
|
||||
}
|
||||
crate::tasks::cancel_owner(cx, window)?;
|
||||
for page in data.pages.clone() {
|
||||
crate::tasks::cancel_owner(cx, page)?;
|
||||
unregister_page(cx, window, page)?;
|
||||
}
|
||||
data = cx
|
||||
|
||||
Reference in New Issue
Block a user