diff --git a/README.md b/README.md index e4daa68..0e18b5e 100644 --- a/README.md +++ b/README.md @@ -471,9 +471,8 @@ 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) +pending for later polls. Timers and asynchronous UTF-8 file reads use the same task lifecycle. +Network providers, await/coroutines and interrupting a blocked native callback remain unimplemented. See [owned-tasks.endor](examples/owned-tasks.endor) for real Endor code and native buttons. Typed capability methods cannot be shadowed by instance attributes. Aster checks ordinary writes, type attachment and capability declaration before changing state; queries and method invocation reject backing-store conflicts introduced through trusted host access. The render cache subscribes to these method attribute keys and validates dirty Blocks before native dispatch, so direct storage changes cannot silently leave source calls and rendering on different methods. Removing the conflicting attribute restores the instance. Class method overrides and event subscriptions keep their existing APIs. @@ -551,3 +550,8 @@ Layout and paint drivers now prepare one occurrence at a time. Their fixed-size ui.stats().dependencyInvalidations counts observed layout/paint dependency version mismatches. lastInvalidDependency records the phase, object kind/identity and old/current versions without rendering its fields or retaining it. An input changing its globals is an expected invalidation; compare idle document versions before diagnosing a refresh loop. + + +ui.readText(owner,key,path[,callback]) returns an owner-scoped Task and reads a regular UTF-8 file off the VM thread. Paths use native filesystem syntax; absolute paths are recommended. The optional callback takes zero arguments and must return Unit; it runs only on successful read and can use task.result(). Without a callback, poll status then read result from code. result() is available while a success callback is running or after completion (timers return Unit); error() returns an empty String or the provider/callback error. A provider failure marks the task failed and skips its callback without stopping the VM; a source callback failure still stops the shared domain. Owner/key replacement, explicit cancellation, close/reset/VM discard and GC drop the provider lease, remove queued completion and reject late delivery. In-progress OS reads may finish, but cannot deliver after cancellation. Only the owning VM worker updates managed results and rechecks owner/key identity. No VM handles enter provider threads beyond opaque weak identities. + +The lazy shared pool has four threads and a 64-job queue. Each runtime permits 16 outstanding file requests (one temporary replacement reservation), and each read is capped at 1 MiB by metadata plus actual streaming length; non-regular files, non-UTF-8 data and over-limit content fail rather than truncate. These limits do not constitute a full filesystem sandbox. The provider returns text in the same managed Task, not a second application-state store. Network/await support is still separate unfinished work. See examples/async-file.endor; from REPL call reader.read("/absolute/path.txt") to update its actual TextBlock, even when that object is hidden but retained. diff --git a/examples/async-file.endor b/examples/async-file.endor new file mode 100644 index 0000000..44a6add --- /dev/null +++ b/examples/async-file.endor @@ -0,0 +1,22 @@ +class FileReader { + output: TextBlock + problem: TextBlock + status: TextBlock + task: Object + function apply(self: FileReader): Unit { + self.output.text = self.task.result() + } + function read(self: FileReader, path: String): Unit { + self.task = ui.readText(self, "file", path, self.apply) + self.output.text = "" + self.status.bind("text", self.task.status) + self.problem.bind("text", self.task.error) + } +} +output = TextBlock("尚未读取文件") +problem = TextBlock("") +status = TextBlock("") +reader = FileReader(output, problem, status, ui.state(0)) +page = Page() +page.title = "异步文件" +page.render(Column(24,16,TextBlock("在 REPL 调用 reader.read(绝对路径字符串)",2),status,output,problem)) diff --git a/src/README.md b/src/README.md index f46007c..63df238 100644 --- a/src/README.md +++ b/src/README.md @@ -16,7 +16,8 @@ | event_dispatch.rs | Typed Event factory and managed Event/Subscription methods, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver | | protocols.rs | Register typed Visual/EventTarget/Children (including insert)/Presentable managed trait requirements, using canonical signatures and explicit 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 | Typed Task/ui.after methods, managed owner scopes and callbacks, weak timer index, request-key replacement, lifecycle cancellation and budgeted worker delivery | +| io_tasks.rs | Lazy bounded file-provider pool, plain-data mailbox and cancellation leases without managed roots | +| tasks.rs | Typed Task/ui.after/ui.readText/result/error methods, 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, drag gaps/anchors/insertion markers and opaque published Page identities | | window.rs | Typed native Window queries/effects, construction/close, context ownership, ordered Page roots, read-only guards, Page reordering, physical desktop placement and coalesced GUI projections | | vm_sequence.rs | Shared validated call-sequence builder and EXTENDED_ARG-aware same-frame repetition for layout, event and lifecycle work | @@ -206,3 +207,8 @@ Layout and paint drivers now prepare one occurrence at a time. Their fixed-size Presentation dependency diagnostics record a counter and the last invalidated object kind/identity and version transition. ui.stats exposes dependencyInvalidations and lastInvalidDependency without retaining the dependency or rendering its data. These help distinguish expected input invalidation from repeated background refresh. + + +ui.readText(owner,key,path[,callback]) returns an owner-scoped Task and reads a regular UTF-8 file off the VM thread. Paths use native filesystem syntax; absolute paths are recommended. The optional callback takes zero arguments and must return Unit; it runs only on successful read and can use task.result(). Without a callback, poll status then read result from code. result() is available while a success callback is running or after completion (timers return Unit); error() returns an empty String or the provider/callback error. A provider failure marks the task failed and skips its callback without stopping the VM; a source callback failure still stops the shared domain. Owner/key replacement, explicit cancellation, close/reset/VM discard and GC drop the provider lease, remove queued completion and reject late delivery. In-progress OS reads may finish, but cannot deliver after cancellation. Only the owning VM worker updates managed results and rechecks owner/key identity. No VM handles enter provider threads beyond opaque weak identities. + +The lazy shared pool has four threads and a 64-job queue. Each runtime permits 16 outstanding file requests (one temporary replacement reservation), and each read is capped at 1 MiB by metadata plus actual streaming length; non-regular files, non-UTF-8 data and over-limit content fail rather than truncate. These limits do not constitute a full filesystem sandbox. The provider returns text in the same managed Task, not a second application-state store. Network/await support is still separate unfinished work. See examples/async-file.endor; from REPL call reader.read("/absolute/path.txt") to update its actual TextBlock, even when that object is hidden but retained. diff --git a/src/api.rs b/src/api.rs index 2ae5b3a..7c0f00b 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1444,7 +1444,7 @@ 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. +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 support timers and asynchronous text-file reads; network providers and await remain 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. Declared-field construction and set_attr writes are also checked, as described below. Static inference, generic and static effect typing remain pending. @@ -1507,6 +1507,10 @@ Layout and paint drivers now prepare one occurrence at a time. Their fixed-size ui.stats().dependencyInvalidations counts observed layout/paint dependency version mismatches. lastInvalidDependency records the phase, object kind/identity and old/current versions without rendering its fields or retaining it. An input changing its globals is an expected invalidation; compare idle document versions before diagnosing a refresh loop. +ui.readText(owner,key,path[,callback]) returns an owner-scoped Task and reads a regular UTF-8 file off the VM thread. Paths use native filesystem syntax; absolute paths are recommended. The optional callback takes zero arguments and must return Unit; it runs only on successful read and can use task.result(). Without a callback, poll status then read result from code. result() is available while a success callback is running or after completion (timers return Unit); error() returns an empty String or the provider/callback error. A provider failure marks the task failed and skips its callback without stopping the VM; a source callback failure still stops the shared domain. Owner/key replacement, explicit cancellation, close/reset/VM discard and GC drop the provider lease, remove queued completion and reject late delivery. In-progress OS reads may finish, but cannot deliver after cancellation. Only the owning VM worker updates managed results and rechecks owner/key identity. No VM handles enter provider threads beyond opaque weak identities. + +The lazy shared pool has four threads and a 64-job queue. Each runtime permits 16 outstanding file requests (one temporary replacement reservation), and each read is capped at 1 MiB by metadata plus actual streaming length; non-regular files, non-UTF-8 data and over-limit content fail rather than truncate. These limits do not constitute a full filesystem sandbox. The provider returns text in the same managed Task, not a second application-state store. Network/await support is still separate unfinished work. See examples/async-file.endor; from REPL call reader.read("/absolute/path.txt") to update its actual TextBlock, even when that object is hidden but retained. + ## UI host object Positional arguments only: diff --git a/src/endor_host.rs b/src/endor_host.rs index 6755254..4c1fdc3 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -2031,6 +2031,167 @@ page.render(block) ); } + fn with_file_task_input(contents: &str, run: impl FnOnce(&std::path::Path)) { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("tessera-text-task-{}-{id}.txt", std::process::id())); + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let _cleanup = Cleanup(path.clone()); + std::fs::write(&path, contents).unwrap(); + run(&path); + } + fn file_task_source(path: &std::path::Path, tail: &str) -> String { + let path = serde_json::to_string(&path.to_string_lossy()).unwrap(); + format!( + "class Loader {{\n target: TextBlock\n task: Object\n function apply(self: Loader): Unit {{ self.target.text = self.task.result() }}\n}}\ntarget = TextBlock(\"waiting\")\nloader = Loader(target,ui.state(0))\npage = Page()\npage.render(TextBlock(\"target stays hidden\"))\nloader.task = ui.readText(loader,\"read\",{path},loader.apply)\n{tail}" + ) + } + fn file_task_state(session: &mut ReplSession) -> String { + let globals = session.candidate.globals.unwrap(); + let Value::Object(loader) = session + .candidate + .vm + .dict_get(globals, &Value::Text("loader".into())) + .unwrap() + .unwrap() + else { + panic!("loader"); + }; + let Value::Object(task) = session.candidate.vm.get_attr(loader, "task").unwrap() else { + panic!("Task"); + }; + let definition = session + .candidate + .vm + .object_store() + .type_of(task) + .unwrap() + .unwrap(); + let method = session + .candidate + .vm + .object_store() + .lookup_method(definition, "status") + .unwrap() + .unwrap(); + let Value::Text(status) = session + .candidate + .vm + .call(method, &[Value::Object(task)]) + .unwrap() + else { + panic!("status"); + }; + status + } + fn complete_file_task(session: &mut ReplSession) { + for _ in 0..1000 { + session.poll_tasks().unwrap(); + if file_task_state(session) != "pending" { + return; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + panic!("file task did not complete"); + } + #[test] + fn file_task_updates_hidden_object_and_replacement_drops_old_delivery() { + with_file_task_input("old", |old| { + with_file_task_input("new UTF-8 文本", |new| { + let path = serde_json::to_string(&new.to_string_lossy()).unwrap(); + let tail = format!( + "old = loader.task\nloader.task = ui.readText(loader,\"read\",{path},loader.apply)" + ); + let (mut session, _) = + ReplSession::load(&file_task_source(old, &tail), "app.main", 282, 1).unwrap(); + complete_file_task(&mut session); + assert_eq!(file_task_state(&mut session), "completed"); + assert_eq!( + session.execute("target.text", "app.main").unwrap().value, + "\"new UTF-8 文本\"" + ); + assert_eq!( + session.execute("old.status()", "app.main").unwrap().value, + "\"cancelled\"" + ); + assert_eq!( + session + .execute("target.mounts().count", "app.main") + .unwrap() + .value, + "0" + ); + }) + }); + } + #[test] + fn cancelled_file_task_never_runs_callback_and_missing_file_keeps_vm_live() { + with_file_task_input("ignored", |path| { + let (mut cancelled, _) = ReplSession::load( + &file_task_source(path, "loader.task.cancel()"), + "app.main", + 283, + 1, + ) + .unwrap(); + complete_file_task(&mut cancelled); + assert_eq!(file_task_state(&mut cancelled), "cancelled"); + assert_eq!( + cancelled.execute("target.text", "app.main").unwrap().value, + "\"waiting\"" + ); + let missing = path.with_extension("missing"); + let (mut failed, _) = + ReplSession::load(&file_task_source(&missing, ""), "app.main", 284, 1).unwrap(); + complete_file_task(&mut failed); + assert_eq!(file_task_state(&mut failed), "failed"); + assert!(!failed.is_faulted()); + assert_ne!( + failed + .execute("loader.task.error()", "app.main") + .unwrap() + .value, + "\"\"" + ); + assert_eq!( + failed.execute("target.text", "app.main").unwrap().value, + "\"waiting\"" + ); + }); + } + #[test] + fn callback_free_file_task_retains_result_after_completion() { + with_file_task_input("callback free", |path| { + let path = serde_json::to_string(&path.to_string_lossy()).unwrap(); + let source = format!( + "class Holder {{ task: Object }}\nloader = Holder(ui.state(0))\npage = Page()\npage.render(TextBlock(\"file\"))\nloader.task = ui.readText(ui,\"read\",{path})" + ); + let (mut session, _) = ReplSession::load(&source, "app.main", 285, 1).unwrap(); + complete_file_task(&mut session); + assert_eq!(file_task_state(&mut session), "completed"); + assert_eq!( + session + .execute("loader.task.result()", "app.main") + .unwrap() + .value, + "\"callback free\"" + ); + assert_eq!( + session + .execute("loader.task.error()", "app.main") + .unwrap() + .value, + "\"\"" + ); + }); + } + #[test] fn owned_tasks_replace_cancel_and_update_unmounted_objects() { let source = r#"class Action { diff --git a/src/io_tasks.rs b/src/io_tasks.rs index 7ae5c03..0a0d7ce 100644 --- a/src/io_tasks.rs +++ b/src/io_tasks.rs @@ -125,30 +125,27 @@ fn pool() -> Result<&'static SyncSender, &'static str> { .map_err(|_| "file provider unavailable") } fn read_text(path: &str) -> Completion { - let read = || -> Result { - let metadata = std::fs::metadata(path).map_err(|error| error.to_string())?; - if !metadata.is_file() { - return Err("text source must be a regular file".into()); - } - 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() - .map_err(|error| error.to_string())? - .is_file() - { - return Err("text source must be a regular file".into()); - } - let mut bytes = Vec::new(); - file.take(MAX_TEXT as u64 + 1) - .read_to_end(&mut bytes) - .map_err(|error| error.to_string())?; - if bytes.len() > MAX_TEXT { - return Err("text source exceeds 1 MiB".into()); - } - String::from_utf8(bytes).map_err(|_| "text source must be UTF-8".into()) - }; - read() + let metadata = std::fs::metadata(path).map_err(|error| error.to_string())?; + if !metadata.is_file() { + return Err("text source must be a regular file".into()); + } + 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() + .map_err(|error| error.to_string())? + .is_file() + { + return Err("text source must be a regular file".into()); + } + let mut bytes = Vec::new(); + file.take(MAX_TEXT as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() > MAX_TEXT { + return Err("text source exceeds 1 MiB".into()); + } + String::from_utf8(bytes).map_err(|_| "text source must be UTF-8".into()) }