M1.3: engine workspace, file and buffer commands, event stream
State holds the open project (VFS project, watcher, watched directories)
and versioned buffers. New commands: project.open/close/children,
file.open/save/saveAll, buffer.get/edit/close. buffer.edit takes UTF-16
change sets based on a version and fails with the new stale_version code;
closing dirty buffers or projects without force fails with
unsaved_changes. Commands queue events (projectOpened, treeChanged,
bufferChanged, dirtyChanged, fileChangedOnDisk, ...) that the engine
returns in Outcome.events; Engine::pump_vfs maps changes on disk to
events and reloads clean buffers. project.children watches listed
directories, capped at 256 native / 32 polling, least recently listed
dropped first.
Control channel: events.subscribe streams {"event": ...} lines, with
bounded per-subscriber queues (lutra_control::Subscribers) and method docs
in methods.rs. testkit's EngineBackend and the desktop Host implement the
new Backend::subscribe. Verified with 14 engine integration tests, a TCP
events test and the running app over the control channel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a63ab4ac45
commit
f1976c7d67
30 changed files with 2235 additions and 46 deletions
445
crates/engine/tests/workspace.rs
Normal file
445
crates/engine/tests/workspace.rs
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
//! Workspace commands and events against real folders in temp directories.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::panic,
|
||||
clippy::indexing_slicing
|
||||
)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_engine::{Command, CommandSpec, Engine, EngineError, Event, Outcome, State};
|
||||
use serde_json::{Value, json};
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// A temp folder with a few files, opened in a fresh engine.
|
||||
fn open_project(files: &[(&str, &[u8])]) -> (TempDir, Engine, Vec<Event>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (path, bytes) in files {
|
||||
let abs = dir.path().join(path);
|
||||
fs::create_dir_all(abs.parent().unwrap()).unwrap();
|
||||
fs::write(abs, bytes).unwrap();
|
||||
}
|
||||
let mut engine = Engine::new().unwrap();
|
||||
let out = engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
(dir, engine, out.events)
|
||||
}
|
||||
|
||||
fn run(engine: &mut Engine, command: &str, params: Value) -> Outcome {
|
||||
engine
|
||||
.execute(command, params)
|
||||
.unwrap_or_else(|e| panic!("{command} failed: {e}"))
|
||||
}
|
||||
|
||||
fn open_file(engine: &mut Engine, path: &str) -> (u64, Value) {
|
||||
let out = run(engine, "file.open", json!({"path": path}));
|
||||
(out.value["id"].as_u64().unwrap(), out.value)
|
||||
}
|
||||
|
||||
/// Pumps VFS events until `pred` matches one, or fails after five seconds.
|
||||
fn wait_for(engine: &mut Engine, pred: impl Fn(&Event) -> bool) -> Vec<Event> {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut seen = Vec::new();
|
||||
while Instant::now() < deadline {
|
||||
let events = engine.pump_vfs().unwrap();
|
||||
let hit = events.iter().any(&pred);
|
||||
seen.extend(events);
|
||||
if hit {
|
||||
return seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
panic!("event not seen within 5 s; got {seen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_commands_are_disabled_without_a_project() {
|
||||
let mut engine = Engine::new().unwrap();
|
||||
for (command, params) in [
|
||||
("project.children", json!({})),
|
||||
("project.close", json!({})),
|
||||
("file.open", json!({"path": "a.php"})),
|
||||
("file.save", json!({"id": 1})),
|
||||
("file.saveAll", Value::Null),
|
||||
("buffer.get", json!({"id": 1})),
|
||||
(
|
||||
"buffer.edit",
|
||||
json!({"id": 1, "baseVersion": 1, "edits": []}),
|
||||
),
|
||||
("buffer.close", json!({"id": 1})),
|
||||
] {
|
||||
let err = engine.execute(command, params).unwrap_err();
|
||||
assert_eq!(err.code(), "disabled", "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_missing_folder_fails_and_keeps_state() {
|
||||
let mut engine = Engine::new().unwrap();
|
||||
let err = engine
|
||||
.execute("project.open", json!({"path": "/definitely/not/here"}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "failed");
|
||||
assert!(!engine.state().has_project());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_lists_children_and_reports_the_project() {
|
||||
let (dir, mut engine, events) = open_project(&[
|
||||
("src/Kernel.php", b"<?php\n"),
|
||||
("b.txt", b"b"),
|
||||
("A.txt", b"a"),
|
||||
(".gitignore", b"b.txt\n"),
|
||||
("vendor/x/y.php", b"<?php\n"),
|
||||
]);
|
||||
let root = fs::canonicalize(dir.path()).unwrap();
|
||||
assert!(matches!(&events[0], Event::ProjectOpened { name, .. }
|
||||
if *name == root.file_name().unwrap().to_string_lossy()));
|
||||
|
||||
let out = run(&mut engine, "project.children", json!({}));
|
||||
let names: Vec<&str> = out.value["entries"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e["name"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, ["src", "vendor", ".gitignore", "A.txt", "b.txt"]);
|
||||
let entries = out.value["entries"].as_array().unwrap();
|
||||
let by_name = |n: &str| entries.iter().find(|e| e["name"] == n).unwrap();
|
||||
assert_eq!(by_name("b.txt")["ignored"], true);
|
||||
assert_eq!(by_name("vendor")["role"], "library");
|
||||
assert_eq!(by_name("src")["kind"], "directory");
|
||||
|
||||
let out = run(&mut engine, "project.children", json!({"dir": "src"}));
|
||||
assert_eq!(out.value["entries"][0]["path"], "src/Kernel.php");
|
||||
let err = engine
|
||||
.execute("project.children", json!({"dir": "../.."}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_save_and_dirty_state() {
|
||||
let (dir, mut engine, _) = open_project(&[("a.php", "<?php\n// 😀 x\n".as_bytes())]);
|
||||
let (id, opened) = open_file(&mut engine, "a.php");
|
||||
assert_eq!(opened["version"], 1);
|
||||
assert_eq!(opened["dirty"], false);
|
||||
assert_eq!(opened["lineEnding"], "lf");
|
||||
|
||||
let (again, _) = open_file(&mut engine, "a.php");
|
||||
assert_eq!(again, id, "opening twice returns the same buffer");
|
||||
|
||||
let after_emoji = "<?php\n// 😀".encode_utf16().count();
|
||||
let out = run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [
|
||||
{"from": 0, "to": 5, "insert": "<?PHP"},
|
||||
{"from": after_emoji, "to": after_emoji + 2, "insert": "!"}
|
||||
]}),
|
||||
);
|
||||
assert_eq!(out.value, json!({"id": id, "version": 2, "dirty": true}));
|
||||
assert_eq!(
|
||||
out.events,
|
||||
vec![
|
||||
Event::BufferChanged { id, version: 2 },
|
||||
Event::DirtyChanged { id, dirty: true }
|
||||
]
|
||||
);
|
||||
let text = run(&mut engine, "buffer.get", json!({"id": id})).value["text"].clone();
|
||||
assert_eq!(text, "<?PHP\n// 😀!\n");
|
||||
|
||||
let out = run(&mut engine, "file.save", json!({"id": id}));
|
||||
assert_eq!(out.value["version"], 2);
|
||||
assert_eq!(out.events, vec![Event::DirtyChanged { id, dirty: false }]);
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
||||
"<?PHP\n// 😀!\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_and_invalid_edits_are_rejected_without_change() {
|
||||
let (_dir, mut engine, _) = open_project(&[("a.php", "a😀b".as_bytes())]);
|
||||
let (id, _) = open_file(&mut engine, "a.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}),
|
||||
);
|
||||
let err = engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "y"}]}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "stale_version");
|
||||
assert_eq!(
|
||||
err,
|
||||
EngineError::StaleVersion {
|
||||
id,
|
||||
base: 1,
|
||||
current: 2
|
||||
}
|
||||
);
|
||||
for edits in [
|
||||
json!([{"from": 3, "to": 3, "insert": "z"}]),
|
||||
json!([{"from": 0, "to": 99, "insert": ""}]),
|
||||
json!([{"from": 0, "to": 2}, {"from": 1, "to": 3}]),
|
||||
] {
|
||||
let err = engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 2, "edits": edits}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "invalid_params", "{edits}");
|
||||
}
|
||||
let got = run(&mut engine, "buffer.get", json!({"id": id})).value;
|
||||
assert_eq!(got["text"], "xa😀b");
|
||||
assert_eq!(got["version"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_endings_and_bom_survive_a_save() {
|
||||
let mut bytes = vec![0xef, 0xbb, 0xbf];
|
||||
bytes.extend_from_slice(b"a\r\nb\r\n");
|
||||
let (dir, mut engine, _) = open_project(&[("w.php", &bytes)]);
|
||||
let (id, opened) = open_file(&mut engine, "w.php");
|
||||
assert_eq!(opened["lineEnding"], "crlf");
|
||||
assert_eq!(opened["text"], "a\r\nb\r\n");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 6, "insert": "c\n"}]}),
|
||||
);
|
||||
run(&mut engine, "file.save", json!({"id": id}));
|
||||
let mut expected = vec![0xef, 0xbb, 0xbf];
|
||||
expected.extend_from_slice(b"a\r\nb\r\nc\r\n");
|
||||
assert_eq!(fs::read(dir.path().join("w.php")).unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_dirty_buffers_needs_force() {
|
||||
let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("b.php", b"b")]);
|
||||
let (a, _) = open_file(&mut engine, "a.php");
|
||||
let (b, _) = open_file(&mut engine, "b.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": a, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "!"}]}),
|
||||
);
|
||||
let err = engine
|
||||
.execute("buffer.close", json!({"id": a}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "unsaved_changes");
|
||||
let out = run(&mut engine, "buffer.close", json!({"id": b}));
|
||||
assert_eq!(out.events, vec![Event::BufferClosed { id: b }]);
|
||||
|
||||
let err = engine.execute("project.close", json!({})).unwrap_err();
|
||||
assert_eq!(err.code(), "unsaved_changes");
|
||||
assert!(engine.state().has_project());
|
||||
let out = run(&mut engine, "project.close", json!({"force": true}));
|
||||
assert_eq!(
|
||||
out.events,
|
||||
vec![Event::BufferClosed { id: a }, Event::ProjectClosed]
|
||||
);
|
||||
assert!(!engine.state().has_project());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_all_saves_every_dirty_buffer() {
|
||||
let (dir, mut engine, _) = open_project(&[("a.php", b"a"), ("b.php", b"b")]);
|
||||
let (a, _) = open_file(&mut engine, "a.php");
|
||||
let (b, _) = open_file(&mut engine, "b.php");
|
||||
for id in [a, b] {
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": ">"}]}),
|
||||
);
|
||||
}
|
||||
let out = run(&mut engine, "file.saveAll", Value::Null);
|
||||
assert_eq!(out.value, json!({"saved": [a, b], "failed": []}));
|
||||
assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_paths_must_be_inside_the_project() {
|
||||
let (dir, mut engine, _) = open_project(&[("a.php", b"a")]);
|
||||
let inside = fs::canonicalize(dir.path()).unwrap().join("a.php");
|
||||
let (id, value) = open_file(&mut engine, inside.to_str().unwrap());
|
||||
assert_eq!(value["path"], "a.php");
|
||||
assert!(id > 0);
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
fs::write(other.path().join("x.php"), "x").unwrap();
|
||||
let outside = fs::canonicalize(other.path()).unwrap().join("x.php");
|
||||
let err = engine
|
||||
.execute("file.open", json!({"path": outside}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "failed");
|
||||
let err = engine
|
||||
.execute("file.open", json!({"path": "../x.php"}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_buffers_reload_and_dirty_ones_report_conflicts() {
|
||||
let (dir, mut engine, _) = open_project(&[("clean.php", b"one"), ("dirty.php", b"one")]);
|
||||
let (clean, _) = open_file(&mut engine, "clean.php");
|
||||
let (dirty, _) = open_file(&mut engine, "dirty.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": dirty, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "mine "}]}),
|
||||
);
|
||||
fs::write(dir.path().join("clean.php"), "two, longer").unwrap();
|
||||
fs::write(dir.path().join("dirty.php"), "theirs, longer").unwrap();
|
||||
|
||||
let mut events = wait_for(
|
||||
&mut engine,
|
||||
|e| matches!(e, Event::BufferChanged { id, .. } if *id == clean),
|
||||
);
|
||||
if !events
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty))
|
||||
{
|
||||
events = wait_for(
|
||||
&mut engine,
|
||||
|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.all(|e| !matches!(e, Event::FileChangedOnDisk { id, .. } if *id == clean))
|
||||
);
|
||||
let clean_now = run(&mut engine, "buffer.get", json!({"id": clean})).value;
|
||||
assert_eq!(clean_now["text"], "two, longer");
|
||||
assert_eq!(clean_now["dirty"], false);
|
||||
let dirty_now = run(&mut engine, "buffer.get", json!({"id": dirty})).value;
|
||||
assert_eq!(dirty_now["text"], "mine one");
|
||||
assert_eq!(dirty_now["dirty"], true);
|
||||
|
||||
fs::remove_file(dir.path().join("clean.php")).unwrap();
|
||||
wait_for(
|
||||
&mut engine,
|
||||
|e| matches!(e, Event::FileChangedOnDisk { id, removed: true, .. } if *id == clean),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_saves_do_not_reload() {
|
||||
let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]);
|
||||
let (id, _) = open_file(&mut engine, "a.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "b"}]}),
|
||||
);
|
||||
run(&mut engine, "file.save", json!({"id": id}));
|
||||
let deadline = Instant::now() + Duration::from_millis(600);
|
||||
while Instant::now() < deadline {
|
||||
let events = engine.pump_vfs().unwrap();
|
||||
assert!(
|
||||
!events.iter().any(|e| matches!(
|
||||
e,
|
||||
Event::BufferChanged { .. } | Event::FileChangedOnDisk { .. }
|
||||
)),
|
||||
"{events:?}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
assert_eq!(
|
||||
run(&mut engine, "buffer.get", json!({"id": id})).value["version"],
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_changes_are_reported_for_listed_directories() {
|
||||
let (dir, mut engine, _) = open_project(&[("src/a.php", b"a")]);
|
||||
run(&mut engine, "project.children", json!({"dir": "src"}));
|
||||
fs::write(dir.path().join("new.php"), "n").unwrap();
|
||||
wait_for(
|
||||
&mut engine,
|
||||
|e| matches!(e, Event::TreeChanged { dir } if dir.is_empty()),
|
||||
);
|
||||
fs::write(dir.path().join("src").join("b.php"), "b").unwrap();
|
||||
wait_for(
|
||||
&mut engine,
|
||||
|e| matches!(e, Event::TreeChanged { dir } if dir == "src"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watched_directories_are_capped_least_recently_listed_first() {
|
||||
let (dir, mut engine, _) = open_project(&[]);
|
||||
let limit = engine.state().project.as_ref().unwrap().watch_limit();
|
||||
assert!(limit > 0, "the watcher should start on a temp dir");
|
||||
let count = limit + 5;
|
||||
for n in 0..count {
|
||||
fs::create_dir(dir.path().join(format!("d{n:04}"))).unwrap();
|
||||
}
|
||||
for n in 0..count {
|
||||
run(
|
||||
&mut engine,
|
||||
"project.children",
|
||||
json!({"dir": format!("d{n:04}")}),
|
||||
);
|
||||
}
|
||||
run(&mut engine, "project.children", json!({"dir": "d0000"}));
|
||||
let watched = engine.state().project.as_ref().unwrap().watched_dirs();
|
||||
assert_eq!(watched.len(), limit);
|
||||
assert_eq!(watched.last().unwrap(), Path::new("d0000"));
|
||||
assert!(!watched.iter().any(|d| d == Path::new("d0001")));
|
||||
assert!(!watched.iter().any(|d| d == Path::new("d0005")));
|
||||
assert!(watched.iter().any(|d| d == Path::new("d0006")));
|
||||
}
|
||||
|
||||
/// A command that reads the state and then panics on an index.
|
||||
struct PanicsMidway;
|
||||
|
||||
impl Command for PanicsMidway {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "test.panicsMidway",
|
||||
label: "Panics",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let _ = state.buffers.len();
|
||||
let empty: Vec<u8> = Vec::new();
|
||||
Ok(Outcome::value(json!(empty[3])))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_command_leaves_open_buffers_intact() {
|
||||
let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]);
|
||||
engine.register(Box::new(PanicsMidway)).unwrap();
|
||||
let (id, _) = open_file(&mut engine, "a.php");
|
||||
run(
|
||||
&mut engine,
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": " unsaved"}]}),
|
||||
);
|
||||
let err = engine
|
||||
.execute("test.panicsMidway", Value::Null)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "internal");
|
||||
let got = run(&mut engine, "buffer.get", json!({"id": id})).value;
|
||||
assert_eq!(got["text"], "a unsaved");
|
||||
assert_eq!(got["dirty"], true);
|
||||
run(&mut engine, "file.save", json!({"id": id}));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue