1use std::fmt;
4
5use reqwest::Method;
6use serde_json::{json, Value};
7use sha2::{Digest, Sha256};
8
9use crate::client::{json_body, Request, RequestOptions, Wellfriend};
10use crate::error::{Error, OperationFailure, Result};
11use crate::file_input::FileInput;
12use crate::generated::models::Quote;
13use crate::generated::resources::Workflows;
14use crate::generated::tools::{tool_spec, ToolId};
15use crate::models::{Operation, OperationState, Workflow, WorkflowStatus};
16use crate::operations;
17use crate::tools::{ToolParameters, ToolResult};
18use crate::uploads;
19use crate::Object;
20
21pub const MAX_PIPELINE_STEPS: usize = 10;
23
24const WORKFLOW_FORBIDDEN_KEYS: &[&str] = &[
26 "code",
27 "script",
28 "command",
29 "executable",
30 "shell",
31 "password",
32 "secret",
33 "token",
34];
35
36#[derive(Debug, Clone, PartialEq)]
48pub struct Step {
49 pub(crate) tool: ToolId,
50 pub(crate) parameters: Object,
51}
52
53impl Step {
54 pub fn new(tool: impl Into<ToolId>) -> Self {
56 Step {
57 tool: tool.into(),
58 parameters: Object::new(),
59 }
60 }
61
62 pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
64 self.parameters = params.into().into_object();
65 self
66 }
67
68 pub fn tool(&self) -> &ToolId {
70 &self.tool
71 }
72
73 pub(crate) fn typed<P: serde::Serialize>(tool: ToolId, params: Option<&P>) -> Self {
74 let parameters = params
75 .and_then(|params| ToolParameters::from_serialize(params).ok())
76 .map(ToolParameters::into_object)
77 .unwrap_or_default();
78 Step { tool, parameters }
79 }
80}
81
82#[derive(Clone)]
103pub struct Pipeline {
104 client: Wellfriend,
105 options: RequestOptions,
106 steps: Vec<Step>,
107}
108
109impl fmt::Debug for Pipeline {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 f.debug_struct("Pipeline")
112 .field("steps", &self.steps)
113 .finish_non_exhaustive()
114 }
115}
116
117impl Wellfriend {
118 pub fn pipeline(&self, steps: impl IntoIterator<Item = Step>) -> Pipeline {
120 Pipeline {
121 client: self.clone(),
122 options: RequestOptions::default(),
123 steps: steps.into_iter().collect(),
124 }
125 }
126
127 pub async fn quote(
129 &self,
130 tool: impl Into<ToolId>,
131 params: Option<ToolParameters>,
132 ) -> Result<Quote> {
133 let body = json!({ "toolId": tool.into().as_str(), "parameters": params.unwrap_or_default().into_object() });
134 let request = Request::new(Method::POST, ["quote"]).json(json_body(&body, None)?);
135 self.json_field(&RequestOptions::default(), request, "quote")
136 .await
137 }
138}
139
140impl Pipeline {
141 pub fn with_options(mut self, options: RequestOptions) -> Self {
144 self.options = options;
145 self
146 }
147
148 pub fn steps(&self) -> &[Step] {
150 &self.steps
151 }
152
153 pub async fn run(&self, input: impl Into<FileInput>) -> Result<ToolResult> {
157 validate(&self.steps, false)?;
158 let client = &self.client;
159 let key = self.options.key();
160 let input = input.into();
161 let stem = input.stem();
162 let stored =
163 uploads::ensure_stored(client, &self.options, input, Some(format!("{key}.upload")))
164 .await?
165 .reference;
166
167 let mut created: Vec<Operation> = Vec::with_capacity(self.steps.len());
168 for (index, step) in self.steps.iter().enumerate() {
169 let mut body = json!({ "toolId": step.tool.as_str(), "parameters": step.parameters });
170 match created.last() {
171 None => {
172 body["documentId"] = json!(stored.document_id);
173 if let Some(version) = &stored.version_id {
174 body["versionId"] = json!(version);
175 }
176 }
177 Some(previous) => body["source"] = json!({ "operationId": previous.id }),
178 }
179 let step_key = format!("{key}.step{}", index + 1);
180 let request = Request::new(Method::POST, ["document-operations"])
181 .json(json_body(&body, Some(&step_key))?)
182 .idempotency_key(step_key);
183 match client
184 .json_field::<Operation>(&self.options, request, "operation")
185 .await
186 {
187 Ok(operation) => created.push(operation),
188 Err(error) if error.code() == Some("SOURCE_FAILED") => {
190 return Err(self.first_failure(&created).await.unwrap_or(error))
191 }
192 Err(error) => return Err(error),
193 }
194 }
195
196 let last = created
197 .last()
198 .map(|operation| operation.id.clone())
199 .unwrap_or_default();
200 match operations::wait_operation(client, &self.options, &last).await {
201 Ok(operation) => {
202 ToolResult::from_operation(client, &self.options, operation, stem).await
203 }
204 Err(Error::OperationFailed(failure)) => {
205 let step = created.len();
206 match self.first_failure(&created).await {
207 Some(earlier) => Err(earlier),
208 None => Err(Error::OperationFailed(Box::new(name_step(
209 *failure,
210 step,
211 &self.steps[step - 1].tool,
212 )))),
213 }
214 }
215 Err(error) => Err(error),
216 }
217 }
218
219 async fn first_failure(&self, created: &[Operation]) -> Option<Error> {
221 let reads = self.options.without_key();
222 for (index, operation) in created.iter().enumerate() {
223 let Ok(current) = operations::get_operation(&self.client, &reads, &operation.id).await
224 else {
225 continue;
226 };
227 if current.state.is_terminal() && current.state != OperationState::Completed {
228 let Error::OperationFailed(failure) = operations::operation_failed(current) else {
229 continue;
230 };
231 return Some(Error::OperationFailed(Box::new(name_step(
232 *failure,
233 index + 1,
234 &self.steps[index].tool,
235 ))));
236 }
237 }
238 None
239 }
240
241 pub async fn quote(&self) -> Result<Quote> {
243 validate(&self.steps, false)?;
244 let steps: Vec<Value> = self
245 .steps
246 .iter()
247 .enumerate()
248 .map(|(index, step)| json!({ "id": format!("step{}", index + 1), "toolId": step.tool.as_str(), "parameters": step.parameters }))
249 .collect();
250 let request = Request::new(Method::POST, ["quote"])
251 .json(json_body(&json!({ "steps": steps }), None)?);
252 self.client
253 .json_field(&self.options.without_key(), request, "quote")
254 .await
255 }
256}
257
258fn name_step(mut failure: OperationFailure, step: usize, tool: &ToolId) -> OperationFailure {
259 failure.step = Some(step);
260 failure.message = if failure.message.is_empty() {
261 format!("step {step} ({tool}) failed")
262 } else {
263 format!("step {step} ({tool}): {}", failure.message)
264 };
265 failure
266}
267
268#[derive(Clone)]
270pub struct DefinedWorkflow {
271 client: Wellfriend,
272 options: RequestOptions,
273 steps: usize,
274 pub workflow: Workflow,
276}
277
278impl fmt::Debug for DefinedWorkflow {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_struct("DefinedWorkflow")
281 .field("workflow", &self.workflow)
282 .finish_non_exhaustive()
283 }
284}
285
286impl DefinedWorkflow {
287 pub fn id(&self) -> &str {
289 &self.workflow.id
290 }
291
292 pub async fn run(&self, input: impl Into<FileInput>) -> Result<ToolResult> {
294 run_workflow(
295 &self.client,
296 &self.options,
297 &self.workflow.id,
298 self.steps,
299 input.into(),
300 )
301 .await
302 }
303}
304
305impl Workflows {
306 pub async fn define(
310 &self,
311 name: &str,
312 steps: impl IntoIterator<Item = Step>,
313 ) -> Result<DefinedWorkflow> {
314 let steps: Vec<Step> = steps.into_iter().collect();
315 validate(&steps, true)?;
316 let key = format!(
319 "sdk-workflow-{}",
320 short_hash(&format!(
321 "{name}\n{}\n{}",
322 steps_json(&steps),
323 graph(&steps)
324 ))
325 );
326 let options = self.options.without_key();
327 let mut body = json!({ "name": name, "description": "Defined with the Wellfriend Rust SDK.", "graph": graph(&steps), "trigger": { "type": "manual" } });
328 body["idempotencyKey"] = json!(key);
329 let request = Request::new(Method::POST, ["workflows"])
330 .json(json_body(&body, None)?)
331 .idempotency_key(key);
332 let mut workflow: Workflow = self
333 .client
334 .json_field(&options, request, "workflow")
335 .await?;
336 if workflow.status != WorkflowStatus::Published {
337 let request =
338 Request::new(Method::POST, ["workflows", workflow.id.as_str(), "publish"])
339 .json(json_body(&json!({}), None)?)
340 .retry_always();
341 workflow = self
342 .client
343 .json_field(&options, request, "workflow")
344 .await?;
345 }
346 Ok(DefinedWorkflow {
347 client: self.client.clone(),
348 options: self.options.clone(),
349 steps: steps.len(),
350 workflow,
351 })
352 }
353}
354
355fn validate(steps: &[Step], workflow: bool) -> Result<()> {
356 if steps.is_empty() || steps.len() > MAX_PIPELINE_STEPS {
357 return Err(Error::InvalidInput(format!(
358 "a pipeline has 1 to {MAX_PIPELINE_STEPS} steps, got {}",
359 steps.len()
360 )));
361 }
362 for (index, step) in steps.iter().enumerate() {
363 if let Some(spec) = tool_spec(step.tool.as_str()) {
364 if spec.min_files > 1 {
365 return Err(Error::InvalidInput(format!(
366 "step {}: {} reads several files and cannot be a pipeline step",
367 index + 1,
368 step.tool
369 )));
370 }
371 }
372 if workflow {
373 if let Some(key) = step
374 .parameters
375 .keys()
376 .find(|key| WORKFLOW_FORBIDDEN_KEYS.contains(&key.to_ascii_lowercase().as_str()))
377 {
378 return Err(Error::InvalidInput(format!(
379 "step {} ({}): a workflow cannot hold the secret parameter `{key}`; use a pipeline instead",
380 index + 1,
381 step.tool
382 )));
383 }
384 }
385 }
386 Ok(())
387}
388
389fn steps_json(steps: &[Step]) -> String {
390 let list: Vec<Value> = steps
391 .iter()
392 .map(|step| json!({ "toolId": step.tool.as_str(), "parameters": step.parameters }))
393 .collect();
394 Value::Array(list).to_string()
395}
396
397fn short_hash(text: &str) -> String {
398 crate::util::hex(&Sha256::digest(text.as_bytes()))[..12].to_owned()
399}
400
401fn graph(steps: &[Step]) -> Value {
406 let mut nodes = Vec::with_capacity(steps.len() + 1);
407 let mut edges = Vec::with_capacity(steps.len());
408 for (index, step) in steps.iter().enumerate() {
409 let id = format!("step{}", index + 1);
410 let mut configuration = json!({ "toolId": step.tool.as_str() });
411 if !step.parameters.is_empty() {
412 configuration["parameters"] = Value::Object(step.parameters.clone());
413 }
414 nodes.push(json!({
415 "id": id,
416 "type": "action",
417 "action": "document-operations.create",
418 "configuration": configuration,
419 "input": { "documentId": "string", "versionId": "string" },
420 "output": { "outputDocumentId": "string", "outputVersionId": "string" },
421 }));
422 let mut edge = json!({ "from": id, "to": "done" });
423 if index + 1 < steps.len() {
424 edge["to"] = json!(format!("step{}", index + 2));
425 edge["mappings"] = json!([
426 { "from": "outputDocumentId", "to": "documentId" },
427 { "from": "outputVersionId", "to": "versionId" },
428 ]);
429 }
430 edges.push(edge);
431 }
432 nodes.push(json!({ "id": "done", "type": "completion" }));
433 json!({ "schemaVersion": "wellfriend-workflow/v2", "startNodeId": "step1", "nodes": nodes, "edges": edges })
434}
435
436fn result_operation_id(run: &crate::models::WorkflowRun, steps: usize) -> Option<String> {
440 let id = |output: &Object, key: &str| {
441 output
442 .get(key)
443 .and_then(Value::as_str)
444 .filter(|id| !id.is_empty())
445 .map(str::to_owned)
446 };
447 id(&run.output, "operationId").or_else(|| {
448 run.step(&format!("step{steps}"))
449 .and_then(|step| id(&step.output, "id"))
450 })
451}
452
453fn recorded_operation(run: &crate::models::WorkflowRun, operation_id: &str) -> Option<Operation> {
455 run.steps
456 .iter()
457 .map(|step| &step.output)
458 .find(|output| output.get("id").and_then(Value::as_str) == Some(operation_id))
459 .and_then(|output| serde_json::from_value(Value::Object(output.clone())).ok())
460}
461
462async fn run_workflow(
463 client: &Wellfriend,
464 options: &RequestOptions,
465 workflow_id: &str,
466 steps: usize,
467 input: FileInput,
468) -> Result<ToolResult> {
469 let stem = input.stem();
470 let key = options.key();
471 let uploaded =
472 uploads::ensure_stored(client, options, input, Some(format!("{key}.upload"))).await?;
473 let mut run_input = json!({ "documentId": uploaded.reference.document_id });
474 if let Some(version) = &uploaded.reference.version_id {
475 run_input["versionId"] = json!(version);
476 }
477 let request = Request::new(Method::POST, ["workflows", workflow_id, "runs"])
478 .json(json_body(&json!({ "input": run_input }), Some(&key))?)
479 .idempotency_key(key);
480 let run: crate::models::WorkflowRun = client.json_field(options, request, "run").await?;
481 let run = operations::wait_run(client, options, &run.id).await?;
482 let Some(operation_id) = result_operation_id(&run, steps) else {
483 return Err(Error::Decode(format!(
484 "workflow run {} finished without a result operation",
485 run.id
486 )));
487 };
488 let operation =
489 match operations::get_operation(client, &options.without_key(), &operation_id).await {
490 Ok(operation) => operation,
491 Err(error) => recorded_operation(&run, &operation_id).ok_or(error)?,
492 };
493 Ok(ToolResult::from_operation(client, options, operation, stem)
494 .await?
495 .with_run(run))
496}
497
498#[cfg(test)]
499mod tests {
500 use super::*;
501
502 #[test]
503 fn the_workflow_graph_chains_each_step_to_the_previous_output() {
504 let steps = vec![
505 Step::new("compress-pdf").params(ToolParameters::new().set("profile", "medium")),
506 Step::new("pdf-to-text"),
507 ];
508 let graph = graph(&steps);
509 assert_eq!(graph["startNodeId"], "step1");
510 assert_eq!(
511 graph["nodes"][0]["configuration"]["parameters"]["profile"],
512 "medium"
513 );
514 assert_eq!(graph["nodes"][1]["input"]["versionId"], "string");
515 assert_eq!(graph["nodes"][1]["output"]["outputVersionId"], "string");
516 assert_eq!(
517 graph["edges"][0]["mappings"],
518 json!([
519 { "from": "outputDocumentId", "to": "documentId" },
520 { "from": "outputVersionId", "to": "versionId" },
521 ])
522 );
523 assert_eq!(graph["edges"][1]["to"], "done");
524 assert!(graph["edges"][1].get("mappings").is_none());
525 }
526
527 #[test]
529 fn the_run_result_is_the_operation_the_run_output_names() {
530 let run = |output: Value| -> crate::models::WorkflowRun {
531 serde_json::from_value(json!({
532 "id": "wfrun_9", "state": "SUCCEEDED", "output": output,
533 "steps": [
534 { "id": "s1", "nodeId": "step1", "state": "SUCCEEDED", "output": { "id": "op_1", "state": "completed" } },
535 { "id": "s2", "nodeId": "step2", "state": "SUCCEEDED", "output": { "id": "op_2", "state": "completed" } },
536 { "id": "s3", "nodeId": "done", "state": "SUCCEEDED", "output": { "completed": true } },
537 ],
538 }))
539 .unwrap()
540 };
541 let named = run(
542 json!({ "operationId": "op_2", "outputDocumentId": "doc_1", "outputVersionId": "ver_2", "steps": {} }),
543 );
544 assert_eq!(
545 result_operation_id(&named, 1).as_deref(),
546 Some("op_2"),
547 "the named operation wins"
548 );
549 let unnamed = run(json!({ "steps": {} }));
550 assert_eq!(result_operation_id(&unnamed, 2).as_deref(), Some("op_2"));
551 assert_eq!(result_operation_id(&run(Value::Null), 3), None);
552 assert_eq!(
553 recorded_operation(&unnamed, "op_1").map(|operation| operation.id),
554 Some("op_1".to_owned())
555 );
556 }
557
558 #[test]
559 fn rejects_bad_step_lists() {
560 let steps: Vec<_> = (0..11).map(|_| Step::new("compress-pdf")).collect();
561 assert!(matches!(
562 validate(&steps, false),
563 Err(Error::InvalidInput(_))
564 ));
565 assert!(matches!(validate(&[], false), Err(Error::InvalidInput(_))));
566 assert!(matches!(
567 validate(&[Step::new("merge-pdf")], false),
568 Err(Error::InvalidInput(_))
569 ));
570 let secret =
571 vec![Step::new("protect-pdf").params(ToolParameters::new().set("password", "x"))];
572 assert!(
573 validate(&secret, false).is_ok(),
574 "a pipeline may carry a password; it is not stored in a workflow"
575 );
576 assert!(
577 matches!(validate(&secret, true), Err(Error::InvalidInput(message)) if message.contains("password"))
578 );
579 }
580
581 #[test]
582 fn failures_name_their_step() {
583 let failure = OperationFailure {
584 code: "PDF_DANGEROUS_CONTENT".into(),
585 message: "unsafe".into(),
586 id: "op".into(),
587 step: None,
588 operation: None,
589 run: None,
590 };
591 let named = name_step(failure, 2, &ToolId::RotatePdf);
592 assert_eq!(named.step, Some(2));
593 assert_eq!(named.message, "step 2 (rotate-pdf): unsafe");
594 }
595}