Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4417,6 +4417,15 @@ script file, or a program or interpreter named by a path that is not a file, is

Batch runs are `not_supported` outside Windows.

In a remote workspace (a request carrying `remoteWorkspace`) every
`runConfig.*` command reads and checks the host's files, and process runs are
planned for the host, which is Linux or macOS, so they never get a Windows
interpreter or a batch script even when the client is Windows. The plan's
`executable.path`, `arguments` and `inlineScript.path` are host paths, and
`inlineScriptBase` must name a host temporary directory, so the client starts
the process on the host without translating the plan. A host that cannot be
reached fails the request instead of reporting a file as missing.

`diagnostics.redactText` accepts `text` and returns `redacted` with
credentials, tokens, and home-directory paths replaced by stable placeholders
(`<redacted>` for secrets, `<HOME>` for a macOS/Linux `Users`/`home` path or a
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
fn has_remote_workspace_adapter(command: &str) -> bool {
command.starts_with("git.")
|| command.starts_with("build.")
|| command.starts_with("runConfig.")
|| matches!(
command,
"workspace.repositories"
Expand Down
110 changes: 110 additions & 0 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,116 @@ fn remote_build_detects_host_models_normalizes_diagnostics_and_invalidates_sync(
assert_eq!(std::fs::read_dir(placeholder).unwrap().count(), 0);
}

/// Run configurations of a remote workspace are read from the host, checked
/// against the host's files, and planned with host paths, so the client starts
/// the process on the host without translating the plan.
#[test]
fn remote_run_configurations_resolve_and_plan_against_the_host() {
let host = HostFixture::new();
let root = host.root.join("host");
let placeholder = host.root.join("placeholder");
std::fs::create_dir_all(root.join("scripts")).unwrap();
std::fs::create_dir_all(root.join("web")).unwrap();
std::fs::write(
root.join("scripts/build.sh"),
"#!/bin/bash -e\necho built\n",
)
.unwrap();
super::support::write_run_document(
&root,
".lithe/run/configurations.yaml",
&json!({"version": 2, "configurations": [
{"id": "user:build", "name": "build", "provider": "process.shell",
"confidence": "declared", "cwd": "web",
"extensions": {"process": {"script": "scripts/build.sh"}}},
{"id": "user:inline", "name": "inline", "provider": "process.shell",
"confidence": "declared", "extensions": {"process": {"text": "echo hi\n"}}},
{"id": "user:missing", "name": "missing", "provider": "process.shell",
"confidence": "declared", "extensions": {"process": {"script": "scripts/gone.sh"}}},
]}),
);

let resolved = host.request("runConfig.resolve", json!({"root": placeholder}));
let availability = |id: &str| {
resolved["configurations"]
.as_array()
.unwrap()
.iter()
.find(|entry| entry["id"] == id)
.unwrap_or_else(|| panic!("{id} missing from {resolved}"))["availability"]
.clone()
};
// The documents exist only on the host; a runnable entry carries no
// availability.
assert!(availability("user:build").is_null(), "{resolved}");

// The script and its `#!` line are read on the host; every path in the
// plan is the host's.
let plan = host.request(
"runConfig.createLaunchPlan",
json!({"root": placeholder, "configurationId": "user:build"}),
);
let script = root.join("scripts/build.sh");
assert_eq!(plan["executable"], json!({"path": "/bin/bash"}), "{plan}");
assert_eq!(plan["arguments"], json!(["-e", script]), "{plan}");
assert_eq!(plan["workingDirectory"], "web", "{plan}");

// An inline script goes where the client asked, on the host.
let inline = host.request(
"runConfig.createLaunchPlan",
json!({"root": placeholder, "configurationId": "user:inline",
"inlineScriptBase": "/tmp/lithe-run-x/script"}),
);
assert_eq!(
inline["inlineScript"]["path"], "/tmp/lithe-run-x/script.sh",
"{inline}"
);
assert_eq!(inline["inlineScript"]["content"], "echo hi\n", "{inline}");

// A script missing on the host is refused before anything starts.
let response: Value = serde_json::from_str(&crate::execute_json(
&json!({
"id": test_support::unique_id(), "command": "runConfig.createLaunchPlan",
"remoteWorkspace": {"sessionId": host.id, "localRoot": placeholder, "remoteRoot": root},
"payload": {"root": placeholder, "configurationId": "user:missing"},
})
.to_string(),
))
.unwrap();
assert_eq!(response["ok"], false, "{response}");
assert_eq!(
response["error"]["message"], "Script file was not found",
"{response}"
);

// The editor checks a working directory against the host's folders and
// saves through changes the client applies on the host.
let form = host.request(
"runConfig.editorForm",
json!({"root": placeholder, "configurationId": "user:build"}),
);
let mut values = form["values"].as_object().unwrap().clone();
values.insert("workingDirectory".into(), json!("nowhere"));
let refused = host.request(
"runConfig.saveConfiguration",
json!({"root": placeholder, "provider": "process.shell",
"configurationId": "user:build", "values": values}),
);
assert_eq!(
refused["errors"],
json!([{"field": "workingDirectory", "code": "notFound"}]),
"{refused}"
);
values.insert("workingDirectory".into(), json!("scripts"));
let saved = host.request(
"runConfig.saveConfiguration",
json!({"root": placeholder, "provider": "process.shell",
"configurationId": "user:build", "values": values}),
);
assert_eq!(saved["status"], "saved", "{saved}");
assert_eq!(std::fs::read_dir(placeholder).unwrap().count(), 0);
}

/// A remote root opened through a host symbolic link resolves outside the
/// local placeholder; the empty-root boundary must ask the host, not the
/// unmaterialized local projection, before scanning.
Expand Down
14 changes: 13 additions & 1 deletion rust/crates/execution/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use lithe_platform::paths::{
};
use lithe_platform::Platform;
use lithe_protocol::{CoreError, ErrorCode};
use lithe_workspace::fs;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

mod arrangement;
Expand All @@ -34,6 +34,18 @@ mod resolve;
mod storage;
mod validation;

/// The platform whose rules decide how a run's process starts: the
/// workspace host's when the workspace is remote, else this machine's.
/// Remote hosts are Linux or macOS, so a remote run never gets a Windows
/// interpreter or a batch script even when this machine is Windows.
pub(crate) fn run_platform() -> Platform {
if lithe_workspace::is_remote() {
Platform::Unix
} else {
Platform::HOST
}
}

pub use arrangement::{arrange, ArrangeRequest};
pub(crate) use arrangement::{valid_folder, Arrangement};
pub use before_launch::{
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/execution/src/configuration/declared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,8 @@ pub(crate) fn validate(configuration: &RunConfiguration) -> Result<(), CoreError
#[cfg(test)]
mod tests {
use super::*;
// Fixtures live on this machine.
use std::fs;

fn kind() -> DeclaredRunType {
DeclaredRunType {
Expand Down
21 changes: 13 additions & 8 deletions rust/crates/execution/src/configuration/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub fn configuration_types(request: ConfigurationTypesRequest) -> Result<Value,
.into_iter()
.map(|kind| {
let mut item = json!({ "provider": kind.provider() });
if let Some(availability) = process::platform_availability(kind, Platform::HOST) {
if let Some(availability) = process::platform_availability(kind, run_platform()) {
item["availability"] = json!(availability);
}
item
Expand Down Expand Up @@ -138,7 +138,7 @@ pub fn editor_form(request: EditorFormRequest) -> Result<Value, CoreError> {
});
match editor {
Editor::Process(kind) => {
if let Some(availability) = process::platform_availability(kind, Platform::HOST) {
if let Some(availability) = process::platform_availability(kind, run_platform()) {
form["availability"] = json!(availability);
}
}
Expand Down Expand Up @@ -672,7 +672,7 @@ fn header_fields(automatic_name: Option<String>) -> Vec<Field> {

/// The fields of `kind`'s editor, with automatic values for `draft`.
fn fields(kind: Kind, root: &Path, draft: &Draft, choices: StepChoices) -> Vec<Value> {
let platform = Platform::HOST;
let platform = run_platform();
let options = draft.options();
let mut fields = header_fields(process::default_name(&options));
if kind.runs_script() {
Expand Down Expand Up @@ -906,8 +906,8 @@ impl Common {
let working_directory = match self.working_directory.trim() {
"" | "." => ".".to_string(),
value => normalize_working_directory(root, value).unwrap_or_else(|_| {
let target = process::file_path(root, value, Platform::HOST);
let code = if target.is_dir() {
let target = process::file_path(root, value, run_platform());
let code = if fs::is_dir(&target).unwrap_or(false) {
"outsideProject"
} else {
"notFound"
Expand Down Expand Up @@ -1084,7 +1084,7 @@ impl Draft {
"process",
serde_json::to_value(&options).expect("process options encode"),
);
if let Ok(found) = process::field_errors(&configuration, Platform::HOST) {
if let Ok(found) = process::field_errors(&configuration, run_platform()) {
for error in found {
if error.code != "required"
&& !errors.iter().any(|known| known.field == error.field)
Expand Down Expand Up @@ -1134,14 +1134,19 @@ fn stored_path(
if let Some(code) = process::text_error(value, 4096) {
return Err(code);
}
let platform = Platform::HOST;
let platform = run_platform();
let absolute = lithe_platform::paths::is_absolute_path(value, platform);
let path = if absolute {
PathBuf::from(value)
} else {
root.join(value)
};
if (directory && !path.is_dir()) || (!directory && !path.is_file()) {
let found = if directory {
fs::is_dir(&path)
} else {
fs::is_file(&path)
};
if !found.unwrap_or(false) {
return Err("notFound");
}
let canonical = fs::canonicalize(&path).map_err(|_| "notFound")?;
Expand Down
35 changes: 34 additions & 1 deletion rust/crates/execution/src/configuration/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,40 @@ pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result<Va
/// the provider or the saved entry named, or an executable owned by a runtime
/// toolchain.
/// Ecosystem launch semantics stay in the plugin that declared the run.
///
/// In a remote workspace the plan names the host's files: the placeholder
/// paths it was assembled with become the host paths they stand for, so the
/// client starts the process on the host without translating any of it.
pub fn create_launch_plan(request: LaunchPlanRequest) -> Result<Value, CoreError> {
assemble_launch_plan(request).map(host_paths)
}

/// Replaces placeholder paths in `plan`'s executable, arguments and inline
/// script with the host paths they stand for; other values stay as they are.
fn host_paths(mut plan: Value) -> Value {
if !lithe_workspace::is_remote() {
return plan;
}
let host = |value: &mut Value| {
if let Some(text) = value.as_str() {
if let Some(mapped) = lithe_workspace::remote_path(Path::new(text)).to_str() {
*value = json!(mapped);
}
}
};
if let Some(path) = plan.pointer_mut("/executable/path") {
host(path);
}
if let Some(arguments) = plan.get_mut("arguments").and_then(Value::as_array_mut) {
arguments.iter_mut().for_each(host);
}
if let Some(path) = plan.pointer_mut("/inlineScript/path") {
host(path);
}
plan
}

fn assemble_launch_plan(request: LaunchPlanRequest) -> Result<Value, CoreError> {
let root = existing_root(&request.root)?;
let layers = read_layers(&root, None, request.local_document)?;
let resolved = resolve_layers(&root, &layers, None)?;
Expand All @@ -90,7 +123,7 @@ pub fn create_launch_plan(request: LaunchPlanRequest) -> Result<Value, CoreError
return super::process::launch_plan(
&root,
config,
Platform::HOST,
run_platform(),
request.inline_script_base.as_deref(),
);
}
Expand Down
18 changes: 11 additions & 7 deletions rust/crates/execution/src/configuration/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use super::*;
/// editors would otherwise be stored as a literal directory name.
pub(crate) fn normalize_working_directory(root: &Path, value: &str) -> Result<String, CoreError> {
normalize_project_directory(root, value).map_err(|error| {
if value.contains('$') && !root.join(value).is_dir() {
if value.contains('$') && !fs::is_dir(root.join(value)).unwrap_or(false) {
CoreError::new(
ErrorCode::InvalidRequest,
"Working directory variables are not supported; use a path relative to the project",
Expand Down Expand Up @@ -73,7 +73,7 @@ pub(crate) fn project_directory_exists(root: &Path, value: &str) -> bool {
let Ok(canonical_target) = fs::canonicalize(root.join(value)) else {
return false;
};
canonical_target.is_dir() && canonical_target.starts_with(canonical_root)
canonical_target.starts_with(canonical_root) && fs::is_dir(&canonical_target).unwrap_or(false)
}

/// Reads a sidecar document below `.lithe`, such as `project.json`, with the
Expand Down Expand Up @@ -111,11 +111,15 @@ pub(crate) fn generated_ids(root: &Path) -> BTreeSet<String> {

pub(crate) fn existing_root(value: &str) -> Result<PathBuf, CoreError> {
let path = PathBuf::from(value);
if !path.is_dir() {
return Err(CoreError::new(
ErrorCode::WorkspaceNotFound,
"Project root does not exist",
));
match fs::is_dir(&path) {
Ok(true) => {}
Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)),
Ok(false) | Err(_) => {
return Err(CoreError::new(
ErrorCode::WorkspaceNotFound,
"Project root does not exist",
))
}
}
Ok(path)
}
Expand Down
8 changes: 6 additions & 2 deletions rust/crates/execution/src/configuration/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ pub(crate) fn launch_plan(
let (script, shebang) = match (options.script(), options.text()) {
(Some(script), _) => {
let file = file_path(root, script, platform);
if !file.is_file() {
if !fs::is_file(&file).unwrap_or(false) {
return Err(
CoreError::new(ErrorCode::InvalidRequest, "Script file was not found")
.with_details(script),
Expand Down Expand Up @@ -761,7 +761,9 @@ fn require_program(
executable: &Executable,
platform: Platform,
) -> Result<(), CoreError> {
if matches!(executable, Executable::Path(_)) && !file_path(root, value, platform).is_file() {
if matches!(executable, Executable::Path(_))
&& !fs::is_file(file_path(root, value, platform)).unwrap_or(false)
{
return Err(
CoreError::new(ErrorCode::InvalidRequest, "Program was not found").with_details(value),
);
Expand Down Expand Up @@ -801,6 +803,8 @@ pub(crate) fn cmd_quote(argument: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
// Fixtures live on this machine.
use std::fs;

/// A fresh project directory, removed when dropped.
struct Project(PathBuf);
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/execution/src/configuration/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub(crate) fn resolve_layers(
}
}
let global_toolchain = local.get("toolchain").cloned();
let platform = Platform::HOST;
let platform = run_platform();
for configuration in &mut configurations {
configuration.plugin = layers
.plugin_dependency(&configuration.id)
Expand Down
Loading
Loading