Skip to main content

wellfriend/
tools.rs

1//! Running document tools: upload, start, wait, and the result.
2
3use std::fmt;
4use std::path::{Path, PathBuf};
5
6use base64::Engine;
7use bytes::Bytes;
8use futures_util::Stream;
9use reqwest::Method;
10use serde::{Deserialize, Serialize};
11use serde_json::{json, Value};
12
13use crate::client::{json_body, Request, RequestOptions, Wellfriend};
14use crate::download::Download;
15use crate::error::{Error, Result};
16use crate::file_input::{FileInput, ToolInput};
17use crate::generated::tools::{tool_spec, ToolId};
18use crate::models::{Operation, OperationOutputs, Output, WorkflowRun};
19use crate::operations;
20use crate::uploads;
21use crate::Object;
22
23/// Tool parameters as a JSON object. Every generated `...Params` struct converts into it; use
24/// it directly for options this SDK version does not model yet.
25///
26/// ```
27/// use wellfriend::ToolParameters;
28///
29/// let params = ToolParameters::new().set("profile", "medium").set("fastWebView", true);
30/// assert_eq!(params.as_object()["profile"], "medium");
31/// ```
32#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
33#[serde(transparent)]
34pub struct ToolParameters(Object);
35
36impl ToolParameters {
37    /// No parameters.
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Sets one parameter.
43    pub fn set(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
44        self.0.insert(name.into(), value.into());
45        self
46    }
47
48    /// The parameters as a JSON object.
49    pub fn as_object(&self) -> &Object {
50        &self.0
51    }
52
53    /// The parameters as a JSON object, by value.
54    pub fn into_object(self) -> Object {
55        self.0
56    }
57
58    /// Converts any serializable parameter struct.
59    pub fn from_serialize<P: Serialize>(params: &P) -> Result<Self> {
60        match serde_json::to_value(params)
61            .map_err(|error| Error::InvalidInput(error.to_string()))?
62        {
63            Value::Object(map) => Ok(ToolParameters(map)),
64            Value::Null => Ok(ToolParameters::default()),
65            other => Err(Error::InvalidInput(format!(
66                "tool parameters must be an object, got {other}"
67            ))),
68        }
69    }
70}
71
72impl From<Object> for ToolParameters {
73    fn from(map: Object) -> Self {
74        ToolParameters(map)
75    }
76}
77
78/// A named asset file a tool reads (a watermark image, a signature image, a certificate).
79#[derive(Debug)]
80pub enum Asset {
81    /// A file uploaded (or already stored) as a document version.
82    File(FileInput),
83    /// A file sent inline, base64-encoded, and never stored (the tools say which assets take
84    /// this form, for example `certificateFile`).
85    Inline {
86        /// The file content.
87        content: Bytes,
88        /// The file name.
89        file_name: String,
90    },
91}
92
93impl Asset {
94    /// An asset uploaded from a path, bytes or a stored document.
95    pub fn file(input: impl Into<FileInput>) -> Self {
96        Asset::File(input.into())
97    }
98
99    /// An asset sent inline.
100    pub fn inline(content: impl Into<Bytes>, file_name: impl Into<String>) -> Self {
101        Asset::Inline {
102            content: content.into(),
103            file_name: file_name.into(),
104        }
105    }
106}
107
108/// Request units and credits a tool run used, when the API reports them.
109#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct ToolUsage {
112    /// Request units charged.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub request_units: Option<i64>,
115    /// Credits charged.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub credits: Option<i64>,
118    /// Fields this SDK version does not model.
119    #[serde(flatten)]
120    pub extra: Object,
121}
122
123/// Access to the document tools. Get it with [`Wellfriend::tools`].
124///
125/// Each tool has a typed method (generated from the tool catalog) that uploads the input,
126/// starts the operation, waits for it and returns a [`ToolResult`]:
127///
128/// ```no_run
129/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
130/// use wellfriend::{CompressPdfParams, CompressPdfProfile};
131///
132/// let params = CompressPdfParams { profile: Some(CompressPdfProfile::AggressiveLossless), ..Default::default() };
133/// let result = wf.tools().compress_pdf("scan.pdf", Some(params)).await?;
134/// result.save("scan.small.pdf").await?;
135/// # Ok(())
136/// # }
137/// ```
138#[derive(Clone, Debug)]
139pub struct Tools {
140    pub(crate) client: Wellfriend,
141    pub(crate) options: RequestOptions,
142}
143
144impl Wellfriend {
145    /// The document tools.
146    pub fn tools(&self) -> Tools {
147        Tools {
148            client: self.clone(),
149            options: RequestOptions::default(),
150        }
151    }
152}
153
154impl Tools {
155    /// The same handle with these options for every call made through it.
156    pub fn with_options(mut self, options: RequestOptions) -> Self {
157        self.options = options;
158        self
159    }
160
161    /// Runs any tool by id and waits for the result.
162    ///
163    /// ```no_run
164    /// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
165    /// use wellfriend::{ToolId, ToolParameters};
166    ///
167    /// let params = ToolParameters::new().set("profile", "medium");
168    /// wf.tools().run(ToolId::CompressPdf, "in.pdf", Some(params)).await?.save("out.pdf").await?;
169    /// # Ok(())
170    /// # }
171    /// ```
172    pub async fn run(
173        &self,
174        tool: impl Into<ToolId>,
175        input: impl Into<ToolInput>,
176        params: Option<ToolParameters>,
177    ) -> Result<ToolResult> {
178        self.request(tool)
179            .input(input)
180            .params(params.unwrap_or_default())
181            .run()
182            .await
183    }
184
185    /// Starts a tool and returns the operation without waiting for it. Resume later with
186    /// [`DocumentOperations::wait`](crate::DocumentOperations::wait).
187    pub async fn start(
188        &self,
189        tool: impl Into<ToolId>,
190        input: impl Into<ToolInput>,
191        params: Option<ToolParameters>,
192    ) -> Result<Operation> {
193        self.request(tool)
194            .input(input)
195            .params(params.unwrap_or_default())
196            .start()
197            .await
198    }
199
200    /// A request builder, for tools that read named asset files.
201    pub fn request(&self, tool: impl Into<ToolId>) -> ToolRequest {
202        ToolRequest {
203            tools: self.clone(),
204            tool: tool.into(),
205            input: ToolInput::default(),
206            parameters: ToolParameters::default(),
207            assets: Vec::new(),
208        }
209    }
210
211    pub(crate) async fn run_typed<P: Serialize>(
212        &self,
213        tool: ToolId,
214        input: ToolInput,
215        params: Option<&P>,
216    ) -> Result<ToolResult> {
217        let parameters = match params {
218            Some(params) => ToolParameters::from_serialize(params)?,
219            None => ToolParameters::default(),
220        };
221        ToolRequest {
222            tools: self.clone(),
223            tool,
224            input,
225            parameters,
226            assets: Vec::new(),
227        }
228        .run()
229        .await
230    }
231}
232
233/// A tool call with every option: inputs, parameters and named assets.
234///
235/// ```no_run
236/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
237/// use wellfriend::{Asset, ToolId, ToolParameters};
238///
239/// let result = wf
240///     .tools()
241///     .request(ToolId::AddWatermark)
242///     .input("agreement.pdf")
243///     .params(ToolParameters::new().set("type", "image"))
244///     .asset("watermarkImage", Asset::file("logo.png"))
245///     .run()
246///     .await?;
247/// result.save("agreement.watermarked.pdf").await?;
248/// # Ok(())
249/// # }
250/// ```
251#[derive(Debug)]
252pub struct ToolRequest {
253    tools: Tools,
254    tool: ToolId,
255    input: ToolInput,
256    parameters: ToolParameters,
257    assets: Vec<(String, Asset)>,
258}
259
260impl ToolRequest {
261    /// The input file or files.
262    pub fn input(mut self, input: impl Into<ToolInput>) -> Self {
263        self.input = input.into();
264        self
265    }
266
267    /// The tool parameters.
268    pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
269        self.parameters = params.into();
270        self
271    }
272
273    /// A named asset file.
274    pub fn asset(mut self, name: impl Into<String>, asset: Asset) -> Self {
275        self.assets.push((name.into(), asset));
276        self
277    }
278
279    /// Starts the operation and waits for its result.
280    pub async fn run(self) -> Result<ToolResult> {
281        let tools = self.tools.clone();
282        let stem = self.input.files.first().and_then(FileInput::stem);
283        let operation = self.start().await?;
284        let operation =
285            operations::wait_operation(&tools.client, &tools.options, &operation.id).await?;
286        ToolResult::from_operation(&tools.client, &tools.options, operation, stem).await
287    }
288
289    /// Starts the operation and returns it without waiting.
290    pub async fn start(self) -> Result<Operation> {
291        let ToolRequest {
292            tools,
293            tool,
294            input,
295            parameters,
296            assets,
297        } = self;
298        let client = &tools.client;
299        let options = &tools.options;
300        if let Some(spec) = tool_spec(tool.as_str()) {
301            let count = input.files.len();
302            if count < spec.min_files || count > spec.max_files {
303                let wanted = if spec.min_files == spec.max_files {
304                    format!("{}", spec.min_files)
305                } else {
306                    format!("{} to {}", spec.min_files, spec.max_files)
307                };
308                return Err(Error::InvalidInput(format!(
309                    "{tool} takes {wanted} input files, got {count}"
310                )));
311            }
312        } else if input.files.is_empty() {
313            return Err(Error::InvalidInput(format!("{tool} needs an input file")));
314        }
315        let mut stored = Vec::with_capacity(input.files.len());
316        for (index, file) in input.files.into_iter().enumerate() {
317            let key = options.derived_key(&format!("upload{index}"));
318            stored.push(
319                uploads::ensure_stored(client, options, file, key)
320                    .await?
321                    .reference,
322            );
323        }
324        let mut asset_map = Object::new();
325        for (name, asset) in assets {
326            let value = match asset {
327                Asset::File(file) => {
328                    let key = options.derived_key(&format!("asset-{name}"));
329                    let reference = uploads::ensure_stored(client, options, file, key)
330                        .await?
331                        .reference;
332                    serde_json::to_value(reference)
333                        .map_err(|error| Error::InvalidInput(error.to_string()))?
334                }
335                Asset::Inline { content, file_name } => {
336                    json!({ "content": base64::engine::general_purpose::STANDARD.encode(&content), "fileName": file_name })
337                }
338            };
339            asset_map.insert(name, value);
340        }
341        let mut stored = stored.into_iter();
342        let first = stored
343            .next()
344            .ok_or_else(|| Error::InvalidInput(format!("{tool} needs an input file")))?;
345        let mut body = json!({ "toolId": tool.as_str(), "documentId": first.document_id, "parameters": parameters.into_object() });
346        if let Some(version) = first.version_id {
347            body["versionId"] = json!(version);
348        }
349        let rest: Vec<_> = stored.collect();
350        if !rest.is_empty() {
351            body["inputs"] = serde_json::to_value(rest)
352                .map_err(|error| Error::InvalidInput(error.to_string()))?;
353        }
354        if !asset_map.is_empty() {
355            body["assets"] = Value::Object(asset_map);
356        }
357        let key = options.key();
358        let request = Request::new(Method::POST, ["document-operations"])
359            .json(json_body(&body, Some(&key))?)
360            .idempotency_key(key);
361        client.json_field(options, request, "operation").await
362    }
363}
364
365/// The result of a finished tool run or pipeline.
366///
367/// ```no_run
368/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
369/// let result = wf.tools().pdf_to_text("report.pdf", None).await?;
370/// for output in &result.outputs {
371///     println!("{} ({}, {:?} bytes)", output.filename, output.content_type, output.size_bytes);
372/// }
373/// let text = result.bytes().await?;
374/// # Ok(())
375/// # }
376/// ```
377#[non_exhaustive]
378pub struct ToolResult {
379    client: Wellfriend,
380    options: RequestOptions,
381    stem: Option<String>,
382    /// The finished operation (for a pipeline, its last step).
383    pub operation: Operation,
384    /// The output files. Index 0 is the whole output; a ZIP output lists its files after it.
385    pub outputs: Vec<Output>,
386    /// Request units and credits, when the API reports them.
387    pub usage: Option<ToolUsage>,
388    /// The workflow run, for a pipeline or workflow.
389    pub run: Option<WorkflowRun>,
390}
391
392impl fmt::Debug for ToolResult {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        f.debug_struct("ToolResult")
395            .field("operation", &self.operation)
396            .field("outputs", &self.outputs)
397            .field("usage", &self.usage)
398            .field("run", &self.run.as_ref().map(|run| &run.id))
399            .finish_non_exhaustive()
400    }
401}
402
403impl ToolResult {
404    pub(crate) async fn from_operation(
405        client: &Wellfriend,
406        options: &RequestOptions,
407        operation: Operation,
408        stem: Option<String>,
409    ) -> Result<ToolResult> {
410        let reads = options.without_key();
411        let request = Request::new(
412            Method::GET,
413            ["document-operations", operation.id.as_str(), "outputs"],
414        );
415        let outputs = match client.json::<OperationOutputs>(&reads, request).await {
416            Ok(listed) if !listed.outputs.is_empty() => listed.outputs,
417            Ok(_) | Err(Error::NotFound(_)) => fallback_outputs(&operation),
418            Err(error) => return Err(error),
419        };
420        let usage = operation
421            .extra
422            .get("usage")
423            .and_then(|value| serde_json::from_value(value.clone()).ok());
424        Ok(ToolResult {
425            client: client.clone(),
426            options: reads,
427            stem,
428            operation,
429            outputs,
430            usage,
431            run: None,
432        })
433    }
434
435    pub(crate) fn with_run(mut self, run: WorkflowRun) -> Self {
436        self.run = Some(run);
437        self
438    }
439
440    /// The first output: the document and version holding the result.
441    pub fn output(&self) -> Option<&Output> {
442        self.outputs
443            .iter()
444            .find(|output| output.document_id.is_some())
445    }
446
447    /// Opens a streaming download of the first output.
448    pub async fn download(&self) -> Result<Download> {
449        let output = self.output().ok_or_else(|| {
450            Error::Decode(format!(
451                "operation {} has no stored output",
452                self.operation.id
453            ))
454        })?;
455        self.download_output(output).await
456    }
457
458    /// Opens a streaming download of one output.
459    pub async fn download_output(&self, output: &Output) -> Result<Download> {
460        let (Some(document), Some(version)) = (&output.document_id, &output.version_id) else {
461            return Err(Error::InvalidInput(format!(
462                "output {} has not been stored as a document",
463                output.index
464            )));
465        };
466        let request = Request::new(
467            Method::GET,
468            [
469                "documents",
470                document.as_str(),
471                "versions",
472                version.as_str(),
473                "content",
474            ],
475        );
476        Ok(Download::new(
477            self.client.send(&self.options, request).await?,
478        ))
479    }
480
481    /// Saves the result.
482    ///
483    /// When `path` is an existing directory, every stored output is written into it under its own
484    /// file name; otherwise the first output is streamed to `path`. Returns the files written.
485    pub async fn save(&self, path: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
486        let path = path.as_ref();
487        let is_dir = tokio::fs::metadata(path)
488            .await
489            .map(|meta| meta.is_dir())
490            .unwrap_or(false);
491        if !is_dir {
492            self.download().await?.save(path).await?;
493            return Ok(vec![path.to_path_buf()]);
494        }
495        let mut written = Vec::new();
496        for output in self
497            .outputs
498            .iter()
499            .filter(|output| output.document_id.is_some())
500        {
501            let target = path.join(self.file_name_for(output));
502            self.download_output(output).await?.save(&target).await?;
503            written.push(target);
504        }
505        Ok(written)
506    }
507
508    /// The first output in memory. Prefer [`save`](Self::save) or [`stream`](Self::stream) for
509    /// large files.
510    pub async fn bytes(&self) -> Result<Bytes> {
511        self.download().await?.bytes().await
512    }
513
514    /// The first output as a stream of chunks.
515    pub async fn stream(&self) -> Result<impl Stream<Item = Result<Bytes>> + Send + 'static> {
516        Ok(self.download().await?.bytes_stream())
517    }
518
519    /// The default file name for an output: its own name, else `<input-stem>-<tool>.<ext>`.
520    fn file_name_for(&self, output: &Output) -> String {
521        if let Some(name) = crate::util::safe_file_name(&output.filename) {
522            return name;
523        }
524        let extension = tool_spec(self.operation.tool_id.as_str())
525            .map(|spec| spec.output_extension.to_owned())
526            .unwrap_or_else(|| crate::util::extension_for(&output.content_type).to_owned());
527        let stem = self.stem.clone().unwrap_or_else(|| "output".into());
528        format!(
529            "{stem}-{}-{}.{extension}",
530            self.operation.tool_id, output.index
531        )
532    }
533}
534
535/// Outputs built from the operation itself, for an operation whose outputs cannot be listed.
536fn fallback_outputs(operation: &Operation) -> Vec<Output> {
537    match &operation.output_document_id {
538        Some(document) => vec![Output {
539            index: 0,
540            document_id: Some(document.clone()),
541            version_id: operation.output_version_id.clone(),
542            filename: operation.output_file_name().unwrap_or_default().to_owned(),
543            content_type: operation
544                .result
545                .get("mimeType")
546                .and_then(Value::as_str)
547                .unwrap_or_default()
548                .to_owned(),
549            size_bytes: operation.result.get("sizeBytes").and_then(Value::as_u64),
550            extra: Object::new(),
551        }],
552        None => Vec::new(),
553    }
554}