Files
windmill/backend/windmill-api-client/src/lib.rs
Ruben Fiszel 31d6660d56 feat: script module mode with CLI sync, preview, and WAC UI improvements (#8380)
* feat: add script module mode with folder model for Bun and Python

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add missing modules field to RawCode in bun_executor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* sqlx

* feat: enrich WAC templates with checkpoint and replay semantics

Add prominent comments explaining that all computation must happen
inside task/step/taskScript or it will be replayed on resume/retry.
Clarify that waitForApproval does not hold a worker and that
approve/reject URLs are available in the timeline step details.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(cli): script module sync idempotency, per-module hash tracking, and preview support

- Fix pull→push idempotency: use `??` instead of `||` for module lock
  field so empty strings are preserved (matches API's `lock: ""`)
- Add per-module hash tracking in wmill-lock.yaml following the flow
  inline script pattern (SCRIPT_TOP_HASH + per-module subpath hashes)
- Selective module lock regeneration: only regenerate locks for modules
  whose content actually changed, not all modules
- Use unfiltered rawWorkspaceDependencies for module hashes to match
  what updateModuleLocks passes to fetchScriptLock
- Show changed module names in stale script output for clarity
- Add module support to `script preview` command: read modules from
  __mod/ folder and pass them in the preview API request
- Add preview tests for taskScript pattern (flat and folder layout)
- Update test assertion for module stale detection output

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): WAC UI improvements — reorder templates, module tab rename, import consolidation

- Reorder WAC template buttons: TypeScript before Python in
  ScriptBuilder, CreateActionsScript, and CreateActionsFlow
- Remove dropdown items from +Script button (simplify to direct link)
- Move "Import Workflow-as-Code" to +Flow dropdown with dedicated drawer
- Add module tab rename: pencil icon on hover opens popover with
  validation, fixed-width icon container prevents layout shift

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: remaining module-mode changes from working branch

- Backend parser updates for WAC detection
- CLI sync/types updates for raw app path and module support
- Frontend UI polish (Dev.svelte, ScriptRow, script hash page)
- Test fixture updates

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test(cli): add test for module modification detection in generate-metadata

Verifies that modifying a single module file re-triggers stale
detection and only the changed module is listed, not all modules.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): critical fixes from PR review

- Fix hardcoded dev path in bun_executor.rs WAC v2 wrapper — use
  "windmill-client" import instead of absolute filesystem path
- Fix missed no_main_func → auto_kind rename in parser TS test
- Add modules column to clone_script SQL (windmill-common and
  windmill-api-workspaces) so cloned scripts retain their modules
- Add modules: None to RawCode structs in worker tests
- Restore complete sqlx cache (merge main's cache + our new queries)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix clone warning treated as error in CI

Change `.clone()` on double reference to `*k` dereference in
scripts.rs hash implementation. Update sqlx cache with new query
hashes from modified clone_script SQL.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use published parser wasm versions for CI build

The local file:// paths for windmill-parser-wasm-py and
windmill-parser-wasm-ts don't exist in the Cloudflare Pages build
environment. Revert to published npm versions (1.655.0).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): update parser wasm packages to 1.657.2

Use newly published windmill-parser-wasm-ts and windmill-parser-wasm-py
v1.657.2 which include auto_kind/WAC detection changes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): regenerate package-lock.json for npm ci compatibility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use main's lockfile as base, update only parser wasm packages

Regenerating package-lock.json from scratch pulled different dependency
versions causing svelte-check type errors. Instead, start from main's
lockfile and only update the two changed packages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): add modules column to fetch_script_for_update query

The Script<SR> struct has a modules field (FromRow), but
fetch_script_for_update didn't SELECT modules, causing a runtime
error "no column found for name: modules" when the worker processed
dependency jobs. This was the root cause of the relock_skip test
timeout.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix script module execution for Python and Bun

- Fix modules not passed through job queue: inject _MODULES into
  PushArgs.extra when pushing Code jobs so worker can extract them
- Fix Python module imports: use relative imports (from .helper)
  and add sys.path.insert for module directory in wrapper
- Fix Python tests: use relative imports and empty lock to prevent
  pip from resolving module names as packages
- Add local file check in Bun loader for module resolution
- Ignore Bun module test (bundle mode loader integration tracked
  separately)
- Add missing modules column to fetch_script_for_update query

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): remove unnecessary empty lock in Python module tests

Relative imports (from .helper) are not parsed as pip packages,
so the empty lock workaround is not needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix module execution for Python and Bun — all tests pass

Python modules:
- Use relative imports (from .helper import greet) since scripts run
  as packages
- Add sys.path.insert for module directory in wrapper to ensure local
  modules take precedence over pip packages with same name

Bun modules:
- Use bundled output (./out/main.js) as wrapper import when modules
  are present — the bundled output has module content inlined by
  Bun.build, avoiding runtime loader resolution issues
- Add local file check in loader.bun.js onResolve to short-circuit
  API URL resolution for module files on disk

Job queue:
- Inject _MODULES into PushArgs.extra when pushing Code jobs so
  the worker can extract them at execution time

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: address PR review — simplify, fix correctness, remove dead code

Critical fixes:
- Replace all CLI `no_main_func` references with `auto_kind` (string)
  to match the backend migration and API changes
- Remove duplicated `compute_python_module_dir` in worker.rs, use
  the canonical version from python_executor.rs

High priority:
- Auto-create `__init__.py` in intermediate directories for nested
  Python modules so imports like `from .utils.math import add` work
  without users manually creating __init__.py files
- Remove redundant `sys_path_insert` — relative imports use Python's
  package system, not sys.path

Medium:
- Fix lock file base name extraction: use regex to strip only the
  final extension (`.replace(/\.[^.]+$/, '')`) instead of `indexOf(".")`
  which breaks for files like `helper.test.ts`

Simplification:
- Remove dead `{#if false}` Popover block in ScriptEditor.svelte
- Guard loader.bun.js local file check to only run for relative paths
  (matching the Windows loader pattern)
- Add clarifying comment on Bun dual mechanism (build + run phases)
- Add maintenance comment on manual Hash impl for NewScript

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: final review fixes — stale cleanup, baseName, auto_kind export

- Fix sync.ts baseName extraction using indexOf(".") → regex
  (same fix as script.ts/metadata.ts, missed this instance)
- Add stale module file cleanup in writeModulesToDisk: removes files
  from __mod/ that are no longer in the modules map before writing,
  fixing the pull→push cycle that couldn't delete modules
- Log warning when _MODULES serialization fails in job push instead
  of silently dropping modules
- Use strict equality (===) for auto_kind comparison
- Exclude auto_kind from workspace export — it is auto-detected by
  the parser at deploy time from script content

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(cli): remove auto_kind from push, comparison, and metadata

auto_kind is auto-detected by the parser at deploy time, so the CLI
should not send it, compare it, or write it to script.yaml.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove erroneously added backend/backend/.sqlx directory

Duplicate .sqlx cache was committed at the wrong nested path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review feedback + fix CI dead_code warning

Frontend (ScriptEditor.svelte):
- Fix switchToMain() missing lastSyncedCode update — prevents stale
  code sync on external changes while editing a module tab
- Fix formatAction saving module code to main script's localStorage
  draft — now saves main code when on a module tab
- Fix non-null assertion on inferModuleLang in renameModule — fall
  back to original language instead of force unwrap
- Remove redundant activeModuleTab truthy check in runTest

CLI (script.ts):
- Clean up empty directories after removing stale module files in
  writeModulesToDisk

Backend:
- Add path traversal guard in write_module_files — reject module
  paths containing ".."
- Fix dead_code warning on auto_kind field in workspace export struct

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): improve auto_kind UX + address review findings

- Rename "Include without main function" toggle to "Include library
  scripts" in script list (ItemsList.svelte)
- Update NoMainFuncBadge: "No main" → "Library" with clearer tooltip
- Filter module file extensions by main script language — Python
  scripts only allow .py modules, TypeScript only .ts, etc.
- Split flushModuleState into flushModuleContent (no UI side-effect)
  and flushModuleState (flush + reset tab), reducing duplication
- Dynamic placeholder and hint text in add module popover based on
  main script language

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 01:20:09 +00:00

771 lines
27 KiB
Rust

//! Minimal Windmill API client for tests
//!
//! This is a handwritten minimal client that provides just enough functionality
//! for the integration tests. It replaces the auto-generated progenitor client.
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Client for Windmill API
#[derive(Clone)]
pub struct Client {
pub baseurl: String,
pub client: reqwest::Client,
}
impl Client {
/// Create a new client with an existing reqwest::Client
pub fn new_with_client(baseurl: &str, client: reqwest::Client) -> Self {
Self { baseurl: baseurl.to_string(), client }
}
/// Get the base URL
pub fn baseurl(&self) -> &String {
&self.baseurl
}
/// Get the internal reqwest::Client
pub fn client(&self) -> &reqwest::Client {
&self.client
}
/// Create a script
pub async fn create_script(
&self,
workspace: &str,
body: &types::NewScript,
) -> Result<String, Error> {
let url = format!(
"{}/w/{}/scripts/create",
self.baseurl,
urlencoding::encode(workspace)
);
let response = self.client.post(&url).json(body).send().await?;
if response.status().is_success() {
Ok(response.text().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
/// Create a flow
pub async fn create_flow(
&self,
workspace: &str,
body: &types::CreateFlowBody,
) -> Result<String, Error> {
let url = format!(
"{}/w/{}/flows/create",
self.baseurl,
urlencoding::encode(workspace)
);
let response = self.client.post(&url).json(body).send().await?;
if response.status().is_success() {
Ok(response.text().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
/// Get flow by path
pub async fn get_flow_by_path(
&self,
workspace: &str,
path: &str,
with_starred_info: Option<bool>,
) -> Result<types::Flow, Error> {
let url = format!(
"{}/w/{}/flows/get/{}",
self.baseurl,
urlencoding::encode(workspace),
urlencoding::encode(path)
);
let mut request = self.client.get(&url);
if let Some(starred) = with_starred_info {
request = request.query(&[("with_starred_info", starred.to_string())]);
}
let response = request.send().await?;
if response.status().is_success() {
Ok(response.json().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
/// Create a schedule
pub async fn create_schedule(
&self,
workspace: &str,
body: &types::NewSchedule,
) -> Result<String, Error> {
let url = format!(
"{}/w/{}/schedules/create",
self.baseurl,
urlencoding::encode(workspace)
);
let response = self.client.post(&url).json(body).send().await?;
if response.status().is_success() {
Ok(response.text().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
/// Update a schedule
pub async fn update_schedule(
&self,
workspace: &str,
path: &str,
body: &types::EditSchedule,
) -> Result<String, Error> {
let url = format!(
"{}/w/{}/schedules/update/{}",
self.baseurl,
urlencoding::encode(workspace),
urlencoding::encode(path)
);
let response = self.client.post(&url).json(body).send().await?;
if response.status().is_success() {
Ok(response.text().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
/// List workspaces
pub async fn list_workspaces(&self) -> Result<Vec<types::Workspace>, Error> {
let url = format!("{}/workspaces/list", self.baseurl);
let response = self.client.get(&url).send().await?;
if response.status().is_success() {
Ok(response.json().await?)
} else {
Err(Error::UnexpectedResponse(
response.status().as_u16(),
response.text().await.unwrap_or_default(),
))
}
}
}
/// Create a client with bearer token authentication
pub fn create_client(base_url: &str, token: String) -> Client {
let mut val = HeaderValue::from_str(&format!("Bearer {token}")).expect("header creation");
val.set_sensitive(true);
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, val);
let client = reqwest::ClientBuilder::new()
.default_headers(headers)
.build()
.expect("client build");
Client::new_with_client(&format!("{}/api", base_url.trim_end_matches('/')), client)
}
/// Error type for API client
#[derive(Debug)]
pub enum Error {
/// Request error
Request(reqwest::Error),
/// Unexpected response status
UnexpectedResponse(u16, String),
}
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Self {
Error::Request(err)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Request(e) => write!(f, "Request error: {}", e),
Error::UnexpectedResponse(status, body) => {
write!(f, "Unexpected response ({}): {}", status, body)
}
}
}
}
impl std::error::Error for Error {}
/// API types
pub mod types {
use super::*;
/// Script language
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum ScriptLang {
#[serde(rename = "python3")]
Python3,
#[serde(rename = "deno")]
Deno,
#[serde(rename = "go")]
Go,
#[serde(rename = "bash")]
Bash,
#[serde(rename = "powershell")]
Powershell,
#[serde(rename = "postgresql")]
Postgresql,
#[serde(rename = "mysql")]
Mysql,
#[serde(rename = "bigquery")]
Bigquery,
#[serde(rename = "snowflake")]
Snowflake,
#[serde(rename = "mssql")]
Mssql,
#[serde(rename = "oracledb")]
Oracledb,
#[serde(rename = "graphql")]
Graphql,
#[serde(rename = "nativets")]
Nativets,
#[serde(rename = "bun")]
Bun,
#[serde(rename = "php")]
Php,
#[serde(rename = "rust")]
Rust,
#[serde(rename = "ansible")]
Ansible,
#[serde(rename = "csharp")]
Csharp,
#[serde(rename = "nu")]
Nu,
#[serde(rename = "java")]
Java,
#[serde(rename = "ruby")]
Ruby,
#[serde(rename = "duckdb")]
Duckdb,
}
impl std::str::FromStr for ScriptLang {
type Err = &'static str;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"python3" => Ok(Self::Python3),
"deno" => Ok(Self::Deno),
"go" => Ok(Self::Go),
"bash" => Ok(Self::Bash),
"powershell" => Ok(Self::Powershell),
"postgresql" => Ok(Self::Postgresql),
"mysql" => Ok(Self::Mysql),
"bigquery" => Ok(Self::Bigquery),
"snowflake" => Ok(Self::Snowflake),
"mssql" => Ok(Self::Mssql),
"oracledb" => Ok(Self::Oracledb),
"graphql" => Ok(Self::Graphql),
"nativets" => Ok(Self::Nativets),
"bun" => Ok(Self::Bun),
"php" => Ok(Self::Php),
"rust" => Ok(Self::Rust),
"ansible" => Ok(Self::Ansible),
"csharp" => Ok(Self::Csharp),
"nu" => Ok(Self::Nu),
"java" => Ok(Self::Java),
"ruby" => Ok(Self::Ruby),
"duckdb" => Ok(Self::Duckdb),
_ => Err("invalid script language"),
}
}
}
/// Raw script language (for flow modules)
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum RawScriptLanguage {
#[serde(rename = "python3")]
Python3,
#[serde(rename = "deno")]
Deno,
#[serde(rename = "go")]
Go,
#[serde(rename = "bash")]
Bash,
#[serde(rename = "powershell")]
Powershell,
#[serde(rename = "postgresql")]
Postgresql,
#[serde(rename = "mysql")]
Mysql,
#[serde(rename = "bigquery")]
Bigquery,
#[serde(rename = "snowflake")]
Snowflake,
#[serde(rename = "mssql")]
Mssql,
#[serde(rename = "oracledb")]
Oracledb,
#[serde(rename = "graphql")]
Graphql,
#[serde(rename = "nativets")]
Nativets,
#[serde(rename = "bun")]
Bun,
#[serde(rename = "php")]
Php,
#[serde(rename = "rust")]
Rust,
#[serde(rename = "ansible")]
Ansible,
#[serde(rename = "csharp")]
Csharp,
#[serde(rename = "nu")]
Nu,
#[serde(rename = "java")]
Java,
#[serde(rename = "ruby")]
Ruby,
#[serde(rename = "duckdb")]
Duckdb,
}
/// New script request body
#[derive(Clone, Debug, Serialize)]
pub struct NewScript {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assets: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_ttl: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub codebase: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_time_window_s: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrent_limit: Option<i64>,
pub content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dedicated_worker: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delete_after_use: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deployment_message: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub draft_only: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub envs: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub has_preprocessor: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_template: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
pub language: ScriptLang,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of_email: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_hash: Option<String>,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub restart_unless_cancelled: Option<bool>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub schema: HashMap<String, serde_json::Value>,
pub summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub visible_to_runner_only: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ws_error_handler_muted: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modules: Option<HashMap<String, serde_json::Value>>,
}
/// Script arguments (used in schedules)
pub type ScriptArgs = HashMap<String, serde_json::Value>;
/// New schedule request body
#[derive(Clone, Debug, Serialize)]
pub struct NewSchedule {
pub args: ScriptArgs,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cron_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
pub is_flow: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub no_flow_overlap: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_exact: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_extra_args: Option<ScriptArgs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_times: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery_extra_args: Option<ScriptArgs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery_times: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_success: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_success_extra_args: Option<ScriptArgs>,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry: Option<serde_json::Value>,
pub schedule: String,
pub script_path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
pub timezone: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ws_error_handler_muted: Option<bool>,
}
/// Edit schedule request body
#[derive(Clone, Debug, Serialize)]
pub struct EditSchedule {
pub args: ScriptArgs,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cron_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub no_flow_overlap: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_exact: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_extra_args: Option<ScriptArgs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_failure_times: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery_extra_args: Option<ScriptArgs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_recovery_times: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_success: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_success_extra_args: Option<ScriptArgs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry: Option<serde_json::Value>,
pub schedule: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
pub timezone: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ws_error_handler_muted: Option<bool>,
}
/// Open flow definition
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct OpenFlow {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub schema: HashMap<String, serde_json::Value>,
pub summary: String,
pub value: FlowValue,
}
/// Flow value containing modules
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FlowValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_ttl: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_time_window_s: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrent_limit: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub early_return: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure_module: Option<FlowModule>,
pub modules: Vec<FlowModule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preprocessor_module: Option<FlowModule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub same_worker: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_expr: Option<String>,
}
/// Flow module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FlowModule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_ttl: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub continue_on_error: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delete_after_use: Option<bool>,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mock: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_if: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sleep: Option<InputTransform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stop_after_all_iters_if: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stop_after_if: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspend: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout: Option<InputTransform>,
pub value: FlowModuleValue,
}
/// Input transform
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InputTransform {
Static {
#[serde(rename = "type")]
type_: String,
value: serde_json::Value,
},
Javascript {
#[serde(rename = "type")]
type_: String,
expr: String,
},
}
/// Flow module value (the actual module content)
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FlowModuleValue {
RawScript(RawScript),
Script(ScriptModule),
Flow(FlowModule2),
ForLoop(ForLoopModule),
WhileLoop(WhileLoopModule),
BranchOne(BranchOneModule),
BranchAll(BranchAllModule),
Identity(IdentityModule),
Other(serde_json::Value),
}
/// Raw script module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RawScript {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assets: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrency_time_window_s: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concurrent_limit: Option<f64>,
pub content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub custom_concurrency_key: Option<String>,
pub input_transforms: HashMap<String, InputTransform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_trigger: Option<bool>,
pub language: RawScriptLanguage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
#[serde(rename = "type")]
pub type_: String,
}
impl RawScript {
pub fn new(content: String, language: RawScriptLanguage) -> Self {
Self {
assets: vec![],
concurrency_time_window_s: None,
concurrent_limit: None,
content,
custom_concurrency_key: None,
input_transforms: HashMap::new(),
is_trigger: None,
language,
lock: None,
path: None,
tag: None,
type_: "rawscript".to_string(),
}
}
}
/// Script module reference
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ScriptModule {
#[serde(rename = "type")]
pub type_: String,
pub path: String,
pub input_transforms: HashMap<String, InputTransform>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
}
/// Flow module reference
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FlowModule2 {
#[serde(rename = "type")]
pub type_: String,
pub path: String,
pub input_transforms: HashMap<String, InputTransform>,
}
/// For loop module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ForLoopModule {
#[serde(rename = "type")]
pub type_: String,
pub iterator: InputTransform,
pub modules: Vec<FlowModule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parallel: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parallelism: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_failures: Option<bool>,
}
/// While loop module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WhileLoopModule {
#[serde(rename = "type")]
pub type_: String,
pub modules: Vec<FlowModule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_failures: Option<bool>,
}
/// Branch one module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BranchOneModule {
#[serde(rename = "type")]
pub type_: String,
pub branches: Vec<serde_json::Value>,
pub default: Vec<FlowModule>,
}
/// Branch all module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BranchAllModule {
#[serde(rename = "type")]
pub type_: String,
pub branches: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parallel: Option<bool>,
}
/// Identity module
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IdentityModule {
#[serde(rename = "type")]
pub type_: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flow: Option<bool>,
}
/// Open flow with path
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct OpenFlowWPath {
#[serde(flatten)]
pub open_flow: OpenFlow,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dedicated_worker: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of_email: Option<String>,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub visible_to_runner_only: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ws_error_handler_muted: Option<bool>,
}
/// Create flow request body
#[derive(Clone, Debug, Serialize)]
pub struct CreateFlowBody {
#[serde(flatten)]
pub open_flow_w_path: OpenFlowWPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deployment_message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub draft_only: Option<bool>,
}
/// Flow response type
#[derive(Clone, Debug, Deserialize)]
pub struct Flow {
pub path: String,
#[serde(flatten)]
pub open_flow: OpenFlow,
#[serde(flatten)]
pub extra: HashMap<String, serde_json::Value>,
}
/// Workspace
#[derive(Clone, Debug, Deserialize)]
pub struct Workspace {
pub id: String,
pub name: String,
#[serde(default)]
pub owner: Option<String>,
#[serde(flatten)]
pub extra: HashMap<String, serde_json::Value>,
}
}