wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Pipelines: several tools on one file, each step reading the previous step's output.

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;

/// The most steps one pipeline may have.
pub const MAX_PIPELINE_STEPS: usize = 10;

/// Configuration keys a workflow may not hold (the API refuses inline secrets and code).
const WORKFLOW_FORBIDDEN_KEYS: &[&str] = &[
    "code",
    "script",
    "command",
    "executable",
    "shell",
    "password",
    "secret",
    "token",
];

/// One step of a pipeline: a tool and its parameters.
///
/// There is a typed constructor per tool, for example [`Step::compress_pdf`]; use
/// [`Step::new`] for any tool id:
///
/// ```
/// use wellfriend::{CompressPdfParams, CompressPdfProfile, Step};
///
/// let step = Step::new("compress-pdf").params(CompressPdfParams { profile: Some(CompressPdfProfile::Medium), ..Default::default() });
/// assert_eq!(step.tool().as_str(), "compress-pdf");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Step {
    pub(crate) tool: ToolId,
    pub(crate) parameters: Object,
}

impl Step {
    /// A step running `tool` with no parameters.
    pub fn new(tool: impl Into<ToolId>) -> Self {
        Step {
            tool: tool.into(),
            parameters: Object::new(),
        }
    }

    /// The step's parameters: a typed `...Params` struct or [`ToolParameters`].
    pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
        self.parameters = params.into().into_object();
        self
    }

    /// The tool this step runs.
    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 }
    }
}

/// Several tools run one after another on one file.
///
/// The input is uploaded once. Every step is created at once: the first on the uploaded file,
/// each next one on the output of the step before it (the API holds it in state `waiting` and
/// queues it when that step completes). The pipeline waits for the last step only and returns
/// its result. If a step fails, the steps after it fail too and their request units are given
/// back; the error names the step that failed.
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// use wellfriend::Step;
///
/// let result = wf
///     .pipeline([Step::compress_pdf(None), Step::rotate_pdf(None)])
///     .run("report.pdf")
///     .await?;
/// result.save("report.small.rotated.pdf").await?;
/// # Ok(())
/// # }
/// ```
#[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 {
    /// A pipeline of tool steps (1 to [`MAX_PIPELINE_STEPS`]).
    pub fn pipeline(&self, steps: impl IntoIterator<Item = Step>) -> Pipeline {
        Pipeline {
            client: self.clone(),
            options: RequestOptions::default(),
            steps: steps.into_iter().collect(),
        }
    }

    /// The price of one tool run before sending it. Free: nothing is reserved or recorded.
    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 {
    /// The same pipeline with these options for its calls. An idempotency key covers the whole
    /// run: the upload and each step use keys derived from it.
    pub fn with_options(mut self, options: RequestOptions) -> Self {
        self.options = options;
        self
    }

    /// The steps.
    pub fn steps(&self) -> &[Step] {
        &self.steps
    }

    /// Uploads the input once, creates every step and waits for the last one.
    ///
    /// Fails with [`Error::OperationFailed`] naming the step (1-based) and tool that failed.
    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),
                // The step before failed while this one was being created.
                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),
        }
    }

    /// The first step that ended failed or cancelled, as an error naming it.
    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
    }

    /// The price of the pipeline before running it.
    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
}

/// A workflow defined from tool steps, reusable like a tool.
#[derive(Clone)]
pub struct DefinedWorkflow {
    client: Wellfriend,
    options: RequestOptions,
    steps: usize,
    /// The workflow.
    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 {
    /// The workflow id.
    pub fn id(&self) -> &str {
        &self.workflow.id
    }

    /// Uploads the input, starts a workflow run and waits for its last step.
    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 {
    /// Defines (or finds again) a published workflow whose action nodes run `steps` in order,
    /// for use with triggers and the dashboard. To run tools on a file from code, prefer
    /// [`Wellfriend::pipeline`], which needs no workflow.
    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)?;
        // The key covers the graph, so a definition made before the graph carried its edge
        // mappings is not found again.
        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()
}

/// A linear graph of document-operation nodes: each node after the first reads the version the
/// node before it made. Every step's input starts as the run input (`documentId`, `versionId`);
/// the edge into a step maps the previous operation's `outputDocumentId`/`outputVersionId` over it,
/// as in the graph the TypeScript, Python and Go SDKs build.
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 })
}

/// The operation whose output is the run's result: the one a succeeded run names in its output
/// (`operationId`, beside `outputDocumentId` and `outputVersionId`), else the operation of its
/// last tool step, whose public view is that step's output.
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"))
    })
}

/// The operation as a step of the run recorded it (its public view), when it cannot be read.
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());
    }

    /// A succeeded run names its result operation; without that, the last step's.
    #[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");
    }
}