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
//! Running document tools: upload, start, wait, and the result.

use std::fmt;
use std::path::{Path, PathBuf};

use base64::Engine;
use bytes::Bytes;
use futures_util::Stream;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::client::{json_body, Request, RequestOptions, Wellfriend};
use crate::download::Download;
use crate::error::{Error, Result};
use crate::file_input::{FileInput, ToolInput};
use crate::generated::tools::{tool_spec, ToolId};
use crate::models::{Operation, OperationOutputs, Output, WorkflowRun};
use crate::operations;
use crate::uploads;
use crate::Object;

/// Tool parameters as a JSON object. Every generated `...Params` struct converts into it; use
/// it directly for options this SDK version does not model yet.
///
/// ```
/// use wellfriend::ToolParameters;
///
/// let params = ToolParameters::new().set("profile", "medium").set("fastWebView", true);
/// assert_eq!(params.as_object()["profile"], "medium");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolParameters(Object);

impl ToolParameters {
    /// No parameters.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets one parameter.
    pub fn set(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
        self.0.insert(name.into(), value.into());
        self
    }

    /// The parameters as a JSON object.
    pub fn as_object(&self) -> &Object {
        &self.0
    }

    /// The parameters as a JSON object, by value.
    pub fn into_object(self) -> Object {
        self.0
    }

    /// Converts any serializable parameter struct.
    pub fn from_serialize<P: Serialize>(params: &P) -> Result<Self> {
        match serde_json::to_value(params)
            .map_err(|error| Error::InvalidInput(error.to_string()))?
        {
            Value::Object(map) => Ok(ToolParameters(map)),
            Value::Null => Ok(ToolParameters::default()),
            other => Err(Error::InvalidInput(format!(
                "tool parameters must be an object, got {other}"
            ))),
        }
    }
}

impl From<Object> for ToolParameters {
    fn from(map: Object) -> Self {
        ToolParameters(map)
    }
}

/// A named asset file a tool reads (a watermark image, a signature image, a certificate).
#[derive(Debug)]
pub enum Asset {
    /// A file uploaded (or already stored) as a document version.
    File(FileInput),
    /// A file sent inline, base64-encoded, and never stored (the tools say which assets take
    /// this form, for example `certificateFile`).
    Inline {
        /// The file content.
        content: Bytes,
        /// The file name.
        file_name: String,
    },
}

impl Asset {
    /// An asset uploaded from a path, bytes or a stored document.
    pub fn file(input: impl Into<FileInput>) -> Self {
        Asset::File(input.into())
    }

    /// An asset sent inline.
    pub fn inline(content: impl Into<Bytes>, file_name: impl Into<String>) -> Self {
        Asset::Inline {
            content: content.into(),
            file_name: file_name.into(),
        }
    }
}

/// Request units and credits a tool run used, when the API reports them.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolUsage {
    /// Request units charged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_units: Option<i64>,
    /// Credits charged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credits: Option<i64>,
    /// Fields this SDK version does not model.
    #[serde(flatten)]
    pub extra: Object,
}

/// Access to the document tools. Get it with [`Wellfriend::tools`].
///
/// Each tool has a typed method (generated from the tool catalog) that uploads the input,
/// starts the operation, waits for it and returns a [`ToolResult`]:
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// use wellfriend::{CompressPdfParams, CompressPdfProfile};
///
/// let params = CompressPdfParams { profile: Some(CompressPdfProfile::AggressiveLossless), ..Default::default() };
/// let result = wf.tools().compress_pdf("scan.pdf", Some(params)).await?;
/// result.save("scan.small.pdf").await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Tools {
    pub(crate) client: Wellfriend,
    pub(crate) options: RequestOptions,
}

impl Wellfriend {
    /// The document tools.
    pub fn tools(&self) -> Tools {
        Tools {
            client: self.clone(),
            options: RequestOptions::default(),
        }
    }
}

impl Tools {
    /// The same handle with these options for every call made through it.
    pub fn with_options(mut self, options: RequestOptions) -> Self {
        self.options = options;
        self
    }

    /// Runs any tool by id and waits for the result.
    ///
    /// ```no_run
    /// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
    /// use wellfriend::{ToolId, ToolParameters};
    ///
    /// let params = ToolParameters::new().set("profile", "medium");
    /// wf.tools().run(ToolId::CompressPdf, "in.pdf", Some(params)).await?.save("out.pdf").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run(
        &self,
        tool: impl Into<ToolId>,
        input: impl Into<ToolInput>,
        params: Option<ToolParameters>,
    ) -> Result<ToolResult> {
        self.request(tool)
            .input(input)
            .params(params.unwrap_or_default())
            .run()
            .await
    }

    /// Starts a tool and returns the operation without waiting for it. Resume later with
    /// [`DocumentOperations::wait`](crate::DocumentOperations::wait).
    pub async fn start(
        &self,
        tool: impl Into<ToolId>,
        input: impl Into<ToolInput>,
        params: Option<ToolParameters>,
    ) -> Result<Operation> {
        self.request(tool)
            .input(input)
            .params(params.unwrap_or_default())
            .start()
            .await
    }

    /// A request builder, for tools that read named asset files.
    pub fn request(&self, tool: impl Into<ToolId>) -> ToolRequest {
        ToolRequest {
            tools: self.clone(),
            tool: tool.into(),
            input: ToolInput::default(),
            parameters: ToolParameters::default(),
            assets: Vec::new(),
        }
    }

    pub(crate) async fn run_typed<P: Serialize>(
        &self,
        tool: ToolId,
        input: ToolInput,
        params: Option<&P>,
    ) -> Result<ToolResult> {
        let parameters = match params {
            Some(params) => ToolParameters::from_serialize(params)?,
            None => ToolParameters::default(),
        };
        ToolRequest {
            tools: self.clone(),
            tool,
            input,
            parameters,
            assets: Vec::new(),
        }
        .run()
        .await
    }
}

/// A tool call with every option: inputs, parameters and named assets.
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// use wellfriend::{Asset, ToolId, ToolParameters};
///
/// let result = wf
///     .tools()
///     .request(ToolId::AddWatermark)
///     .input("agreement.pdf")
///     .params(ToolParameters::new().set("type", "image"))
///     .asset("watermarkImage", Asset::file("logo.png"))
///     .run()
///     .await?;
/// result.save("agreement.watermarked.pdf").await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ToolRequest {
    tools: Tools,
    tool: ToolId,
    input: ToolInput,
    parameters: ToolParameters,
    assets: Vec<(String, Asset)>,
}

impl ToolRequest {
    /// The input file or files.
    pub fn input(mut self, input: impl Into<ToolInput>) -> Self {
        self.input = input.into();
        self
    }

    /// The tool parameters.
    pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
        self.parameters = params.into();
        self
    }

    /// A named asset file.
    pub fn asset(mut self, name: impl Into<String>, asset: Asset) -> Self {
        self.assets.push((name.into(), asset));
        self
    }

    /// Starts the operation and waits for its result.
    pub async fn run(self) -> Result<ToolResult> {
        let tools = self.tools.clone();
        let stem = self.input.files.first().and_then(FileInput::stem);
        let operation = self.start().await?;
        let operation =
            operations::wait_operation(&tools.client, &tools.options, &operation.id).await?;
        ToolResult::from_operation(&tools.client, &tools.options, operation, stem).await
    }

    /// Starts the operation and returns it without waiting.
    pub async fn start(self) -> Result<Operation> {
        let ToolRequest {
            tools,
            tool,
            input,
            parameters,
            assets,
        } = self;
        let client = &tools.client;
        let options = &tools.options;
        if let Some(spec) = tool_spec(tool.as_str()) {
            let count = input.files.len();
            if count < spec.min_files || count > spec.max_files {
                let wanted = if spec.min_files == spec.max_files {
                    format!("{}", spec.min_files)
                } else {
                    format!("{} to {}", spec.min_files, spec.max_files)
                };
                return Err(Error::InvalidInput(format!(
                    "{tool} takes {wanted} input files, got {count}"
                )));
            }
        } else if input.files.is_empty() {
            return Err(Error::InvalidInput(format!("{tool} needs an input file")));
        }
        let mut stored = Vec::with_capacity(input.files.len());
        for (index, file) in input.files.into_iter().enumerate() {
            let key = options.derived_key(&format!("upload{index}"));
            stored.push(
                uploads::ensure_stored(client, options, file, key)
                    .await?
                    .reference,
            );
        }
        let mut asset_map = Object::new();
        for (name, asset) in assets {
            let value = match asset {
                Asset::File(file) => {
                    let key = options.derived_key(&format!("asset-{name}"));
                    let reference = uploads::ensure_stored(client, options, file, key)
                        .await?
                        .reference;
                    serde_json::to_value(reference)
                        .map_err(|error| Error::InvalidInput(error.to_string()))?
                }
                Asset::Inline { content, file_name } => {
                    json!({ "content": base64::engine::general_purpose::STANDARD.encode(&content), "fileName": file_name })
                }
            };
            asset_map.insert(name, value);
        }
        let mut stored = stored.into_iter();
        let first = stored
            .next()
            .ok_or_else(|| Error::InvalidInput(format!("{tool} needs an input file")))?;
        let mut body = json!({ "toolId": tool.as_str(), "documentId": first.document_id, "parameters": parameters.into_object() });
        if let Some(version) = first.version_id {
            body["versionId"] = json!(version);
        }
        let rest: Vec<_> = stored.collect();
        if !rest.is_empty() {
            body["inputs"] = serde_json::to_value(rest)
                .map_err(|error| Error::InvalidInput(error.to_string()))?;
        }
        if !asset_map.is_empty() {
            body["assets"] = Value::Object(asset_map);
        }
        let key = options.key();
        let request = Request::new(Method::POST, ["document-operations"])
            .json(json_body(&body, Some(&key))?)
            .idempotency_key(key);
        client.json_field(options, request, "operation").await
    }
}

/// The result of a finished tool run or pipeline.
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// let result = wf.tools().pdf_to_text("report.pdf", None).await?;
/// for output in &result.outputs {
///     println!("{} ({}, {:?} bytes)", output.filename, output.content_type, output.size_bytes);
/// }
/// let text = result.bytes().await?;
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
pub struct ToolResult {
    client: Wellfriend,
    options: RequestOptions,
    stem: Option<String>,
    /// The finished operation (for a pipeline, its last step).
    pub operation: Operation,
    /// The output files. Index 0 is the whole output; a ZIP output lists its files after it.
    pub outputs: Vec<Output>,
    /// Request units and credits, when the API reports them.
    pub usage: Option<ToolUsage>,
    /// The workflow run, for a pipeline or workflow.
    pub run: Option<WorkflowRun>,
}

impl fmt::Debug for ToolResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolResult")
            .field("operation", &self.operation)
            .field("outputs", &self.outputs)
            .field("usage", &self.usage)
            .field("run", &self.run.as_ref().map(|run| &run.id))
            .finish_non_exhaustive()
    }
}

impl ToolResult {
    pub(crate) async fn from_operation(
        client: &Wellfriend,
        options: &RequestOptions,
        operation: Operation,
        stem: Option<String>,
    ) -> Result<ToolResult> {
        let reads = options.without_key();
        let request = Request::new(
            Method::GET,
            ["document-operations", operation.id.as_str(), "outputs"],
        );
        let outputs = match client.json::<OperationOutputs>(&reads, request).await {
            Ok(listed) if !listed.outputs.is_empty() => listed.outputs,
            Ok(_) | Err(Error::NotFound(_)) => fallback_outputs(&operation),
            Err(error) => return Err(error),
        };
        let usage = operation
            .extra
            .get("usage")
            .and_then(|value| serde_json::from_value(value.clone()).ok());
        Ok(ToolResult {
            client: client.clone(),
            options: reads,
            stem,
            operation,
            outputs,
            usage,
            run: None,
        })
    }

    pub(crate) fn with_run(mut self, run: WorkflowRun) -> Self {
        self.run = Some(run);
        self
    }

    /// The first output: the document and version holding the result.
    pub fn output(&self) -> Option<&Output> {
        self.outputs
            .iter()
            .find(|output| output.document_id.is_some())
    }

    /// Opens a streaming download of the first output.
    pub async fn download(&self) -> Result<Download> {
        let output = self.output().ok_or_else(|| {
            Error::Decode(format!(
                "operation {} has no stored output",
                self.operation.id
            ))
        })?;
        self.download_output(output).await
    }

    /// Opens a streaming download of one output.
    pub async fn download_output(&self, output: &Output) -> Result<Download> {
        let (Some(document), Some(version)) = (&output.document_id, &output.version_id) else {
            return Err(Error::InvalidInput(format!(
                "output {} has not been stored as a document",
                output.index
            )));
        };
        let request = Request::new(
            Method::GET,
            [
                "documents",
                document.as_str(),
                "versions",
                version.as_str(),
                "content",
            ],
        );
        Ok(Download::new(
            self.client.send(&self.options, request).await?,
        ))
    }

    /// Saves the result.
    ///
    /// When `path` is an existing directory, every stored output is written into it under its own
    /// file name; otherwise the first output is streamed to `path`. Returns the files written.
    pub async fn save(&self, path: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
        let path = path.as_ref();
        let is_dir = tokio::fs::metadata(path)
            .await
            .map(|meta| meta.is_dir())
            .unwrap_or(false);
        if !is_dir {
            self.download().await?.save(path).await?;
            return Ok(vec![path.to_path_buf()]);
        }
        let mut written = Vec::new();
        for output in self
            .outputs
            .iter()
            .filter(|output| output.document_id.is_some())
        {
            let target = path.join(self.file_name_for(output));
            self.download_output(output).await?.save(&target).await?;
            written.push(target);
        }
        Ok(written)
    }

    /// The first output in memory. Prefer [`save`](Self::save) or [`stream`](Self::stream) for
    /// large files.
    pub async fn bytes(&self) -> Result<Bytes> {
        self.download().await?.bytes().await
    }

    /// The first output as a stream of chunks.
    pub async fn stream(&self) -> Result<impl Stream<Item = Result<Bytes>> + Send + 'static> {
        Ok(self.download().await?.bytes_stream())
    }

    /// The default file name for an output: its own name, else `<input-stem>-<tool>.<ext>`.
    fn file_name_for(&self, output: &Output) -> String {
        if let Some(name) = crate::util::safe_file_name(&output.filename) {
            return name;
        }
        let extension = tool_spec(self.operation.tool_id.as_str())
            .map(|spec| spec.output_extension.to_owned())
            .unwrap_or_else(|| crate::util::extension_for(&output.content_type).to_owned());
        let stem = self.stem.clone().unwrap_or_else(|| "output".into());
        format!(
            "{stem}-{}-{}.{extension}",
            self.operation.tool_id, output.index
        )
    }
}

/// Outputs built from the operation itself, for an operation whose outputs cannot be listed.
fn fallback_outputs(operation: &Operation) -> Vec<Output> {
    match &operation.output_document_id {
        Some(document) => vec![Output {
            index: 0,
            document_id: Some(document.clone()),
            version_id: operation.output_version_id.clone(),
            filename: operation.output_file_name().unwrap_or_default().to_owned(),
            content_type: operation
                .result
                .get("mimeType")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned(),
            size_bytes: operation.result.get("sizeBytes").and_then(Value::as_u64),
            extra: Object::new(),
        }],
        None => Vec::new(),
    }
}