mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-04 16:09:13 +00:00
fix: run R scripts with their deployed lock and version-keyed packages (#12851)
* fix: run R scripts with their deployed lock and key the R cache by version Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: key R packages by repository and expose dependencies during install Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2664b6c7e0
commit
188f2dffc8
10 files changed
+435
-132
No files matched your search
@@ -40,8 +40,12 @@ pub fn parse_r_signature(code: &str) -> anyhow::Result<MainArgSignature> {
|
||||
Ok(parse_r_sig_meta(code)?)
|
||||
}
|
||||
|
||||
/// Extract package names from `library(...)` and `require(...)` calls in R code.
|
||||
/// Returns a newline-separated list of package names.
|
||||
/// Extract the packages R code depends on: `library()`, `require()`, `requireNamespace()`,
|
||||
/// `loadNamespace()` and `pkg::fun` / `pkg:::fun`. Returns a newline-separated, sorted list.
|
||||
///
|
||||
/// The worker keys its resolution cache on this list while renv resolves from its own scan of
|
||||
/// the code, so a form renv detects and this misses lets two scripts share a lock that lacks
|
||||
/// one of their packages.
|
||||
pub fn parse_r_requirements(code: &str) -> anyhow::Result<String> {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let language = tree_sitter_r::LANGUAGE;
|
||||
@@ -66,41 +70,89 @@ pub fn parse_r_requirements(code: &str) -> anyhow::Result<String> {
|
||||
}
|
||||
|
||||
fn find_library_calls(node: Node, code: &str, packages: &mut Vec<String>) {
|
||||
let text = |n: Node| n.utf8_text(code.as_bytes()).unwrap_or("");
|
||||
let mut cursor = node.walk();
|
||||
for child in node.children(&mut cursor) {
|
||||
if child.kind() == "call" {
|
||||
// call node: child 0 is the function name, child 1 is arguments
|
||||
if let (Some(func_node), Some(args_node)) = (child.child(0), child.child(1)) {
|
||||
let func_name = func_node.utf8_text(code.as_bytes()).unwrap_or("");
|
||||
if func_name == "library" || func_name == "require" {
|
||||
// AST: arguments → ( + argument → identifier/string + )
|
||||
if args_node.kind() == "arguments" {
|
||||
let mut args_cursor = args_node.walk();
|
||||
for arg in args_node.children(&mut args_cursor) {
|
||||
if arg.kind() == "argument" {
|
||||
// The argument node wraps the actual value
|
||||
if let Some(value_node) = arg.child(0) {
|
||||
let pkg = value_node
|
||||
.utf8_text(code.as_bytes())
|
||||
.unwrap_or("")
|
||||
.trim_matches('"')
|
||||
.trim_matches('\'');
|
||||
if !pkg.is_empty() {
|
||||
packages.push(pkg.to_string());
|
||||
}
|
||||
}
|
||||
break; // only first arg
|
||||
}
|
||||
match child.kind() {
|
||||
"call" => {
|
||||
if let (Some(func_node), Some(args_node)) = (
|
||||
child.child_by_field_name("function"),
|
||||
child.child_by_field_name("arguments"),
|
||||
) {
|
||||
// `library` and `require` take a bare name unless `character.only = TRUE`;
|
||||
// the namespace functions take a string.
|
||||
let bare_name_allowed = match text(func_node) {
|
||||
"library" | "require" => !has_character_only(args_node, code),
|
||||
"requireNamespace" | "loadNamespace" => false,
|
||||
_ => {
|
||||
find_library_calls(child, code, packages);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(value) = package_argument(args_node, code) {
|
||||
let pkg = match value.kind() {
|
||||
"identifier" if bare_name_allowed => Some(text(value)),
|
||||
"string" => Some(text(value).trim_matches(['"', '\''])),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(pkg) = pkg.filter(|p| !p.is_empty()) {
|
||||
packages.push(pkg.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"namespace_operator" => {
|
||||
if let Some(lhs) = child.child_by_field_name("lhs") {
|
||||
if matches!(lhs.kind(), "identifier" | "string") {
|
||||
let pkg = text(lhs).trim_matches(['"', '\'']);
|
||||
if !pkg.is_empty() {
|
||||
packages.push(pkg.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Recurse into children to find nested library() calls
|
||||
find_library_calls(child, code, packages);
|
||||
}
|
||||
}
|
||||
|
||||
/// The first positional argument, or the one named `package`.
|
||||
fn package_argument<'a>(args_node: Node<'a>, code: &str) -> Option<Node<'a>> {
|
||||
let mut cursor = args_node.walk();
|
||||
let mut first_positional = None;
|
||||
for arg in args_node.children(&mut cursor) {
|
||||
if arg.kind() != "argument" {
|
||||
continue;
|
||||
}
|
||||
match arg.child_by_field_name("name") {
|
||||
Some(name) if name.utf8_text(code.as_bytes()).unwrap_or("") == "package" => {
|
||||
return arg.child_by_field_name("value");
|
||||
}
|
||||
Some(_) => {}
|
||||
None if first_positional.is_none() => {
|
||||
first_positional = arg.child_by_field_name("value");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
first_positional
|
||||
}
|
||||
|
||||
fn has_character_only(args_node: Node, code: &str) -> bool {
|
||||
let mut cursor = args_node.walk();
|
||||
let found = args_node.children(&mut cursor).any(|arg| {
|
||||
arg.kind() == "argument"
|
||||
&& arg
|
||||
.child_by_field_name("name")
|
||||
.is_some_and(|n| n.utf8_text(code.as_bytes()).unwrap_or("") == "character.only")
|
||||
&& arg
|
||||
.child_by_field_name("value")
|
||||
.is_some_and(|v| matches!(v.utf8_text(code.as_bytes()).unwrap_or(""), "TRUE" | "T"))
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
fn is_base_package(pkg: &str) -> bool {
|
||||
matches!(
|
||||
pkg,
|
||||
@@ -353,6 +405,30 @@ main <- function() { }
|
||||
assert!(pkgs.contains(&"jsonlite"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_r_requirements_namespace_forms() {
|
||||
use super::parse_r_requirements;
|
||||
|
||||
let code = r#"
|
||||
suppressPackageStartupMessages(library("dplyr", quietly = TRUE))
|
||||
library(package = tidyr)
|
||||
x <- cli::rule()
|
||||
y <- R6:::encapsulate
|
||||
if (requireNamespace("crayon", quietly = TRUE)) {}
|
||||
loadNamespace('digest')
|
||||
z <- utils::head(1)
|
||||
p <- "ggplot2"
|
||||
library(p, character.only = TRUE)
|
||||
requireNamespace(p)
|
||||
"#;
|
||||
let reqs = parse_r_requirements(code).unwrap();
|
||||
let pkgs: Vec<&str> = reqs.lines().collect();
|
||||
assert_eq!(
|
||||
pkgs,
|
||||
vec!["R6", "cli", "crayon", "digest", "dplyr", "tidyr"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_r_requirements_no_deps() {
|
||||
use super::parse_r_requirements;
|
||||
|
||||
@@ -304,7 +304,7 @@
|
||||
"script.nu": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (nu)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n",
|
||||
"script.java": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (java)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# Java\n\nThe script must contain a Main public class with a `public static main()` method:\n\n```java\npublic class Main {\n public static Object main(String name, int count) {\n java.util.Map<String, Object> result = new java.util.HashMap<>();\n result.put(\"name\", name);\n result.put(\"count\", count);\n return result;\n }\n}\n```\n\n**Important:**\n- Class must be named `Main`\n- Method must be `public static Object main(...)`\n- Return type is `Object` or `void`\n\n## Maven Dependencies\n\nAdd dependencies using comments at the top:\n\n```java\n//requirements:\n//com.google.code.gson:gson:2.10.1\n//org.apache.httpcomponents:httpclient:4.5.14\n\nimport com.google.gson.Gson;\n\npublic class Main {\n public static Object main(String input) {\n Gson gson = new Gson();\n return gson.fromJson(input, Object.class);\n }\n}\n```\n",
|
||||
"script.ruby": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (ruby)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n",
|
||||
"script.rlang": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (rlang)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# R\n\n## Structure\n\nDefine a `main` function using `<-` or `=` assignment. Parameters become the script inputs:\n\n```r\nlibrary(dplyr)\nlibrary(jsonlite)\n\nmain <- function(x, name = \"default\", flag = TRUE) {\n df <- tibble(x = x, name = name)\n result <- df %>% mutate(greeting = paste(\"Hello\", name))\n return(toJSON(result, auto_unbox = TRUE))\n}\n```\n\n**Important:**\n- The `main` function is required\n- Use `library()` to load packages — they are resolved and installed automatically\n- `jsonlite` is always available (used internally for argument parsing)\n- Return values must be JSON-serializable\n\n## Parameters\n\nR types map to Windmill types:\n- `numeric` → float/int\n- `character` → string\n- `logical` → bool (use `TRUE`/`FALSE`)\n- `list` → object/dict\n- `NULL` → null\n\nDefault values are inferred from the function signature:\n\n```r\nmain <- function(\n naLine truncated
|
||||
"script.rlang": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (rlang)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# R\n\n## Structure\n\nDefine a `main` function using `<-` or `=` assignment. Parameters become the script inputs:\n\n```r\nlibrary(dplyr)\nlibrary(jsonlite)\n\nmain <- function(x, name = \"default\", flag = TRUE) {\n df <- tibble(x = x, name = name)\n result <- df %>% mutate(greeting = paste(\"Hello\", name))\n return(toJSON(result, auto_unbox = TRUE))\n}\n```\n\n**Important:**\n- The `main` function is required\n- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()`\n- A deployed script runs with the package versions locked when it was deployed\n- `jsonlite` is always available (used internally for argument parsing)\n- Return values must be JSON-serializable\n\n## Parameters\n\nR types map to Windmill types:\n- `numeric` → float/int\n- `character` → string\n- `logical` → boolLine truncated
|
||||
"script.duckdb": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (duckdb)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# DuckDB\n\nArguments are defined with comments and used with `$name` syntax:\n\n```sql\n-- $name (text) = default\n-- $age (integer)\nSELECT * FROM users WHERE name = $name AND age > $age;\n```\n\n## Ducklake Integration\n\nAttach Ducklake for data lake operations:\n\n```sql\n-- Main ducklake\nATTACH 'ducklake' AS dl;\n\n-- Named ducklake\nATTACH 'ducklake://my_lake' AS dl;\n\n-- Then query\nSELECT * FROM dl.schema.table;\n```\n\n## External Database Connections\n\nConnect to external databases using resources:\n\n```sql\nATTACH '$res:path/to/resource' AS db (TYPE postgres);\nSELECT * FROM db.schema.table;\n```\n\n## S3 File Operations\n\nRead files from S3 storage:\n\n```sql\n-- Default storage\nSELECT * FROM read_csv('s3:///path/to/file.csv');\n\n-- Named storage\nSELECT * FROM read_csv('s3://storage_name/path/to/file.csv');\n\n-- Parquet files\nSELECT * FROM read_parquet('s3:///path/to/file.parqLine truncated
|
||||
"script.bunnative": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (bunnative)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# TypeScript (Bun Native)\n\nNative TypeScript execution. Native scripts are Bun scripts that run on the native worker — a lightweight V8 isolate that exposes `fetch` and the JavaScript standard library — and can be heavily parallelized. Every script MUST start with `//native` on its first line so Windmill routes it to the native worker; without it the exact same script runs on the regular Bun worker. You may import npm packages and other Windmill scripts (e.g. `./helper.ts`) — imports are resolved and bundled just like a regular Bun script — as long as everything (your code and its dependencies) relies only on `fetch` and the standard library. Libraries that need Node/Bun runtime APIs (filesystem, `node:*` modules, child processes, native addons) will not work on the native worker; use the regular `bun` language for those.\n\n## Structure\n\nExport a single **async** function called `Line truncated
|
||||
"script.dbt": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (dbt)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n",
|
||||
|
||||
@@ -95,6 +95,13 @@ mount {
|
||||
rw: true
|
||||
}
|
||||
|
||||
mount {
|
||||
src: "{LIB_ROOT}"
|
||||
dst: "{LIB_ROOT}"
|
||||
is_bind: true
|
||||
mandatory: false
|
||||
}
|
||||
|
||||
mount {
|
||||
src: "{PKG_DIR}"
|
||||
dst: "/install"
|
||||
|
||||
@@ -49,6 +49,21 @@ lazy_static::lazy_static! {
|
||||
}
|
||||
|
||||
const DEFAULT_CRAN_REPO_URL: &str = "https://cloud.r-project.org";
|
||||
const R_LIBS_SEPARATOR: &str = if cfg!(windows) { ";" } else { ":" };
|
||||
|
||||
/// A short key for the repository a package is installed from, without credentials, so a
|
||||
/// rotated mirror password does not invalidate the cache.
|
||||
fn repo_key(url: &str) -> String {
|
||||
let url = match url::Url::parse(url) {
|
||||
Ok(mut parsed) => {
|
||||
let _ = parsed.set_username("");
|
||||
let _ = parsed.set_password(None);
|
||||
parsed.to_string()
|
||||
}
|
||||
Err(_) => url.to_string(),
|
||||
};
|
||||
calculate_hash(url.trim_end_matches('/'))[..12].to_string()
|
||||
}
|
||||
|
||||
/// The CRAN mirror configured for this workspace (or instance), if any.
|
||||
///
|
||||
@@ -80,6 +95,106 @@ async fn configured_cran_repo_url(job_id: &Uuid, w_id: &str, conn: &Connection)
|
||||
Some(repo)
|
||||
}
|
||||
|
||||
/// The R a job runs under. A package built by one R `major.minor` is not loadable by another,
|
||||
/// and renv picks the versions the running R supports, so this keys both the resolution cache
|
||||
/// and the installed-package directories.
|
||||
pub struct RRuntime {
|
||||
pub rscript: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref R_VERSIONS: std::sync::Mutex<HashMap<String, String>> = Default::default();
|
||||
}
|
||||
|
||||
impl RRuntime {
|
||||
pub async fn detect() -> Result<RRuntime, Error> {
|
||||
let rscript = if cfg!(windows) {
|
||||
"Rscript.exe".to_string()
|
||||
} else {
|
||||
RSCRIPT_PATH.clone()
|
||||
};
|
||||
Self::for_rscript(rscript).await
|
||||
}
|
||||
|
||||
async fn for_rscript(rscript: String) -> Result<RRuntime, Error> {
|
||||
if let Some(version) = R_VERSIONS.lock().unwrap().get(&rscript) {
|
||||
return Ok(RRuntime { rscript, version: version.clone() });
|
||||
}
|
||||
let out = Command::new(&rscript)
|
||||
.args([
|
||||
"--vanilla",
|
||||
"-e",
|
||||
r#"cat("\n", R.version$major, ".", R.version$minor, "\n", sep = "")"#,
|
||||
])
|
||||
.env_clear()
|
||||
.env("PATH", PATH_ENV.as_str())
|
||||
.envs(WIN_ENVS.to_vec())
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.map_err(|e| Error::ExecutionErr(format!("could not run {rscript}: {e}")))?;
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let version = stdout.trim().lines().last().unwrap_or_default().to_string();
|
||||
let well_formed = version.split('.').count() >= 2
|
||||
&& version
|
||||
.split('.')
|
||||
.all(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()));
|
||||
if !out.status.success() || !well_formed {
|
||||
return Err(Error::ExecutionErr(format!(
|
||||
"could not read the R version of {rscript}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
)));
|
||||
}
|
||||
R_VERSIONS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(rscript.clone(), version.clone());
|
||||
Ok(RRuntime { rscript, version })
|
||||
}
|
||||
|
||||
/// `major.minor`, the granularity at which R requires packages to be reinstalled.
|
||||
pub fn minor(&self) -> String {
|
||||
self.version.split('.').take(2).join(".")
|
||||
}
|
||||
}
|
||||
|
||||
/// The packages a script needs, as the resolution cache knows them: what the parser finds plus
|
||||
/// jsonlite, which the wrapper uses to read arguments and write the result. renv is left out:
|
||||
/// it ships with the image and locks never install it.
|
||||
fn required_packages(inner_content: &str) -> Result<Vec<String>, Error> {
|
||||
let mut packages = parse_r_requirements(inner_content)?
|
||||
.lines()
|
||||
.filter(|p| *p != "renv")
|
||||
.map(str::to_string)
|
||||
.collect_vec();
|
||||
if !packages.iter().any(|p| p == "jsonlite") {
|
||||
packages.push("jsonlite".to_string());
|
||||
packages.sort();
|
||||
}
|
||||
Ok(packages)
|
||||
}
|
||||
|
||||
/// The `major.minor` of the R a lock was resolved under.
|
||||
fn lock_r_minor(lockfile: &str) -> Option<String> {
|
||||
let lock: serde_json::Value = serde_json::from_str(lockfile).ok()?;
|
||||
let version = lock.get("R")?.get("Version")?.as_str()?;
|
||||
Some(version.split('.').take(2).join("."))
|
||||
}
|
||||
|
||||
/// The packages of `required` that `lockfile` does not list.
|
||||
fn missing_from_lock(lockfile: &str, required: &[String]) -> Result<Vec<String>, Error> {
|
||||
let locked = parse_renv_lock(lockfile)?
|
||||
.into_iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
Ok(required
|
||||
.iter()
|
||||
.filter(|p| !locked.contains(*p))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
const NSJAIL_CONFIG_RUN_R_CONTENT: &str = include_str!("../nsjail/run.r.config.proto");
|
||||
const NSJAIL_CONFIG_INSTALL_R_CONTENT: &str = include_str!("../nsjail/install.r.config.proto");
|
||||
|
||||
@@ -123,33 +238,96 @@ pub async fn handle_r_job<'a>(
|
||||
let jailed = !cfg!(windows) && (is_sandboxing_enabled() || annotation.sandbox);
|
||||
check_no_network_jailed(annotation.no_network, jailed)?;
|
||||
|
||||
let runtime = RRuntime::detect().await?;
|
||||
|
||||
// --- Prepare ---
|
||||
{
|
||||
prepare(&args).await?;
|
||||
}
|
||||
// --- Resolve lockfile ---
|
||||
let lockfile = resolve(
|
||||
&args.job.id,
|
||||
args.inner_content,
|
||||
args.mem_peak,
|
||||
args.canceled_by,
|
||||
args.job_dir,
|
||||
args.conn,
|
||||
args.worker_name,
|
||||
&args.job.workspace_id,
|
||||
annotation.renv_verbose,
|
||||
)
|
||||
.await?;
|
||||
// --- Lockfile: the deployed one, else resolve ---
|
||||
// A lock that misses a package the code needs is resolved again rather than trusted: a lock
|
||||
// stored by a dependency job that scanned no code holds only renv, and a preview can carry
|
||||
// the lock of code since edited.
|
||||
let deployed_lock = match args
|
||||
.requirements_o
|
||||
.map(|l| l.trim())
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
Some(lock) => {
|
||||
let required = required_packages(args.inner_content)?;
|
||||
match missing_from_lock(lock, &required) {
|
||||
Ok(missing) if missing.is_empty() => {
|
||||
if let Some(locked_r) = lock_r_minor(lock).filter(|v| *v != runtime.minor()) {
|
||||
append_logs(
|
||||
&args.job.id,
|
||||
&args.job.workspace_id,
|
||||
format!(
|
||||
"\nthe script's lock was resolved under R {locked_r} and runs under R {}: its versions are installed as locked\n",
|
||||
runtime.minor()
|
||||
),
|
||||
args.conn,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Some(lock.to_string())
|
||||
}
|
||||
Ok(missing) => {
|
||||
append_logs(
|
||||
&args.job.id,
|
||||
&args.job.workspace_id,
|
||||
format!(
|
||||
"\nthe script's lock does not cover {}: resolving again. Redeploy the script to store a complete lock.\n",
|
||||
missing.join(", ")
|
||||
),
|
||||
args.conn,
|
||||
)
|
||||
.await;
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
append_logs(
|
||||
&args.job.id,
|
||||
&args.job.workspace_id,
|
||||
format!("\nthe script's lock is not a valid renv.lock ({e}): resolving again.\n"),
|
||||
args.conn,
|
||||
)
|
||||
.await;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let lockfile = match deployed_lock {
|
||||
Some(lock) => lock,
|
||||
None => {
|
||||
resolve(
|
||||
&args.job.id,
|
||||
args.inner_content,
|
||||
args.mem_peak,
|
||||
args.canceled_by,
|
||||
args.job_dir,
|
||||
args.conn,
|
||||
args.worker_name,
|
||||
&args.job.workspace_id,
|
||||
annotation.renv_verbose,
|
||||
&runtime,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
// --- Install ---
|
||||
let lib_path = if !lockfile.is_empty() {
|
||||
let r_libs_user = if !lockfile.is_empty() {
|
||||
Some(
|
||||
install(
|
||||
&mut args,
|
||||
&lockfile,
|
||||
annotation.renv_verbose,
|
||||
annotation.renv_install_verbose,
|
||||
&runtime,
|
||||
)
|
||||
.await?,
|
||||
.await?
|
||||
.join(R_LIBS_SEPARATOR),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
@@ -158,9 +336,10 @@ pub async fn handle_r_job<'a>(
|
||||
{
|
||||
run(
|
||||
&mut args,
|
||||
lib_path.as_deref(),
|
||||
r_libs_user.as_deref(),
|
||||
jailed,
|
||||
annotation.no_network,
|
||||
&runtime,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
@@ -228,26 +407,20 @@ pub async fn resolve<'a>(
|
||||
worker_name: &str,
|
||||
w_id: &str,
|
||||
verbose: bool,
|
||||
runtime: &RRuntime,
|
||||
) -> Result<String, Error> {
|
||||
let mut packages = parse_r_requirements(inner_content)?;
|
||||
|
||||
// jsonlite is always needed by the wrapper for JSON arg parsing and result serialization
|
||||
let has_jsonlite = packages.lines().any(|l| l.trim() == "jsonlite");
|
||||
if !has_jsonlite {
|
||||
if packages.is_empty() {
|
||||
packages = "jsonlite".to_string();
|
||||
} else {
|
||||
packages.push_str("\njsonlite");
|
||||
}
|
||||
}
|
||||
let required = required_packages(inner_content)?;
|
||||
let packages = required.join("\n");
|
||||
|
||||
let custom_repo = configured_cran_repo_url(job_id, w_id, conn).await;
|
||||
|
||||
// A mirror resolves its own versions, so it must not share a cache entry with CRAN.
|
||||
let req_hash = match &custom_repo {
|
||||
Some(repo) => format!("r-{}", calculate_hash(&format!("{packages}\n#repo:{repo}"))),
|
||||
None => format!("r-{}", calculate_hash(&packages)),
|
||||
};
|
||||
// A mirror resolves its own versions, and renv picks versions the running R supports, so
|
||||
// neither may share a cache entry with another.
|
||||
let mut key = format!("{packages}\n#r:{}", runtime.minor());
|
||||
if let Some(repo) = &custom_repo {
|
||||
key.push_str(&format!("\n#repo:{repo}"));
|
||||
}
|
||||
let req_hash = format!("r-{}", calculate_hash(&key));
|
||||
let repo_url = custom_repo.as_deref().unwrap_or(DEFAULT_CRAN_REPO_URL);
|
||||
if let Some(db) = conn.as_sql() {
|
||||
if let Some(cached) = sqlx::query_scalar!(
|
||||
@@ -269,9 +442,16 @@ pub async fn resolve<'a>(
|
||||
)
|
||||
.await;
|
||||
|
||||
// main.r is already written by prepare() and contains the library() calls.
|
||||
// renv will scan it to detect dependencies.
|
||||
// renv resolves what it finds scanning this directory, so it holds the script and the
|
||||
// wrapper's own dependency, and nothing else that would depend on the caller.
|
||||
// Disable renv's own package cache — Windmill manages its own install cache.
|
||||
let resolve_dir = format!("{job_dir}/r_resolve");
|
||||
fs::create_dir_all(&resolve_dir).await?;
|
||||
write_file(
|
||||
&resolve_dir,
|
||||
"main.r",
|
||||
&format!("{inner_content}\n\nlibrary(jsonlite)\n"),
|
||||
)?;
|
||||
let resolve_script = format!(
|
||||
r#"options(
|
||||
repos = c(CRAN = "{repo_url}"),
|
||||
@@ -289,18 +469,13 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE))
|
||||
repo_url = escape_r_double_quoted(repo_url),
|
||||
);
|
||||
|
||||
let mut file = File::create(format!("{}/resolve.r", job_dir)).await?;
|
||||
file.write_all(resolve_script.as_bytes()).await?;
|
||||
write_file(&resolve_dir, "resolve.r", &resolve_script)?;
|
||||
|
||||
let child = {
|
||||
let renv_root = format!("{}/renv", *R_CACHE_DIR);
|
||||
let rscript_executable = if cfg!(windows) {
|
||||
"Rscript.exe"
|
||||
} else {
|
||||
RSCRIPT_PATH.as_str()
|
||||
};
|
||||
let rscript_executable = runtime.rscript.as_str();
|
||||
let mut cmd = Command::new(rscript_executable);
|
||||
cmd.current_dir(job_dir)
|
||||
cmd.current_dir(&resolve_dir)
|
||||
.env("PATH", PATH_ENV.as_str())
|
||||
.env("RENV_PATHS_ROOT", &renv_root)
|
||||
.arg("resolve.r")
|
||||
@@ -326,7 +501,7 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE))
|
||||
)
|
||||
.await?;
|
||||
|
||||
let lock_path = format!("{}/renv.lock", job_dir);
|
||||
let lock_path = format!("{}/renv.lock", resolve_dir);
|
||||
let mut lock_file = File::open(&lock_path).await?;
|
||||
let mut lock = String::new();
|
||||
lock_file.read_to_string(&mut lock).await?;
|
||||
@@ -334,8 +509,21 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE))
|
||||
lock = strip_repo_credentials(lock);
|
||||
}
|
||||
|
||||
// Cache the lockfile
|
||||
if let Some(db) = conn.as_sql() {
|
||||
// A lock without a package the script needs must not be cached: every script with the same
|
||||
// package list would be served it until the entry expires.
|
||||
let missing = missing_from_lock(&lock, &required)?;
|
||||
if !missing.is_empty() {
|
||||
append_logs(
|
||||
job_id,
|
||||
w_id,
|
||||
format!(
|
||||
"renv did not resolve {}: the lock is not cached\n",
|
||||
missing.join(", ")
|
||||
),
|
||||
conn,
|
||||
)
|
||||
.await;
|
||||
} else if let Some(db) = conn.as_sql() {
|
||||
sqlx::query!(
|
||||
"INSERT INTO pip_resolution_cache (hash, lockfile, expiration) VALUES ($1, $2, now() + ('3 days')::interval) ON CONFLICT (hash) DO UPDATE SET lockfile = EXCLUDED.lockfile",
|
||||
req_hash,
|
||||
@@ -504,42 +692,71 @@ fn parse_renv_lock(lockfile: &str) -> Result<Vec<RenvPackage>, Error> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Installs the lock's packages and returns the directories to put on `R_LIBS_USER`: one per
|
||||
/// package, keyed by its version and the R `major.minor`, so that versions and R installs
|
||||
/// sharing a worker cache never see each other's builds.
|
||||
async fn install<'a>(
|
||||
args: &mut JobHandlerInput<'a>,
|
||||
lockfile: &str,
|
||||
verbose: bool,
|
||||
install_verbose: bool,
|
||||
) -> Result<String, Error> {
|
||||
let lib_path = format!("{}/r_site_library", *R_CACHE_DIR);
|
||||
fs::create_dir_all(&lib_path).await?;
|
||||
runtime: &RRuntime,
|
||||
) -> Result<Vec<String>, Error> {
|
||||
let lib_root = format!("{}/r_site_library/{}", *R_CACHE_DIR, runtime.minor());
|
||||
fs::create_dir_all(&lib_root).await?;
|
||||
|
||||
let packages = parse_renv_lock(lockfile)?;
|
||||
if packages.is_empty() {
|
||||
return Ok(lib_path);
|
||||
}
|
||||
|
||||
// The configured mirror wins over the URL recorded in the lockfile, so a lockfile
|
||||
// resolved against CRAN still installs on an instance that can only reach the mirror.
|
||||
let custom_repo =
|
||||
configured_cran_repo_url(&args.job.id, &args.job.workspace_id, args.conn).await;
|
||||
let repo_of = |p: &RenvPackage| custom_repo.clone().unwrap_or_else(|| p.repo_url.clone());
|
||||
// Every workspace shares these directories, and a lock or a workspace setting names the
|
||||
// repository, so a build is only ever reused for the repository it came from.
|
||||
let outer_dir = |p: &RenvPackage| {
|
||||
format!(
|
||||
"{lib_root}/{}/{}_{}_outer",
|
||||
repo_key(&repo_of(p)),
|
||||
p.name,
|
||||
p.version
|
||||
)
|
||||
};
|
||||
let lib_dirs = packages.iter().map(|p| outer_dir(p)).collect_vec();
|
||||
if packages.is_empty() {
|
||||
return Ok(lib_dirs);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct RPackagePayload {
|
||||
pkg: String,
|
||||
version: String,
|
||||
repo_url: String,
|
||||
/// The lock's other packages, which a source build loads while installing.
|
||||
other_libs: Vec<String>,
|
||||
}
|
||||
|
||||
// Build dependency graph for topological layering
|
||||
let mut graph = DependencyGraph::new();
|
||||
for renv_pkg in &packages {
|
||||
let handle = format!("{}-{}", renv_pkg.name, renv_pkg.version);
|
||||
let handle = format!(
|
||||
"{}-{}-r{}-{}",
|
||||
renv_pkg.name,
|
||||
renv_pkg.version,
|
||||
runtime.minor(),
|
||||
repo_key(&repo_of(renv_pkg))
|
||||
);
|
||||
// renv uses staged installation: it builds to a temp dir then rename()s onto
|
||||
// the target. If the target is a bind mount point, rename fails with
|
||||
// "target file already exists". We work around this by mounting the parent
|
||||
// (wrapper) dir at /install so renv can freely create /install/{pkg}/ via rename.
|
||||
let pkg_outer = format!("{}/{}_outer", lib_path, renv_pkg.name);
|
||||
let pkg_outer = outer_dir(renv_pkg);
|
||||
let path = format!("{}/{}", pkg_outer, renv_pkg.name);
|
||||
let other_libs = lib_dirs
|
||||
.iter()
|
||||
.filter(|d| **d != pkg_outer)
|
||||
.cloned()
|
||||
.collect_vec();
|
||||
graph.insert(
|
||||
renv_pkg.name.clone(),
|
||||
RequiredDependency {
|
||||
@@ -549,9 +766,8 @@ async fn install<'a>(
|
||||
custom_payload: RPackagePayload {
|
||||
pkg: renv_pkg.name.clone(),
|
||||
version: renv_pkg.version.clone(),
|
||||
repo_url: custom_repo
|
||||
.clone()
|
||||
.unwrap_or_else(|| renv_pkg.repo_url.clone()),
|
||||
repo_url: repo_of(renv_pkg),
|
||||
other_libs,
|
||||
},
|
||||
},
|
||||
renv_pkg.dependencies.clone(),
|
||||
@@ -560,6 +776,8 @@ async fn install<'a>(
|
||||
|
||||
let jailed = !cfg!(windows) && is_sandboxing_enabled();
|
||||
let job_dir = args.job_dir.to_owned();
|
||||
let rscript = runtime.rscript.clone();
|
||||
let lib_root_c = lib_root.clone();
|
||||
|
||||
par_install_language_dependencies_seq(
|
||||
InstallDeps::Layered(graph),
|
||||
@@ -568,12 +786,14 @@ async fn install<'a>(
|
||||
false,
|
||||
*R_CONCURRENT_DOWNLOADS,
|
||||
move |dependency| {
|
||||
let lib_path_c = lib_path.clone();
|
||||
let job_dir = job_dir.clone();
|
||||
let pkg_name = &dependency.custom_payload.pkg;
|
||||
// pkg_outer is the wrapper dir mounted rw at /install inside nsjail.
|
||||
// renv creates /install/{pkg}/ inside it via staged rename.
|
||||
let pkg_outer = format!("{}/{}_outer", lib_path_c, pkg_name);
|
||||
let pkg_outer = dependency
|
||||
.path
|
||||
.rsplit_once('/')
|
||||
.map(|(outer, _)| outer.to_string())
|
||||
.unwrap_or_default();
|
||||
std::fs::create_dir_all(&pkg_outer)?;
|
||||
|
||||
let mut cmd = if jailed {
|
||||
@@ -581,6 +801,7 @@ async fn install<'a>(
|
||||
let config_content = NSJAIL_CONFIG_INSTALL_R_CONTENT
|
||||
.replace("{JOB_DIR}", &job_dir)
|
||||
.replace("{PKG_DIR}", &pkg_outer)
|
||||
.replace("{LIB_ROOT}", &lib_root_c)
|
||||
.replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string())
|
||||
.replace("{TRACING_PROXY_CA_CERT_PATH}", &*TRACING_PROXY_CA_CERT_PATH)
|
||||
.replace("#{DEV}", DEV_CONF_NSJAIL);
|
||||
@@ -590,19 +811,10 @@ async fn install<'a>(
|
||||
&config_content,
|
||||
)?;
|
||||
let mut cmd = Command::new(NSJAIL_PATH.as_str());
|
||||
cmd.args(vec![
|
||||
"--config",
|
||||
&nsjail_proto,
|
||||
"--",
|
||||
RSCRIPT_PATH.as_str(),
|
||||
]);
|
||||
cmd.args(vec!["--config", &nsjail_proto, "--", rscript.as_str()]);
|
||||
cmd
|
||||
} else {
|
||||
Command::new(if cfg!(windows) {
|
||||
"Rscript.exe"
|
||||
} else {
|
||||
RSCRIPT_PATH.as_str()
|
||||
})
|
||||
Command::new(rscript.as_str())
|
||||
};
|
||||
|
||||
let verbose_r = if verbose { "TRUE" } else { "FALSE" };
|
||||
@@ -619,12 +831,20 @@ async fn install<'a>(
|
||||
.args(&[
|
||||
"-e",
|
||||
&format!(
|
||||
r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#,
|
||||
r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = c("{lib}"{other_libs}), dependencies = FALSE)"#,
|
||||
verbose_r = verbose_r,
|
||||
install_verbose_r = install_verbose_r,
|
||||
pkg = escape_r_double_quoted(&dependency.custom_payload.pkg),
|
||||
version = escape_r_double_quoted(&dependency.custom_payload.version),
|
||||
lib = escape_r_double_quoted(&install_lib),
|
||||
// Installs into the first library; a source build loads the package's
|
||||
// dependencies from the others, which earlier layers installed.
|
||||
other_libs = dependency
|
||||
.custom_payload
|
||||
.other_libs
|
||||
.iter()
|
||||
.map(|d| format!(", \"{}\"", escape_r_double_quoted(d)))
|
||||
.join(""),
|
||||
repo = escape_r_double_quoted(&dependency.custom_payload.repo_url),
|
||||
),
|
||||
// install.packages fallback (no version pinning):
|
||||
@@ -651,23 +871,7 @@ async fn install<'a>(
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(format!("{}/r_site_library", *R_CACHE_DIR))
|
||||
}
|
||||
|
||||
/// Build R_LIBS_USER from lib_path by listing *_outer subdirs.
|
||||
/// Each package wrapper dir ({pkg}_outer) is added so R finds {pkg}_outer/{pkg}/DESCRIPTION.
|
||||
fn r_libs_user(lib_path: &str) -> String {
|
||||
std::fs::read_dir(lib_path)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| {
|
||||
e.file_type().map(|t| t.is_dir()).unwrap_or(false)
|
||||
&& e.file_name().to_string_lossy().ends_with("_outer")
|
||||
})
|
||||
.map(|e| e.path().to_string_lossy().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(":")
|
||||
Ok(lib_dirs)
|
||||
}
|
||||
|
||||
async fn run<'a>(
|
||||
@@ -686,9 +890,10 @@ async fn run<'a>(
|
||||
parent_runnable_path,
|
||||
..
|
||||
}: &mut JobHandlerInput<'a>,
|
||||
lib_path: Option<&str>,
|
||||
r_libs_user: Option<&str>,
|
||||
nsjail: bool,
|
||||
no_network: bool,
|
||||
runtime: &RRuntime,
|
||||
) -> Result<(), Error> {
|
||||
let mut reserved_variables =
|
||||
get_reserved_variables(job, &client.token, conn, parent_runnable_path.clone()).await?;
|
||||
@@ -728,14 +933,14 @@ async fn run<'a>(
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
if let Some(lp) = lib_path {
|
||||
cmd.env("R_LIBS_USER", r_libs_user(lp));
|
||||
if let Some(lp) = r_libs_user {
|
||||
cmd.env("R_LIBS_USER", lp);
|
||||
}
|
||||
cmd.args(vec![
|
||||
"--config",
|
||||
"run.config.proto",
|
||||
"--",
|
||||
RSCRIPT_PATH.as_str(),
|
||||
runtime.rscript.as_str(),
|
||||
"main.r",
|
||||
]);
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
@@ -774,11 +979,7 @@ async fn run<'a>(
|
||||
)
|
||||
.await;
|
||||
|
||||
let rscript_executable = if cfg!(windows) {
|
||||
"Rscript.exe"
|
||||
} else {
|
||||
RSCRIPT_PATH.as_str()
|
||||
};
|
||||
let rscript_executable = runtime.rscript.as_str();
|
||||
|
||||
let args = vec!["main.r"];
|
||||
let mut cmd = build_command_with_isolation(rscript_executable, &args);
|
||||
@@ -804,8 +1005,8 @@ async fn run<'a>(
|
||||
.await?,
|
||||
)
|
||||
.envs(envs);
|
||||
if let Some(lp) = lib_path {
|
||||
cmd.env("R_LIBS_USER", r_libs_user(lp));
|
||||
if let Some(lp) = r_libs_user {
|
||||
cmd.env("R_LIBS_USER", lp);
|
||||
}
|
||||
|
||||
cmd.stdin(Stdio::null())
|
||||
@@ -877,9 +1078,22 @@ tryCatch({{
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
escape_r_double_quoted, parse_renv_lock, strip_repo_credentials, validate_renv_package,
|
||||
escape_r_double_quoted, missing_from_lock, parse_renv_lock, required_packages,
|
||||
strip_repo_credentials, validate_renv_package,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_a_lock_holding_only_renv_covers_nothing() {
|
||||
let required =
|
||||
required_packages("library(R6)\nx <- renv::status\nmain <- function() 1").unwrap();
|
||||
assert_eq!(required, vec!["R6", "jsonlite"]);
|
||||
let renv_only = r#"{"Packages": {"renv": {"Package": "renv", "Version": "1.2.0"}}}"#;
|
||||
assert_eq!(
|
||||
missing_from_lock(renv_only, &required).unwrap(),
|
||||
vec!["R6", "jsonlite"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_renv_package_accepts_real() {
|
||||
for (n, v) in [
|
||||
|
||||
@@ -3807,6 +3807,7 @@ async fn capture_dependency_job(
|
||||
worker_name,
|
||||
w_id,
|
||||
false,
|
||||
&r_executor::RRuntime::detect().await?,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
|
||||
Generated
+2
-1
@@ -5530,7 +5530,8 @@ main <- function(x, name = "default", flag = TRUE) {
|
||||
|
||||
**Important:**
|
||||
- The \`main\` function is required
|
||||
- Use \`library()\` to load packages — they are resolved and installed automatically
|
||||
- Use \`library()\` to load packages — they are resolved and installed automatically, as are packages used through \`pkg::fun()\`, \`require()\` and \`requireNamespace()\`
|
||||
- A deployed script runs with the package versions locked when it was deployed
|
||||
- \`jsonlite\` is always available (used internally for argument parsing)
|
||||
- Return values must be JSON-serializable
|
||||
|
||||
|
||||
@@ -6260,7 +6260,8 @@ main <- function(x, name = "default", flag = TRUE) {
|
||||
|
||||
**Important:**
|
||||
- The \`main\` function is required
|
||||
- Use \`library()\` to load packages — they are resolved and installed automatically
|
||||
- Use \`library()\` to load packages — they are resolved and installed automatically, as are packages used through \`pkg::fun()\`, \`require()\` and \`requireNamespace()\`
|
||||
- A deployed script runs with the package versions locked when it was deployed
|
||||
- \`jsonlite\` is always available (used internally for argument parsing)
|
||||
- Return values must be JSON-serializable
|
||||
|
||||
|
||||
@@ -1254,7 +1254,8 @@ main <- function(x, name = "default", flag = TRUE) {
|
||||
|
||||
**Important:**
|
||||
- The `main` function is required
|
||||
- Use `library()` to load packages — they are resolved and installed automatically
|
||||
- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()`
|
||||
- A deployed script runs with the package versions locked when it was deployed
|
||||
- `jsonlite` is always available (used internally for argument parsing)
|
||||
- Return values must be JSON-serializable
|
||||
|
||||
|
||||
@@ -94,7 +94,8 @@ main <- function(x, name = "default", flag = TRUE) {
|
||||
|
||||
**Important:**
|
||||
- The `main` function is required
|
||||
- Use `library()` to load packages — they are resolved and installed automatically
|
||||
- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()`
|
||||
- A deployed script runs with the package versions locked when it was deployed
|
||||
- `jsonlite` is always available (used internally for argument parsing)
|
||||
- Return values must be JSON-serializable
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ main <- function(x, name = "default", flag = TRUE) {
|
||||
|
||||
**Important:**
|
||||
- The `main` function is required
|
||||
- Use `library()` to load packages — they are resolved and installed automatically
|
||||
- Use `library()` to load packages — they are resolved and installed automatically, as are packages used through `pkg::fun()`, `require()` and `requireNamespace()`
|
||||
- A deployed script runs with the package versions locked when it was deployed
|
||||
- `jsonlite` is always available (used internally for argument parsing)
|
||||
- Return values must be JSON-serializable
|
||||
|
||||
|
||||
Reference in new issue
Block a user