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
use std::fmt;
use std::path::{Path, PathBuf};

use bytes::Bytes;
use tokio::io::AsyncRead;

use crate::models::{Document, VersionRef};

/// A file to process: a local path, bytes in memory, an async reader, or a document that is
/// already stored.
///
/// Anything path-like converts into a `FileInput`, so most calls take a plain string:
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend, data: Vec<u8>) -> wellfriend::Result<()> {
/// use wellfriend::FileInput;
///
/// wf.tools().compress_pdf("scan.pdf", None).await?;                            // a path
/// wf.tools().compress_pdf(FileInput::bytes(data, "scan.pdf"), None).await?;      // bytes
/// wf.tools().compress_pdf(FileInput::document("doc_8kq2W1"), None).await?;       // stored
/// # Ok(())
/// # }
/// ```
///
/// The content type is taken from the file name's extension.
pub struct FileInput {
    pub(crate) source: Source,
    pub(crate) filename: Option<String>,
    pub(crate) content_type: Option<String>,
    pub(crate) sha256: Option<String>,
}

pub(crate) enum Source {
    Path(PathBuf),
    Bytes(Bytes),
    File {
        file: tokio::fs::File,
        size: Option<u64>,
    },
    Reader {
        reader: Box<dyn AsyncRead + Send + Unpin>,
        size: u64,
    },
    Document(VersionRef),
}

impl fmt::Debug for FileInput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let source = match &self.source {
            Source::Path(path) => format!("Path({})", path.display()),
            Source::Bytes(bytes) => format!("Bytes({} bytes)", bytes.len()),
            Source::File { size, .. } => format!("File({size:?} bytes)"),
            Source::Reader { size, .. } => format!("Reader({size} bytes)"),
            Source::Document(reference) => format!("Document({})", reference.document_id),
        };
        f.debug_struct("FileInput")
            .field("source", &source)
            .field("filename", &self.filename)
            .field("content_type", &self.content_type)
            .finish()
    }
}

impl FileInput {
    fn new(source: Source, filename: Option<String>) -> Self {
        FileInput {
            source,
            filename,
            content_type: None,
            sha256: None,
        }
    }

    /// A local file, streamed from disk.
    pub fn path(path: impl AsRef<Path>) -> Self {
        Self::new(Source::Path(path.as_ref().to_path_buf()), None)
    }

    /// Bytes in memory, with the file name to store them under.
    pub fn bytes(data: impl Into<Bytes>, filename: impl Into<String>) -> Self {
        Self::new(Source::Bytes(data.into()), Some(filename.into()))
    }

    /// An open file, streamed from its current position to the end.
    pub fn file(file: tokio::fs::File, filename: impl Into<String>) -> Self {
        Self::new(Source::File { file, size: None }, Some(filename.into()))
    }

    /// Any async reader with its exact size in bytes. Files above the resumable-upload threshold
    /// are sent in parts, holding one part (8 MiB) in memory at a time; above 50 MiB the API
    /// needs the file's SHA-256, so give it with [`FileInput::with_sha256`] or pass a path.
    pub fn reader(
        reader: impl AsyncRead + Send + Unpin + 'static,
        size: u64,
        filename: impl Into<String>,
    ) -> Self {
        Self::new(
            Source::Reader {
                reader: Box::new(reader),
                size,
            },
            Some(filename.into()),
        )
    }

    /// A document already stored in the workspace (its current version). Nothing is uploaded.
    pub fn document(document_id: impl Into<String>) -> Self {
        Self::new(
            Source::Document(VersionRef {
                document_id: document_id.into(),
                version_id: None,
            }),
            None,
        )
    }

    /// One immutable version of a stored document. Nothing is uploaded.
    pub fn version(document_id: impl Into<String>, version_id: impl Into<String>) -> Self {
        Self::new(
            Source::Document(VersionRef {
                document_id: document_id.into(),
                version_id: Some(version_id.into()),
            }),
            None,
        )
    }

    /// Stores the upload under this file name instead of the path's own name.
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Sends this content type instead of the one detected from the file name.
    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    /// The file's SHA-256 in hex, when you already know it. Lets the API skip storing bytes it
    /// already has, and is required for reader inputs above 50 MiB.
    pub fn with_sha256(mut self, sha256: impl Into<String>) -> Self {
        self.sha256 = Some(sha256.into());
        self
    }

    /// True for an input that refers to a stored document.
    pub fn is_document(&self) -> bool {
        matches!(self.source, Source::Document(_))
    }

    /// The file name the upload is stored under.
    pub(crate) fn resolved_filename(&self) -> String {
        if let Some(name) = &self.filename {
            return name.clone();
        }
        match &self.source {
            Source::Path(path) => path
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "upload".into()),
            _ => "upload".into(),
        }
    }

    pub(crate) fn resolved_content_type(&self) -> String {
        self.content_type
            .clone()
            .unwrap_or_else(|| crate::util::content_type_for(&self.resolved_filename()).to_owned())
    }

    /// The stem of the file name, used to name downloads (`in.pdf` → `in`).
    pub(crate) fn stem(&self) -> Option<String> {
        match &self.source {
            Source::Document(_) => None,
            _ => {
                let name = self.resolved_filename();
                Some(
                    name.rsplit_once('.')
                        .map(|(stem, _)| stem.to_owned())
                        .unwrap_or(name),
                )
            }
        }
    }
}

impl From<&str> for FileInput {
    fn from(path: &str) -> Self {
        FileInput::path(path)
    }
}

impl From<String> for FileInput {
    fn from(path: String) -> Self {
        FileInput::path(path)
    }
}

impl From<&String> for FileInput {
    fn from(path: &String) -> Self {
        FileInput::path(path)
    }
}

impl From<&Path> for FileInput {
    fn from(path: &Path) -> Self {
        FileInput::path(path)
    }
}

impl From<PathBuf> for FileInput {
    fn from(path: PathBuf) -> Self {
        FileInput::path(path)
    }
}

impl From<&PathBuf> for FileInput {
    fn from(path: &PathBuf) -> Self {
        FileInput::path(path)
    }
}

impl From<&Document> for FileInput {
    fn from(document: &Document) -> Self {
        match document.current_version_id() {
            Some(version) => FileInput::version(document.id.clone(), version),
            None => FileInput::document(document.id.clone()),
        }
    }
}

impl From<Document> for FileInput {
    fn from(document: Document) -> Self {
        FileInput::from(&document)
    }
}

impl From<VersionRef> for FileInput {
    fn from(reference: VersionRef) -> Self {
        FileInput::new(Source::Document(reference), None)
    }
}

/// The input of a tool run: one file, or several for tools that read several (merge-pdf,
/// image-to-pdf).
#[derive(Debug, Default)]
pub struct ToolInput {
    pub(crate) files: Vec<FileInput>,
}

impl ToolInput {
    /// Several files, in processing order.
    pub fn many<I, F>(files: I) -> Self
    where
        I: IntoIterator<Item = F>,
        F: Into<FileInput>,
    {
        ToolInput {
            files: files.into_iter().map(Into::into).collect(),
        }
    }

    /// The number of files.
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// True when there is no file.
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }
}

macro_rules! single_input {
    ($($ty:ty),*) => {
        $(impl From<$ty> for ToolInput {
            fn from(value: $ty) -> Self {
                ToolInput { files: vec![FileInput::from(value)] }
            }
        })*
    };
}

single_input!(&str, String, &String, &Path, PathBuf, &PathBuf, &Document, Document, VersionRef);

impl From<FileInput> for ToolInput {
    fn from(file: FileInput) -> Self {
        ToolInput { files: vec![file] }
    }
}

impl<F: Into<FileInput>> From<Vec<F>> for ToolInput {
    fn from(files: Vec<F>) -> Self {
        ToolInput::many(files)
    }
}

impl<F: Into<FileInput>, const N: usize> From<[F; N]> for ToolInput {
    fn from(files: [F; N]) -> Self {
        ToolInput::many(files)
    }
}