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
596
597
598
599
600
601
602
603
604
//! Uploads: one streamed request up to 100 MiB, the resumable multipart flow above it.

use std::io::SeekFrom;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use bytes::{Bytes, BytesMut};
use futures_util::stream;
use reqwest::Method;
use serde_json::json;
use sha2::{Digest, Sha256};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt};

use crate::client::{json_body, BodyFuture, Request, RequestBody, RequestOptions, Wellfriend};
use crate::error::{Error, Result};
use crate::file_input::{FileInput, Source};
use crate::generated::models::{Upload, UploadPart, UploadStatus};
use crate::models::{Document, UploadCompletion, VersionRef};

/// The largest body one upload request may carry (100 MiB). Larger files use the resumable flow.
pub const SINGLE_REQUEST_MAX_BYTES: u64 = 100 * 1024 * 1024;
/// Above this size (50 MiB) a resumable upload must declare the file's SHA-256.
pub const CHECKSUM_REQUIRED_ABOVE_BYTES: u64 = 50 * 1024 * 1024;
const READ_CHUNK: usize = 64 * 1024;

/// What an upload produced.
pub(crate) struct Uploaded {
    pub(crate) reference: VersionRef,
    pub(crate) document: Option<Document>,
}

/// Makes sure the input is stored and returns its document version. A stored document is used
/// as it is.
pub(crate) async fn ensure_stored(
    client: &Wellfriend,
    options: &RequestOptions,
    input: FileInput,
    key: Option<String>,
) -> Result<Uploaded> {
    if let Source::Document(reference) = input.source {
        return Ok(Uploaded {
            reference,
            document: None,
        });
    }
    upload(client, options, input, key).await
}

/// Uploads a local input as a new document.
pub(crate) async fn upload(
    client: &Wellfriend,
    options: &RequestOptions,
    input: FileInput,
    key: Option<String>,
) -> Result<Uploaded> {
    let filename = input.resolved_filename();
    let content_type = input.resolved_content_type();
    let declared_sha = input.sha256.clone();
    let key = key.unwrap_or_else(|| options.key());
    let content = Content::open(input.source).await?;
    let size = content.size();
    if size == 0 {
        return Err(Error::InvalidInput(format!("{filename} is empty")));
    }
    if size <= client.inner.upload_threshold {
        let document = direct(
            client,
            options,
            content,
            &filename,
            &content_type,
            declared_sha.as_deref(),
            &key,
        )
        .await?;
        let reference = VersionRef {
            document_id: document.id.clone(),
            version_id: document.current_version_id().map(str::to_owned),
        };
        return Ok(Uploaded {
            reference,
            document: Some(document),
        });
    }
    let reference = multipart(
        client,
        options,
        content,
        &filename,
        &content_type,
        declared_sha,
        &key,
    )
    .await?;
    Ok(Uploaded {
        reference,
        document: None,
    })
}

/// Uploads a local input and returns the stored document.
pub(crate) async fn upload_document(
    client: &Wellfriend,
    options: &RequestOptions,
    input: FileInput,
) -> Result<Document> {
    let uploaded = upload(client, options, input, None).await?;
    match uploaded.document {
        Some(document) => Ok(document),
        None => {
            let request = Request::new(
                Method::GET,
                ["documents", uploaded.reference.document_id.as_str()],
            );
            client
                .json_field(&options.without_key(), request, "document")
                .await
        }
    }
}

/// A local input as a raw request body (for endpoints that take the file itself).
pub(crate) async fn file_body(input: FileInput, content_type: &str) -> Result<RequestBody> {
    let content = Content::open(input.source).await?;
    Ok(content.into_body(content_type.to_owned()))
}

/// `POST /documents` with the body streamed from its source.
async fn direct(
    client: &Wellfriend,
    options: &RequestOptions,
    content: Content,
    filename: &str,
    content_type: &str,
    sha256: Option<&str>,
    key: &str,
) -> Result<Document> {
    let size = content.size();
    let replayable = content.replayable();
    let body = content.into_body(content_type.to_owned());
    let mut request = Request::new(Method::POST, ["documents"])
        .body(body)
        .header("x-wellfriend-filename", &header_safe(filename))
        .idempotency_key(key);
    if let Some(sha) = sha256 {
        request = request.header("x-content-sha256", sha);
    }
    debug_assert!(size <= client.inner.upload_threshold);
    let options = if replayable {
        options.clone()
    } else {
        options.clone().max_retries(0)
    };
    client.json_field(&options, request, "document").await
}

/// The resumable flow: create the upload, send each missing part, complete, and wait for the
/// document.
async fn multipart(
    client: &Wellfriend,
    options: &RequestOptions,
    mut content: Content,
    filename: &str,
    content_type: &str,
    declared_sha: Option<String>,
    key: &str,
) -> Result<VersionRef> {
    let size = content.size();
    let sha256 = match declared_sha {
        Some(sha) => Some(sha),
        None if size > CHECKSUM_REQUIRED_ABOVE_BYTES => Some(content.sha256().await?),
        None => None,
    };
    let mut create =
        json!({ "filename": filename, "contentType": content_type, "sizeBytes": size });
    if let Some(sha) = &sha256 {
        create["sha256"] = json!(sha);
    }
    let request = Request::new(Method::POST, ["uploads"])
        .json(json_body(&create, None)?)
        .idempotency_key(key);
    let upload: Upload = client.json(options, request).await?;
    let reads = options.without_key();
    if let Some(reference) = finished(&upload)? {
        return Ok(reference);
    }
    let part_size = u64::try_from(upload.part_size_bytes)
        .ok()
        .filter(|size| *size > 0)
        .ok_or_else(|| Error::Decode("the upload has no part size".into()))?;
    let part_count = size.div_ceil(part_size);
    for index in 0..part_count {
        let length = part_size.min(size - index * part_size);
        let already = upload
            .received_parts
            .iter()
            .any(|received| u64::try_from(*received) == Ok(index));
        let part = content.part(index * part_size, length, already).await?;
        let Some(part) = part else { continue };
        let digest = crate::util::hex(&Sha256::digest(&part));
        let request = Request::new(
            Method::PUT,
            [
                "uploads".to_owned(),
                upload.upload_id.clone(),
                "parts".to_owned(),
                index.to_string(),
            ],
        )
        .body(RequestBody::Bytes {
            data: part,
            content_type: "application/octet-stream".into(),
        })
        .header("x-part-sha256", &digest)
        .retry_always();
        let _: UploadPart = client.json(&reads, request).await?;
    }
    let request = Request::new(
        Method::POST,
        [
            "uploads".to_owned(),
            upload.upload_id.clone(),
            "complete".to_owned(),
        ],
    )
    .json(Bytes::from_static(b"{}"))
    .retry_always();
    match client.json::<UploadCompletion>(&reads, request).await? {
        UploadCompletion::Document { document, .. } => {
            let version_id = document.current_version_id().map(str::to_owned);
            Ok(VersionRef {
                document_id: document.id,
                version_id,
            })
        }
        UploadCompletion::Pending(pending) => wait_for_upload(client, &reads, pending).await,
    }
}

/// The document of a finished upload, an error for a dead one, `None` while it is open.
fn finished(upload: &Upload) -> Result<Option<VersionRef>> {
    match &upload.status {
        UploadStatus::Completed => match &upload.document_id {
            Some(document_id) => Ok(Some(VersionRef {
                document_id: document_id.clone(),
                version_id: upload.version_id.clone(),
            })),
            None => Err(Error::Decode(
                "the upload completed without a document".into(),
            )),
        },
        UploadStatus::Failed | UploadStatus::Cancelled | UploadStatus::Expired => {
            let code = upload
                .error
                .as_ref()
                .and_then(|error| error.get("code"))
                .and_then(|code| code.as_str())
                .unwrap_or("UPLOAD_FAILED")
                .to_owned();
            let message = upload
                .error
                .as_ref()
                .and_then(|error| error.get("message"))
                .and_then(|m| m.as_str())
                .unwrap_or_default()
                .to_owned();
            Err(Error::OperationFailed(Box::new(
                crate::error::OperationFailure {
                    code,
                    message: if message.is_empty() {
                        format!("the upload is {}", upload.status)
                    } else {
                        message
                    },
                    id: upload.upload_id.clone(),
                    step: None,
                    operation: None,
                    run: None,
                },
            )))
        }
        _ => Ok(None),
    }
}

async fn wait_for_upload(
    client: &Wellfriend,
    options: &RequestOptions,
    mut upload: Upload,
) -> Result<VersionRef> {
    let started = Instant::now();
    let limit = options.wait_limit(client);
    let mut delay = Duration::from_millis(500);
    loop {
        if let Some(reference) = finished(&upload)? {
            return Ok(reference);
        }
        if started.elapsed() >= limit {
            return Err(Error::WaitTimeout {
                kind: "upload",
                id: upload.upload_id,
                waited: started.elapsed(),
            });
        }
        tokio::time::sleep(delay).await;
        delay = (delay.mul_f64(1.5)).min(Duration::from_secs(5));
        upload = client
            .json(
                options,
                Request::new(
                    Method::GET,
                    ["uploads".to_owned(), upload.upload_id.clone()],
                ),
            )
            .await?;
    }
}

/// Header values must be visible ASCII; other characters in a file name are percent-encoded.
fn header_safe(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for byte in name.bytes() {
        if (0x20..0x7f).contains(&byte) && byte != b'%' {
            out.push(byte as char);
        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }
    out
}

/// An upload source with a known size.
enum Content {
    Path {
        path: PathBuf,
        size: u64,
        file: Option<tokio::fs::File>,
    },
    Bytes(Bytes),
    File {
        file: tokio::fs::File,
        start: u64,
        size: u64,
    },
    Reader {
        reader: Box<dyn AsyncRead + Send + Unpin>,
        size: u64,
        position: u64,
    },
}

impl Content {
    async fn open(source: Source) -> Result<Self> {
        Ok(match source {
            Source::Path(path) => {
                let file = tokio::fs::File::open(&path)
                    .await
                    .map_err(|error| io_context(error, &path))?;
                let size = file.metadata().await?.len();
                Content::Path {
                    path,
                    size,
                    file: Some(file),
                }
            }
            Source::Bytes(bytes) => Content::Bytes(bytes),
            Source::File { mut file, size } => {
                let start = file.stream_position().await?;
                let size = match size {
                    Some(size) => size,
                    None => file.metadata().await?.len().saturating_sub(start),
                };
                Content::File { file, start, size }
            }
            Source::Reader { reader, size } => Content::Reader {
                reader,
                size,
                position: 0,
            },
            Source::Document(_) => {
                return Err(Error::InvalidInput(
                    "a stored document is not uploaded again".into(),
                ))
            }
        })
    }

    fn size(&self) -> u64 {
        match self {
            Content::Path { size, .. }
            | Content::File { size, .. }
            | Content::Reader { size, .. } => *size,
            Content::Bytes(bytes) => bytes.len() as u64,
        }
    }

    /// Whether the body can be produced again for a retry.
    fn replayable(&self) -> bool {
        !matches!(self, Content::Reader { .. })
    }

    /// The whole content as a streamed request body.
    fn into_body(self, content_type: String) -> RequestBody {
        match self {
            Content::Bytes(data) => RequestBody::Bytes { data, content_type },
            Content::Path { path, size, .. } => {
                let open = Arc::new(move || -> BodyFuture {
                    let path = path.clone();
                    Box::pin(async move {
                        let file = tokio::fs::File::open(&path).await?;
                        Ok(reqwest::Body::wrap_stream(read_stream(file, size)))
                    })
                });
                RequestBody::Stream {
                    open,
                    length: size,
                    content_type,
                }
            }
            Content::File { file, start, size } => {
                let shared = Arc::new(tokio::sync::Mutex::new(file));
                let open = Arc::new(move || -> BodyFuture {
                    let shared = shared.clone();
                    Box::pin(async move {
                        let mut file = shared.lock().await.try_clone().await?;
                        file.seek(SeekFrom::Start(start)).await?;
                        Ok(reqwest::Body::wrap_stream(read_stream(file, size)))
                    })
                });
                RequestBody::Stream {
                    open,
                    length: size,
                    content_type,
                }
            }
            Content::Reader { reader, size, .. } => {
                let slot = Arc::new(Mutex::new(Some(reader)));
                let open = Arc::new(move || -> BodyFuture {
                    let taken = slot.lock().ok().and_then(|mut slot| slot.take());
                    Box::pin(async move {
                        match taken {
                            Some(reader) => {
                                Ok(reqwest::Body::wrap_stream(read_stream(reader, size)))
                            }
                            None => Err(std::io::Error::other(
                                "a reader input can be sent only once",
                            )),
                        }
                    })
                });
                RequestBody::Stream {
                    open,
                    length: size,
                    content_type,
                }
            }
        }
    }

    /// The SHA-256 of the whole content, read once as a stream.
    async fn sha256(&mut self) -> Result<String> {
        let mut hasher = Sha256::new();
        let mut buffer = vec![0u8; READ_CHUNK];
        match self {
            Content::Bytes(bytes) => hasher.update(bytes),
            Content::Path { path, .. } => {
                let mut file = tokio::fs::File::open(&*path).await?;
                loop {
                    let read = file.read(&mut buffer).await?;
                    if read == 0 {
                        break;
                    }
                    hasher.update(&buffer[..read]);
                }
            }
            Content::File { file, start, size } => {
                file.seek(SeekFrom::Start(*start)).await?;
                let mut remaining = *size;
                while remaining > 0 {
                    let want = buffer.len().min(remaining as usize);
                    let read = file.read(&mut buffer[..want]).await?;
                    if read == 0 {
                        return Err(Error::InvalidInput("the file ended before its declared size".into()));
                    }
                    hasher.update(&buffer[..read]);
                    remaining -= read as u64;
                }
            }
            Content::Reader { .. } => {
                return Err(Error::InvalidInput(
                    "a reader input above 50 MiB needs its SHA-256: use FileInput::with_sha256, or pass a path".into(),
                ))
            }
        }
        Ok(crate::util::hex(&hasher.finalize()))
    }

    /// The bytes of one part (`None` when the part was already received and can be skipped).
    async fn part(&mut self, offset: u64, length: u64, skip: bool) -> Result<Option<Bytes>> {
        let length = usize::try_from(length)
            .map_err(|_| Error::InvalidInput("the part size does not fit in memory".into()))?;
        match self {
            Content::Bytes(bytes) => {
                if skip {
                    return Ok(None);
                }
                let start = usize::try_from(offset)
                    .map_err(|_| Error::InvalidInput("offset out of range".into()))?;
                Ok(Some(bytes.slice(start..start + length)))
            }
            Content::Path { path, file, .. } => {
                if skip {
                    return Ok(None);
                }
                if file.is_none() {
                    *file = Some(tokio::fs::File::open(&*path).await?);
                }
                let handle = file
                    .as_mut()
                    .ok_or_else(|| Error::InvalidInput("the file could not be opened".into()))?;
                handle.seek(SeekFrom::Start(offset)).await?;
                read_exact(handle, length).await.map(Some)
            }
            Content::File { file, start, .. } => {
                if skip {
                    return Ok(None);
                }
                file.seek(SeekFrom::Start(*start + offset)).await?;
                read_exact(file, length).await.map(Some)
            }
            Content::Reader {
                reader, position, ..
            } => {
                if *position != offset {
                    return Err(Error::InvalidInput(
                        "reader parts must be read in order".into(),
                    ));
                }
                let part = read_exact(reader, length).await?;
                *position += length as u64;
                Ok(if skip { None } else { Some(part) })
            }
        }
    }
}

async fn read_exact<R: AsyncRead + Unpin + ?Sized>(reader: &mut R, length: usize) -> Result<Bytes> {
    let mut buffer = BytesMut::zeroed(length);
    reader
        .read_exact(&mut buffer)
        .await
        .map_err(|error| match error.kind() {
            std::io::ErrorKind::UnexpectedEof => {
                Error::InvalidInput("the input ended before its declared size".into())
            }
            _ => Error::Io(error),
        })?;
    Ok(buffer.freeze())
}

/// A stream of at most `size` bytes read from `reader` in 64 KiB chunks.
fn read_stream<R>(
    reader: R,
    size: u64,
) -> impl futures_util::Stream<Item = std::io::Result<Bytes>> + Send + 'static
where
    R: AsyncRead + Send + Unpin + 'static,
{
    stream::try_unfold((reader, size), |(mut reader, remaining)| async move {
        if remaining == 0 {
            return Ok(None);
        }
        let want = READ_CHUNK.min(usize::try_from(remaining).unwrap_or(READ_CHUNK));
        let mut buffer = BytesMut::zeroed(want);
        let read = reader.read(&mut buffer).await?;
        if read == 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "the input ended before its declared size",
            ));
        }
        buffer.truncate(read);
        Ok(Some((buffer.freeze(), (reader, remaining - read as u64))))
    })
}

fn io_context(error: std::io::Error, path: &std::path::Path) -> Error {
    Error::Io(std::io::Error::new(
        error.kind(),
        format!("{}: {error}", path.display()),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn header_safe_keeps_ascii_and_encodes_the_rest() {
        assert_eq!(header_safe("report 2026.pdf"), "report 2026.pdf");
        assert_eq!(header_safe("résumé.pdf"), "r%C3%A9sum%C3%A9.pdf");
    }
}