Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
582 lines (540 loc) · 21.1 KB
/
Copy pathmod.rs
File metadata and controls
582 lines (540 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! End-to-end scenario shared by the official plugin SDKs (`sdk/node`,
//! `sdk/java`), run against Rust Core through the same JSON commands a host
//! sends. The plugin backend scenario of `sdk/rust` is in `backend.rs`.
//!
//! Each SDK's sample backend is launched exactly as a host launches a build
//! provider: Core validates its manifest and expands the launch plan, the
//! runtime version is checked, and `lsp.startServer` starts it. The scenario
//! then drives the typed build requests, a multi-step plugin function with
//! progress, a plugin failure, cancellation of a running tool, runtime
//! registration, and state recovery across a restart. Both samples answer it
//! identically, which keeps the SDKs' behaviour aligned.
//!
//! These files live in lithe-plugin-docs. `scripts/sdk-e2e.mjs` copies them
//! into `rust/lithe-core/tests/` of a Lithe checkout at the pinned commit and
//! runs them there; `LITHE_PLUGIN_SDK_ROOT` names the lithe-plugin-docs
//! checkout that holds the samples.
// Each test binary includes this module and uses only the helpers its SDK needs.
#![allow(dead_code)]
pub mod backend;
pub mod native_build;
pub mod vcs;
use lithe_core::execute_json;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
const BUILD_SYSTEM: &str = "sample";
/// Bound for any single wait; a broken backend fails here instead of in CI.
const WAIT: Duration = Duration::from_secs(20);
fn core(command: &str, payload: Value) -> Value {
let request = json!({ "id": format!("sdk-{command}"), "command": command, "payload": payload });
let response: Value = serde_json::from_str(&execute_json(&request.to_string()))
.expect("Core response should be JSON");
assert_eq!(response["ok"], true, "{command} failed: {response}");
response["data"].clone()
}
/// The lithe-plugin-docs checkout named by `LITHE_PLUGIN_SDK_ROOT`.
fn repository_root() -> PathBuf {
let root = std::env::var_os("LITHE_PLUGIN_SDK_ROOT")
.expect("set LITHE_PLUGIN_SDK_ROOT to the lithe-plugin-docs checkout");
PathBuf::from(root)
.canonicalize()
.expect("lithe-plugin-docs checkout")
}
/// Every file of a directory with its contents, to prove the package is unchanged.
fn listing(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
let mut files = BTreeMap::new();
let mut pending = vec![root.to_path_buf()];
while let Some(directory) = pending.pop() {
for entry in fs::read_dir(&directory).expect("readable directory") {
let path = entry.expect("directory entry").path();
if path.is_dir() {
pending.push(path);
} else {
let contents = fs::read(&path).expect("readable file");
files.insert(path.strip_prefix(root).unwrap().to_path_buf(), contents);
}
}
}
files
}
/// Temporary workspace and host state directories, removed even when an
/// assertion fails.
struct Fixture {
root: PathBuf,
}
impl Fixture {
fn new(label: &str) -> Self {
let root =
std::env::temp_dir().join(format!("lithe-plugin-sdk-{label}-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).expect("fixture directory");
// The backend sees canonical paths (macOS /var is /private/var).
Self {
root: root.canonicalize().expect("fixture path"),
}
}
fn workspace(&self) -> PathBuf {
self.root.join("workspace")
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}
/// One running backend session. Dropping it stops the process and removes
/// the session, so a failed assertion leaves no backend behind.
struct Session {
id: String,
plugin_id: String,
events: Vec<Value>,
}
impl Session {
fn start(plugin_id: &str, executable: &str, arguments: &[Value], workspace: &Path) -> Self {
Self::start_provider(
&format!("buildProvider:{plugin_id}:{BUILD_SYSTEM}"),
plugin_id,
executable,
arguments,
workspace,
)
}
/// Starts a plugin-owned session under the host's provider ID.
fn start_provider(
provider_id: &str,
plugin_id: &str,
executable: &str,
arguments: &[Value],
workspace: &Path,
) -> Self {
let started = core(
"lsp.startServer",
json!({
"providerId": provider_id,
"pluginId": plugin_id,
"executablePath": executable,
"arguments": arguments,
// Directory URI with a trailing slash, as the macOS host sends it.
"rootUri": format!("file://{}/", workspace.display()),
"workingDirectory": workspace,
"initializeTimeoutMilliseconds": WAIT.as_millis() as u64,
"requestTimeoutMilliseconds": WAIT.as_millis() as u64,
"shutdownTimeoutMilliseconds": 5000,
}),
);
let mut session = Self {
id: started["sessionId"]
.as_str()
.expect("session ID")
.to_string(),
plugin_id: plugin_id.to_string(),
events: Vec::new(),
};
session.await_event("the session to become ready", |event| {
event["type"] == "stateChanged" && event["state"] == "ready"
});
session
}
/// Waits for the first event, already received or new, that `matches`.
fn await_event(&mut self, description: &str, matches: impl Fn(&Value) -> bool) -> Value {
let deadline = Instant::now() + WAIT;
loop {
if let Some(event) = self.events.iter().find(|event| matches(event)) {
return event.clone();
}
let remaining = deadline.saturating_duration_since(Instant::now());
assert!(
!remaining.is_zero(),
"timed out waiting for {description}; events: {:#?}",
self.events
);
let drained = core(
"lsp.waitEvents",
json!({ "sessionId": self.id, "timeoutMilliseconds": remaining.as_millis().min(1000) as u64 }),
);
self.events
.extend(drained["events"].as_array().cloned().unwrap_or_default());
}
}
fn completion(&mut self, operation: &str) -> Value {
self.await_event(&format!("operation {operation} to end"), |event| {
// Every terminal outcome, cancellation included, is one requestCompleted.
event["operationId"] == operation && event["type"] == "requestCompleted"
})
}
fn invoke(&mut self, operation: &str, function: &str, params: Value) {
core(
"lsp.functionRequest",
json!({
"sessionId": self.id,
"operationId": operation,
"function": { "pluginID": self.plugin_id, "functionID": function },
"params": params,
}),
);
}
fn call(&mut self, operation: &str, function: &str, params: Value) -> Value {
self.invoke(operation, function, params);
self.completion(operation)
}
/// The registry after the latest `functionsChanged` event.
fn functions(&mut self) -> Vec<String> {
let latest = self
.events
.iter()
.rev()
.find(|event| event["type"] == "functionsChanged")
.expect("a functionsChanged event");
serde_json::from_value(latest["result"]["functions"].clone()).expect("function IDs")
}
fn send_build_request(&mut self, operation: &str, plan: &Value) {
core(
"lsp.buildRequest",
json!({
"sessionId": self.id,
"operationId": operation,
"method": plan["provider"]["method"],
"params": plan["provider"]["params"],
}),
);
}
fn build_request(&mut self, operation: &str, plan: &Value) -> Value {
self.send_build_request(operation, plan);
let completed = self.completion(operation);
assert!(completed.get("error").is_none(), "{completed}");
completed["result"]["value"].clone()
}
fn stop(&mut self) {
core("lsp.stopServer", json!({ "sessionId": self.id }));
self.await_event("the backend to stop", |event| {
event["type"] == "stateChanged" && event["state"] == "stopped"
});
}
}
impl Drop for Session {
fn drop(&mut self) {
let request = json!({ "id": "sdk-cleanup", "command": "lsp.stopServer", "payload": { "sessionId": self.id } });
let _ = execute_json(&request.to_string());
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
let destroy = json!({ "id": "sdk-cleanup", "command": "lsp.destroyServer", "payload": { "sessionId": self.id } });
let response: Value =
serde_json::from_str(&execute_json(&destroy.to_string())).unwrap_or(Value::Null);
if response["ok"] == true {
return;
}
let wait = json!({ "id": "sdk-cleanup", "command": "lsp.waitEvents", "payload": { "sessionId": self.id, "timeoutMilliseconds": 200 } });
let _ = execute_json(&wait.to_string());
}
}
}
#[cfg(unix)]
fn is_alive(pid: u32) -> bool {
Command::new("kill")
.args(["-0", &pid.to_string()])
.status()
.is_ok_and(|status| status.success())
}
/// One SDK's sample backend, packaged as a host installs it.
pub struct Sample {
/// `launch.tool` of the sample's provider: `node` or `java`.
pub tool: &'static str,
/// The runtime executable the host would resolve for that tool.
pub runtime: String,
/// The installed plugin package: `plugin.json` and the launch entry.
pub package: PathBuf,
/// Node.js, which runs the sample workspace's build tools for both SDKs.
pub node: String,
}
/// Node.js from `LITHE_PLUGIN_SDK_NODE`, or `None` with a skip notice.
pub fn node_from_environment(test: &str) -> Option<String> {
let Some(node) = std::env::var_os("LITHE_PLUGIN_SDK_NODE") else {
eprintln!("skipped: set LITHE_PLUGIN_SDK_NODE to run {test}");
return None;
};
Some(node.into_string().expect("UTF-8 Node.js path"))
}
pub fn repository_path(relative: &str) -> PathBuf {
repository_root().join(relative)
}
/// Copies `files` (package-relative destination, source) into a fresh package
/// directory under the system temporary directory, removed on drop.
pub struct TemporaryPackage {
pub root: PathBuf,
}
impl TemporaryPackage {
pub fn new(label: &str, files: &[(&str, PathBuf)]) -> Self {
let root = std::env::temp_dir().join(format!(
"lithe-plugin-sdk-package-{label}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
for (destination, source) in files {
let target = root.join(destination);
fs::create_dir_all(target.parent().expect("package file parent"))
.expect("package directory");
fs::copy(source, &target)
.unwrap_or_else(|error| panic!("copy {}: {error}", source.display()));
}
Self {
root: root.canonicalize().expect("package path"),
}
}
}
impl Drop for TemporaryPackage {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}
/// Runs the shared scenario against `sample`.
pub fn run_sample_scenario(sample: &Sample) {
let package = &sample.package;
let node = &sample.node;
let runtime = &sample.runtime;
let manifest: Value =
serde_json::from_slice(&fs::read(package.join("plugin.json")).expect("sample manifest"))
.expect("sample manifest JSON");
let plugin_id = manifest["id"].as_str().expect("plugin ID").to_string();
let package_before = listing(&package);
// The manifest passes the same validation as an installed plugin.
let validated = core(
"plugins.declarative.validate",
json!({ "manifest": manifest }),
);
assert_eq!(validated["status"], "ok", "{validated}");
let fixture = Fixture::new(sample.tool);
let workspace = fixture.workspace();
for project in ["app", "broken", "slow"] {
fs::create_dir_all(workspace.join(project)).expect("project directory");
}
let slow_pid = workspace.join("slow/slow.pid");
fs::write(
workspace.join("lithe-sample.json"),
json!({
"projects": [
{
"name": "app", "path": "app",
"build": [node, "-e", "console.log('built app')"],
"dependencies": [{ "name": "left-pad", "version": "1.3.0" }]
},
{ "name": "broken", "path": "broken", "build": [node, "-e", "process.exit(2)"] },
{
"name": "slow", "path": "slow",
"build": [node, "-e", "require('fs').writeFileSync('slow.pid', String(process.pid)); setInterval(() => {}, 1000)"]
}
]
})
.to_string(),
)
.expect("workspace file");
// The host expands the launch plan and checks the runtime it found.
let plan = core(
"plugins.declarative.languageServerLaunchPlan",
json!({
"manifest": manifest,
"buildSystemID": BUILD_SYSTEM,
"request": {
"pluginDirectory": package,
"stateDirectory": fixture.root.join("state"),
"workspaceStateDirectory": fixture.root.join("workspace-state"),
"architecture": if cfg!(target_arch = "aarch64") { "arm64" } else { "x86_64" },
}
}),
);
assert_eq!(plan["status"], "ok", "{plan}");
let plan = &plan["plan"];
assert_eq!(plan["launch"]["tool"], sample.tool);
let version = Command::new(runtime)
.args(
plan["launch"]["versionArguments"]
.as_array()
.expect("version probe")
.iter()
.map(|argument| argument.as_str().unwrap()),
)
.output()
.expect("runtime version probe");
// Hosts capture stderr with stdout: `java -version` prints to stderr.
let output = format!(
"{}{}",
String::from_utf8_lossy(&version.stdout),
String::from_utf8_lossy(&version.stderr)
);
let check = core(
"plugins.declarative.checkRuntimeVersion",
json!({
"tool": sample.tool,
"minimumVersion": plan["launch"]["minimumVersion"],
"output": output,
}),
);
assert_eq!(check["check"]["satisfied"], true, "{check}");
for directory in plan["requiredDirectories"].as_array().unwrap() {
let path = match directory.as_str() {
Some("state") => fixture.root.join("state"),
_ => fixture.root.join("workspace-state"),
};
fs::create_dir_all(path).expect("host state directory");
}
let arguments = plan["arguments"].as_array().unwrap().clone();
let mut session = Session::start(&plugin_id, runtime, &arguments, &workspace);
assert_eq!(session.functions(), ["snapshot.read", "workspace.build"]);
// Typed build requests: Core plans them and decodes the answers.
let build = |operation: &str, request: Value| {
core(
operation,
json!({ "manifest": manifest, "buildSystemID": BUILD_SYSTEM, "request": request }),
)
};
let model_plan = build("build.modelPlan", json!({ "root": "." }))["plan"].clone();
assert_eq!(model_plan["provider"]["method"], "lithe/build/model");
let model_result = session.build_request("model", &model_plan);
let model = build(
"build.decodeModel",
json!({ "workspaceRoot": workspace, "root": ".", "result": model_result }),
);
let names: Vec<_> = model["model"]["projects"]
.as_array()
.expect("decoded projects")
.iter()
.map(|project| project["name"].as_str().unwrap().to_string())
.collect();
assert_eq!(names, ["app", "broken", "slow"], "{model}");
let dependency_plan = build(
"build.dependencyPlan",
json!({ "root": ".", "project": { "name": "app", "path": "app" } }),
)["plan"]
.clone();
let dependencies_result = session.build_request("dependencies", &dependency_plan);
let dependencies = build(
"build.decodeDependencies",
json!({ "workspaceRoot": workspace, "root": ".", "project": "app", "result": dependencies_result }),
);
assert_eq!(
dependencies["dependencies"]["dependencies"][0]["name"], "left-pad",
"{dependencies}"
);
// A multi-step function: prepare, run the tool, record a snapshot.
let built = session.call(
"build-app",
"workspace.build",
json!({ "projects": ["app"] }),
);
assert_eq!(
built["result"]["value"],
json!({ "generation": 1, "status": "succeeded", "projects": [{ "name": "app", "exitCode": 0 }] }),
"{built}"
);
let progress: Vec<_> = session
.events
.iter()
.filter(|event| event["type"] == "requestProgress" && event["operationId"] == "build-app")
.map(|event| event["result"]["message"].clone())
.collect();
assert_eq!(progress, ["Preparing", "Building app", "Done"]);
// The backend registered snapshot.clear once a snapshot existed.
session.await_event("snapshot.clear to be registered", |event| {
event["type"] == "functionsChanged"
&& event["result"]["functions"]
.as_array()
.is_some_and(|functions| functions.contains(&json!("snapshot.clear")))
});
// A plugin failure keeps Lithe's stable code and forwards the plugin's own.
let failed = session.call(
"build-broken",
"workspace.build",
json!({ "projects": ["broken"] }),
);
assert_eq!(
failed["error"]["code"], "plugin.function.failed",
"{failed}"
);
assert_eq!(failed["error"]["pluginErrorCode"], "sample.buildFailed");
// Cancelling a running build ends the tool the backend started.
session.invoke(
"build-slow",
"workspace.build",
json!({ "projects": ["slow"] }),
);
let deadline = Instant::now() + WAIT;
let pid = loop {
if let Some(pid) = fs::read_to_string(&slow_pid)
.ok()
.and_then(|text| text.trim().parse::<u32>().ok())
{
break pid;
}
assert!(Instant::now() < deadline, "the slow tool never started");
session.events.extend(
core(
"lsp.waitEvents",
json!({ "sessionId": session.id, "timeoutMilliseconds": 50 }),
)["events"]
.as_array()
.cloned()
.unwrap_or_default(),
);
};
core(
"lsp.cancelOperation",
json!({ "sessionId": session.id, "operationId": "build-slow" }),
);
assert_eq!(
session.completion("build-slow")["error"]["code"],
"requestCancelled"
);
#[cfg(unix)]
{
let deadline = Instant::now() + WAIT;
while is_alive(pid) {
assert!(
Instant::now() < deadline,
"the cancelled tool {pid} is still running"
);
// test-stability: allow(rust-real-sleep) reason: the cancelled tool is a separate OS process that offers no notification channel to the test; the deadline above bounds the loop.
std::thread::sleep(Duration::from_millis(20));
}
}
#[cfg(not(unix))]
let _ = pid;
// State survives a restart: the new process reads the recorded snapshot.
session.stop();
drop(session);
let mut restarted = Session::start(&plugin_id, runtime, &arguments, &workspace);
restarted.await_event("snapshot.clear to be offered again", |event| {
event["type"] == "functionsChanged"
&& event["result"]["functions"]
.as_array()
.is_some_and(|functions| functions.contains(&json!("snapshot.clear")))
});
let snapshot = restarted.call("read", "snapshot.read", json!({}));
assert_eq!(snapshot["result"]["value"]["generation"], 2, "{snapshot}");
assert_eq!(snapshot["result"]["value"]["status"], "failed");
assert_eq!(
restarted.call("clear", "snapshot.clear", json!({}))["result"]["value"],
Value::Null
);
assert_eq!(
restarted.call("read-again", "snapshot.read", json!({}))["result"]["value"],
Value::Null
);
restarted.stop();
drop(restarted);
// The backend wrote only to the host's state directory, never the package.
assert!(
listing(&package) == package_before,
"the plugin package changed at runtime"
);
let state: Vec<_> = fs::read_dir(fixture.root.join("workspace-state"))
.expect("workspace state directory")
.map(|entry| entry.unwrap().file_name())
.collect();
assert!(
state.is_empty(),
"cleared state left files behind: {state:?}"
);
}