use std::fmt;
use reqwest::Method;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use crate::client::{json_body, Request, RequestOptions, Wellfriend};
use crate::error::{Error, OperationFailure, Result};
use crate::file_input::FileInput;
use crate::generated::models::Quote;
use crate::generated::resources::Workflows;
use crate::generated::tools::{tool_spec, ToolId};
use crate::models::{Operation, OperationState, Workflow, WorkflowStatus};
use crate::operations;
use crate::tools::{ToolParameters, ToolResult};
use crate::uploads;
use crate::Object;
pub const MAX_PIPELINE_STEPS: usize = 10;
const WORKFLOW_FORBIDDEN_KEYS: &[&str] = &[
"code",
"script",
"command",
"executable",
"shell",
"password",
"secret",
"token",
];
#[derive(Debug, Clone, PartialEq)]
pub struct Step {
pub(crate) tool: ToolId,
pub(crate) parameters: Object,
}
impl Step {
pub fn new(tool: impl Into<ToolId>) -> Self {
Step {
tool: tool.into(),
parameters: Object::new(),
}
}
pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
self.parameters = params.into().into_object();
self
}
pub fn tool(&self) -> &ToolId {
&self.tool
}
pub(crate) fn typed<P: serde::Serialize>(tool: ToolId, params: Option<&P>) -> Self {
let parameters = params
.and_then(|params| ToolParameters::from_serialize(params).ok())
.map(ToolParameters::into_object)
.unwrap_or_default();
Step { tool, parameters }
}
}
#[derive(Clone)]
pub struct Pipeline {
client: Wellfriend,
options: RequestOptions,
steps: Vec<Step>,
}
impl fmt::Debug for Pipeline {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pipeline")
.field("steps", &self.steps)
.finish_non_exhaustive()
}
}
impl Wellfriend {
pub fn pipeline(&self, steps: impl IntoIterator<Item = Step>) -> Pipeline {
Pipeline {
client: self.clone(),
options: RequestOptions::default(),
steps: steps.into_iter().collect(),
}
}
pub async fn quote(
&self,
tool: impl Into<ToolId>,
params: Option<ToolParameters>,
) -> Result<Quote> {
let body = json!({ "toolId": tool.into().as_str(), "parameters": params.unwrap_or_default().into_object() });
let request = Request::new(Method::POST, ["quote"]).json(json_body(&body, None)?);
self.json_field(&RequestOptions::default(), request, "quote")
.await
}
}
impl Pipeline {
pub fn with_options(mut self, options: RequestOptions) -> Self {
self.options = options;
self
}
pub fn steps(&self) -> &[Step] {
&self.steps
}
pub async fn run(&self, input: impl Into<FileInput>) -> Result<ToolResult> {
validate(&self.steps, false)?;
let client = &self.client;
let key = self.options.key();
let input = input.into();
let stem = input.stem();
let stored =
uploads::ensure_stored(client, &self.options, input, Some(format!("{key}.upload")))
.await?
.reference;
let mut created: Vec<Operation> = Vec::with_capacity(self.steps.len());
for (index, step) in self.steps.iter().enumerate() {
let mut body = json!({ "toolId": step.tool.as_str(), "parameters": step.parameters });
match created.last() {
None => {
body["documentId"] = json!(stored.document_id);
if let Some(version) = &stored.version_id {
body["versionId"] = json!(version);
}
}
Some(previous) => body["source"] = json!({ "operationId": previous.id }),
}
let step_key = format!("{key}.step{}", index + 1);
let request = Request::new(Method::POST, ["document-operations"])
.json(json_body(&body, Some(&step_key))?)
.idempotency_key(step_key);
match client
.json_field::<Operation>(&self.options, request, "operation")
.await
{
Ok(operation) => created.push(operation),
Err(error) if error.code() == Some("SOURCE_FAILED") => {
return Err(self.first_failure(&created).await.unwrap_or(error))
}
Err(error) => return Err(error),
}
}
let last = created
.last()
.map(|operation| operation.id.clone())
.unwrap_or_default();
match operations::wait_operation(client, &self.options, &last).await {
Ok(operation) => {
ToolResult::from_operation(client, &self.options, operation, stem).await
}
Err(Error::OperationFailed(failure)) => {
let step = created.len();
match self.first_failure(&created).await {
Some(earlier) => Err(earlier),
None => Err(Error::OperationFailed(Box::new(name_step(
*failure,
step,
&self.steps[step - 1].tool,
)))),
}
}
Err(error) => Err(error),
}
}
async fn first_failure(&self, created: &[Operation]) -> Option<Error> {
let reads = self.options.without_key();
for (index, operation) in created.iter().enumerate() {
let Ok(current) = operations::get_operation(&self.client, &reads, &operation.id).await
else {
continue;
};
if current.state.is_terminal() && current.state != OperationState::Completed {
let Error::OperationFailed(failure) = operations::operation_failed(current) else {
continue;
};
return Some(Error::OperationFailed(Box::new(name_step(
*failure,
index + 1,
&self.steps[index].tool,
))));
}
}
None
}
pub async fn quote(&self) -> Result<Quote> {
validate(&self.steps, false)?;
let steps: Vec<Value> = self
.steps
.iter()
.enumerate()
.map(|(index, step)| json!({ "id": format!("step{}", index + 1), "toolId": step.tool.as_str(), "parameters": step.parameters }))
.collect();
let request = Request::new(Method::POST, ["quote"])
.json(json_body(&json!({ "steps": steps }), None)?);
self.client
.json_field(&self.options.without_key(), request, "quote")
.await
}
}
fn name_step(mut failure: OperationFailure, step: usize, tool: &ToolId) -> OperationFailure {
failure.step = Some(step);
failure.message = if failure.message.is_empty() {
format!("step {step} ({tool}) failed")
} else {
format!("step {step} ({tool}): {}", failure.message)
};
failure
}
#[derive(Clone)]
pub struct DefinedWorkflow {
client: Wellfriend,
options: RequestOptions,
steps: usize,
pub workflow: Workflow,
}
impl fmt::Debug for DefinedWorkflow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DefinedWorkflow")
.field("workflow", &self.workflow)
.finish_non_exhaustive()
}
}
impl DefinedWorkflow {
pub fn id(&self) -> &str {
&self.workflow.id
}
pub async fn run(&self, input: impl Into<FileInput>) -> Result<ToolResult> {
run_workflow(
&self.client,
&self.options,
&self.workflow.id,
self.steps,
input.into(),
)
.await
}
}
impl Workflows {
pub async fn define(
&self,
name: &str,
steps: impl IntoIterator<Item = Step>,
) -> Result<DefinedWorkflow> {
let steps: Vec<Step> = steps.into_iter().collect();
validate(&steps, true)?;
let key = format!(
"sdk-workflow-{}",
short_hash(&format!(
"{name}\n{}\n{}",
steps_json(&steps),
graph(&steps)
))
);
let options = self.options.without_key();
let mut body = json!({ "name": name, "description": "Defined with the Wellfriend Rust SDK.", "graph": graph(&steps), "trigger": { "type": "manual" } });
body["idempotencyKey"] = json!(key);
let request = Request::new(Method::POST, ["workflows"])
.json(json_body(&body, None)?)
.idempotency_key(key);
let mut workflow: Workflow = self
.client
.json_field(&options, request, "workflow")
.await?;
if workflow.status != WorkflowStatus::Published {
let request =
Request::new(Method::POST, ["workflows", workflow.id.as_str(), "publish"])
.json(json_body(&json!({}), None)?)
.retry_always();
workflow = self
.client
.json_field(&options, request, "workflow")
.await?;
}
Ok(DefinedWorkflow {
client: self.client.clone(),
options: self.options.clone(),
steps: steps.len(),
workflow,
})
}
}
fn validate(steps: &[Step], workflow: bool) -> Result<()> {
if steps.is_empty() || steps.len() > MAX_PIPELINE_STEPS {
return Err(Error::InvalidInput(format!(
"a pipeline has 1 to {MAX_PIPELINE_STEPS} steps, got {}",
steps.len()
)));
}
for (index, step) in steps.iter().enumerate() {
if let Some(spec) = tool_spec(step.tool.as_str()) {
if spec.min_files > 1 {
return Err(Error::InvalidInput(format!(
"step {}: {} reads several files and cannot be a pipeline step",
index + 1,
step.tool
)));
}
}
if workflow {
if let Some(key) = step
.parameters
.keys()
.find(|key| WORKFLOW_FORBIDDEN_KEYS.contains(&key.to_ascii_lowercase().as_str()))
{
return Err(Error::InvalidInput(format!(
"step {} ({}): a workflow cannot hold the secret parameter `{key}`; use a pipeline instead",
index + 1,
step.tool
)));
}
}
}
Ok(())
}
fn steps_json(steps: &[Step]) -> String {
let list: Vec<Value> = steps
.iter()
.map(|step| json!({ "toolId": step.tool.as_str(), "parameters": step.parameters }))
.collect();
Value::Array(list).to_string()
}
fn short_hash(text: &str) -> String {
crate::util::hex(&Sha256::digest(text.as_bytes()))[..12].to_owned()
}
fn graph(steps: &[Step]) -> Value {
let mut nodes = Vec::with_capacity(steps.len() + 1);
let mut edges = Vec::with_capacity(steps.len());
for (index, step) in steps.iter().enumerate() {
let id = format!("step{}", index + 1);
let mut configuration = json!({ "toolId": step.tool.as_str() });
if !step.parameters.is_empty() {
configuration["parameters"] = Value::Object(step.parameters.clone());
}
nodes.push(json!({
"id": id,
"type": "action",
"action": "document-operations.create",
"configuration": configuration,
"input": { "documentId": "string", "versionId": "string" },
"output": { "outputDocumentId": "string", "outputVersionId": "string" },
}));
let mut edge = json!({ "from": id, "to": "done" });
if index + 1 < steps.len() {
edge["to"] = json!(format!("step{}", index + 2));
edge["mappings"] = json!([
{ "from": "outputDocumentId", "to": "documentId" },
{ "from": "outputVersionId", "to": "versionId" },
]);
}
edges.push(edge);
}
nodes.push(json!({ "id": "done", "type": "completion" }));
json!({ "schemaVersion": "wellfriend-workflow/v2", "startNodeId": "step1", "nodes": nodes, "edges": edges })
}
fn result_operation_id(run: &crate::models::WorkflowRun, steps: usize) -> Option<String> {
let id = |output: &Object, key: &str| {
output
.get(key)
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.map(str::to_owned)
};
id(&run.output, "operationId").or_else(|| {
run.step(&format!("step{steps}"))
.and_then(|step| id(&step.output, "id"))
})
}
fn recorded_operation(run: &crate::models::WorkflowRun, operation_id: &str) -> Option<Operation> {
run.steps
.iter()
.map(|step| &step.output)
.find(|output| output.get("id").and_then(Value::as_str) == Some(operation_id))
.and_then(|output| serde_json::from_value(Value::Object(output.clone())).ok())
}
async fn run_workflow(
client: &Wellfriend,
options: &RequestOptions,
workflow_id: &str,
steps: usize,
input: FileInput,
) -> Result<ToolResult> {
let stem = input.stem();
let key = options.key();
let uploaded =
uploads::ensure_stored(client, options, input, Some(format!("{key}.upload"))).await?;
let mut run_input = json!({ "documentId": uploaded.reference.document_id });
if let Some(version) = &uploaded.reference.version_id {
run_input["versionId"] = json!(version);
}
let request = Request::new(Method::POST, ["workflows", workflow_id, "runs"])
.json(json_body(&json!({ "input": run_input }), Some(&key))?)
.idempotency_key(key);
let run: crate::models::WorkflowRun = client.json_field(options, request, "run").await?;
let run = operations::wait_run(client, options, &run.id).await?;
let Some(operation_id) = result_operation_id(&run, steps) else {
return Err(Error::Decode(format!(
"workflow run {} finished without a result operation",
run.id
)));
};
let operation =
match operations::get_operation(client, &options.without_key(), &operation_id).await {
Ok(operation) => operation,
Err(error) => recorded_operation(&run, &operation_id).ok_or(error)?,
};
Ok(ToolResult::from_operation(client, options, operation, stem)
.await?
.with_run(run))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_workflow_graph_chains_each_step_to_the_previous_output() {
let steps = vec![
Step::new("compress-pdf").params(ToolParameters::new().set("profile", "medium")),
Step::new("pdf-to-text"),
];
let graph = graph(&steps);
assert_eq!(graph["startNodeId"], "step1");
assert_eq!(
graph["nodes"][0]["configuration"]["parameters"]["profile"],
"medium"
);
assert_eq!(graph["nodes"][1]["input"]["versionId"], "string");
assert_eq!(graph["nodes"][1]["output"]["outputVersionId"], "string");
assert_eq!(
graph["edges"][0]["mappings"],
json!([
{ "from": "outputDocumentId", "to": "documentId" },
{ "from": "outputVersionId", "to": "versionId" },
])
);
assert_eq!(graph["edges"][1]["to"], "done");
assert!(graph["edges"][1].get("mappings").is_none());
}
#[test]
fn the_run_result_is_the_operation_the_run_output_names() {
let run = |output: Value| -> crate::models::WorkflowRun {
serde_json::from_value(json!({
"id": "wfrun_9", "state": "SUCCEEDED", "output": output,
"steps": [
{ "id": "s1", "nodeId": "step1", "state": "SUCCEEDED", "output": { "id": "op_1", "state": "completed" } },
{ "id": "s2", "nodeId": "step2", "state": "SUCCEEDED", "output": { "id": "op_2", "state": "completed" } },
{ "id": "s3", "nodeId": "done", "state": "SUCCEEDED", "output": { "completed": true } },
],
}))
.unwrap()
};
let named = run(
json!({ "operationId": "op_2", "outputDocumentId": "doc_1", "outputVersionId": "ver_2", "steps": {} }),
);
assert_eq!(
result_operation_id(&named, 1).as_deref(),
Some("op_2"),
"the named operation wins"
);
let unnamed = run(json!({ "steps": {} }));
assert_eq!(result_operation_id(&unnamed, 2).as_deref(), Some("op_2"));
assert_eq!(result_operation_id(&run(Value::Null), 3), None);
assert_eq!(
recorded_operation(&unnamed, "op_1").map(|operation| operation.id),
Some("op_1".to_owned())
);
}
#[test]
fn rejects_bad_step_lists() {
let steps: Vec<_> = (0..11).map(|_| Step::new("compress-pdf")).collect();
assert!(matches!(
validate(&steps, false),
Err(Error::InvalidInput(_))
));
assert!(matches!(validate(&[], false), Err(Error::InvalidInput(_))));
assert!(matches!(
validate(&[Step::new("merge-pdf")], false),
Err(Error::InvalidInput(_))
));
let secret =
vec![Step::new("protect-pdf").params(ToolParameters::new().set("password", "x"))];
assert!(
validate(&secret, false).is_ok(),
"a pipeline may carry a password; it is not stored in a workflow"
);
assert!(
matches!(validate(&secret, true), Err(Error::InvalidInput(message)) if message.contains("password"))
);
}
#[test]
fn failures_name_their_step() {
let failure = OperationFailure {
code: "PDF_DANGEROUS_CONTENT".into(),
message: "unsafe".into(),
id: "op".into(),
step: None,
operation: None,
run: None,
};
let named = name_step(failure, 2, &ToolId::RotatePdf);
assert_eq!(named.step, Some(2));
assert_eq!(named.message, "step 2 (rotate-pdf): unsafe");
}
}