muna 0.0.14

Run prediction functions in your Rust apps.
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
/*
*   Muna
*   Copyright © 2026 NatML Inc. All Rights Reserved.
*/

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::pin::Pin;

use futures_core::Stream;
use reqwest::Method;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use tokio::io::AsyncWriteExt;

/// Muna error.
#[derive(Debug, thiserror::Error)]
pub enum MunaError {
    /// API error with HTTP status.
    #[error("{message}")]
    Api { message: String, status: u16 },
    /// HTTP transport error.
    #[error(transparent)]
    Http(#[from] reqwest::Error),
    /// Prediction error.
    #[error("{0}")]
    Prediction(String),
    /// JSON serialization error.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    /// Native library error.
    #[error("{0}")]
    Native(String),
}

impl MunaError {
    pub fn api_status(&self) -> Option<u16> {
        match self {
            Self::Api { status, .. } => Some(*status),
            _ => None,
        }
    }
}

pub type Result<T> = std::result::Result<T, MunaError>;

/// Server-sent event.
#[derive(Debug, Deserialize)]
pub struct SseEvent<T> {
    pub event: String,
    pub data: T,
}

#[derive(Debug, Deserialize)]
struct CreateResourceResponse {
    url: String,
}

#[derive(Debug, Deserialize)]
struct CreateResourceMultipartResponse {
    #[serde(rename = "uploadId")]
    upload_id: String,
    urls: Vec<String>,
}

/// HTTP request input.
pub struct RequestInput {
    pub path: String,
    pub method: Method,
    pub headers: Option<HashMap<String, String>>,
    pub body: Option<serde_json::Value>,
}

impl RequestInput {
    pub fn get(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            method: Method::GET,
            headers: None,
            body: None,
        }
    }

    pub fn post(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            method: Method::POST,
            headers: None,
            body: None,
        }
    }

    pub fn delete(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            method: Method::DELETE,
            headers: None,
            body: None,
        }
    }

    pub fn body(mut self, body: serde_json::Value) -> Self {
        self.body = Some(body);
        self
    }

    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers
            .get_or_insert_with(HashMap::new)
            .insert(key.into(), value.into());
        self
    }
}

/// Muna API client.
pub struct MunaClient {
    /// Muna API URL.
    pub url: String,
    auth: String,
    http: reqwest::Client,
}

impl MunaClient {
    const DEFAULT_URL: &'static str = "https://api.muna.ai/v1";
    const RESOURCE_URL_BASE: &'static str = "https://cdn.fxn.ai/resources";
    const DOWNLOAD_CHUNK_SIZE: u64 = 50 * 1024 * 1024; // 50 MB per range request
    const DOWNLOAD_MAX_FILES: usize = 16; // maximum parallel connections
    const MULTIPART_THRESHOLD: u64 = 100 * 1024 * 1024; // 100 MB
    const MULTIPART_CHUNK_SIZE: u64 = 50 * 1024 * 1024; // 50 MB per part
    const UPLOAD_MAX_PARALLEL: usize = 8; // maximum parallel part uploads
    const UPLOAD_MAX_RETRIES: u32 = 5;
    const RETRYABLE_STATUS_CODES: [u16; 7] = [400, 408, 429, 500, 502, 503, 504];

    /// Create a Muna API client.
    pub fn new(access_key: Option<&str>, url: Option<&str>) -> Self {
        let url = url.unwrap_or(Self::DEFAULT_URL).to_string();
        let auth = access_key
            .map(|key| format!("Bearer {key}"))
            .unwrap_or_default();
        let http = reqwest::Client::builder()
            .user_agent("muna-rs")
            .build()
            .expect("failed to build reqwest client");
        Self { url, auth, http }
    }

    /// Access the underlying HTTP client.
    pub(crate) fn http(&self) -> &reqwest::Client {
        &self.http
    }

    /// Make a request to a REST endpoint.
    pub async fn request<T: DeserializeOwned>(&self, input: RequestInput) -> Result<T> {
        let url = format!("{}{}", self.url, input.path);
        let mut builder = self
            .http
            .request(input.method, &url)
            .header("Authorization", &self.auth);
        if let Some(headers) = input.headers {
            for (k, v) in headers {
                builder = builder.header(k, v);
            }
        }
        if let Some(body) = input.body {
            builder = builder
                .header("Content-Type", "application/json")
                .body(serde_json::to_string(&body)?);
        }
        let response = builder.send().await?;
        let status = response.status();
        if !status.is_success() {
            let payload: serde_json::Value = response.json().await.unwrap_or_default();
            let message = payload["errors"][0]["message"]
                .as_str()
                .unwrap_or("An unknown error occurred")
                .to_string();
            return Err(MunaError::Api {
                message,
                status: status.as_u16(),
            });
        }
        let result = response.json().await?;
        Ok(result)
    }

    /// Make a request and consume the response as a server-sent events stream.
    pub async fn stream<T: DeserializeOwned + Send + 'static>(
        &self,
        input: RequestInput,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<SseEvent<T>>> + Send>>> {
        let url = format!("{}{}", self.url, input.path);
        let mut builder = self
            .http
            .request(input.method, &url)
            .header("Authorization", &self.auth);
        if let Some(headers) = input.headers {
            for (k, v) in headers {
                builder = builder.header(k, v);
            }
        }
        if let Some(body) = input.body {
            builder = builder
                .header("Content-Type", "application/json")
                .body(serde_json::to_string(&body)?);
        }
        let response = builder.send().await?;
        let status = response.status();
        if !status.is_success() {
            let payload: serde_json::Value = response.json().await.unwrap_or_default();
            let message = payload["errors"][0]["message"]
                .as_str()
                .unwrap_or("An unknown error occurred")
                .to_string();
            return Err(MunaError::Api {
                message,
                status: status.as_u16(),
            });
        }
        let stream = async_stream::try_stream! {
            let mut buffer = String::new();
            for await chunk in response.bytes_stream() {
                let chunk = chunk?;
                buffer.push_str(&String::from_utf8_lossy(&chunk));
                while let Some(boundary) = buffer.find("\n\n") {
                    let event_block = buffer[..boundary].to_string();
                    buffer = buffer[boundary + 2..].to_string();
                    let mut event_name = String::new();
                    let mut data = String::new();
                    for line in event_block.lines() {
                        if let Some(v) = line.strip_prefix("event:") {
                            event_name = v.trim().to_string();
                        } else if let Some(v) = line.strip_prefix("data:") {
                            data = v.trim().to_string();
                        }
                    }
                    if !data.is_empty() {
                        let parsed: T = serde_json::from_str(&data)?;
                        yield SseEvent { event: event_name, data: parsed };
                    }
                }
            }
        };
        Ok(Box::pin(stream))
    }

    /// Download a resource to a file.
    ///
    /// Range-capable resources are downloaded with parallel chunked range
    /// requests to saturate available bandwidth; resources whose server does
    /// not support range requests fall back to a single-connection stream.
    /// The download is atomic: data is written to a temporary file in the
    /// destination directory and renamed into place only on success.
    pub async fn download(&self, url: &str, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| MunaError::Prediction(format!("Failed to create directory: {e}")))?;
        }
        let tmp_path = download_temp_path(path);
        let result = match self.probe_download(url).await {
            Some(size) => self.download_ranges(url, &tmp_path, size).await,
            None => self.download_stream(url, &tmp_path).await,
        };
        match result {
            Ok(()) => tokio::fs::rename(&tmp_path, path).await.map_err(|e| {
                MunaError::Prediction(format!(
                    "Failed to move resource to {}: {e}",
                    path.display()
                ))
            }),
            Err(e) => {
                let _ = tokio::fs::remove_file(&tmp_path).await;
                Err(e)
            }
        }
    }

    /// Probe a resource URL for its size and HTTP range support.
    ///
    /// Uses a single-byte range request rather than a `HEAD` so that the
    /// probe works with method-scoped presigned URLs. Returns the total size
    /// only when the server responds with `206 Partial Content`.
    async fn probe_download(&self, url: &str) -> Option<u64> {
        let response = self
            .http
            .get(url)
            .header(reqwest::header::RANGE, "bytes=0-0")
            .send()
            .await
            .ok()?;
        if response.status() != reqwest::StatusCode::PARTIAL_CONTENT {
            return None;
        }
        let content_range = response
            .headers()
            .get(reqwest::header::CONTENT_RANGE)?
            .to_str()
            .ok()?;
        content_range.rsplit('/').next()?.parse::<u64>().ok()
    }

    /// Download a resource using concurrent range requests. A single range
    /// (small file) streams straight to the destination; otherwise each chunk
    /// goes to its own part file which are then assembled in order.
    async fn download_ranges(&self, url: &str, path: &Path, size: u64) -> Result<()> {
        use futures_util::stream::{StreamExt, TryStreamExt};
        // Build the byte ranges that cover the file.
        let mut ranges: Vec<(usize, u64, u64)> = Vec::new();
        let mut start = 0u64;
        let mut index = 0usize;
        while start < size {
            let end = (start + Self::DOWNLOAD_CHUNK_SIZE).min(size) - 1;
            ranges.push((index, start, end));
            start = end + 1;
            index += 1;
        }
        let part_count = ranges.len();
        // Small file: stream the single range straight to the destination,
        // avoiding the extra part-file assembly pass.
        if part_count <= 1 {
            return download_range(&self.http, url, 0, size.saturating_sub(1), path).await;
        }
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("resource");
        // Destination names are unique, so the file name alone is a safe,
        // collision-free prefix for the part files.
        let part_path = |i: usize| parent.join(format!(".{file_name}.part{i}"));
        // Download each range concurrently, capping the number of open connections.
        let download_result = futures_util::stream::iter(ranges)
            .map(|(i, start, end)| {
                let http = self.http.clone();
                let url = url.to_string();
                let part = part_path(i);
                async move { download_range(&http, &url, start, end, &part).await }
            })
            .buffer_unordered(Self::DOWNLOAD_MAX_FILES)
            .try_collect::<Vec<()>>()
            .await;
        // Assemble the part files into the destination on success; always clean up.
        let result = match download_result {
            Ok(_) => assemble_parts(path, &part_path, part_count).await,
            Err(e) => Err(e),
        };
        for i in 0..part_count {
            let _ = tokio::fs::remove_file(part_path(i)).await;
        }
        result
    }

    /// Upload a resource and return the resource URL.
    ///
    /// Resources already known to the API (matched by SHA-256) are not
    /// re-uploaded. Files at or above the multipart threshold are uploaded
    /// as multiple parts over parallel connections to saturate available
    /// bandwidth; smaller files go up in a single `PUT`.
    pub async fn upload(&self, path: &Path) -> Result<String> {
        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| MunaError::Native(format!("Failed to stat resource: {e}")))?;
        if !metadata.is_file() {
            return Err(MunaError::Native(format!(
                "Cannot upload resource at path {} because it is not a file",
                path.display()
            )));
        }
        let file_size = metadata.len();
        let resource_hash = sha256_file(path).await?;
        if self.resource_exists(&resource_hash).await? {
            return Ok(format!("{}/{resource_hash}", Self::RESOURCE_URL_BASE));
        }
        if file_size >= Self::MULTIPART_THRESHOLD {
            self.upload_resource_multipart(path, file_size, &resource_hash)
                .await?;
        } else {
            self.upload_resource_single(path, &resource_hash).await?;
        }
        Ok(format!("{}/{resource_hash}", Self::RESOURCE_URL_BASE))
    }

    /// Check whether a resource with the given hash already exists.
    async fn resource_exists(&self, resource_hash: &str) -> Result<bool> {
        let url = format!("{}/resources/{resource_hash}", self.url);
        let response = self
            .http
            .head(&url)
            .header("Authorization", &self.auth)
            .send()
            .await?;
        let status = response.status();
        if status.is_success() {
            return Ok(true);
        }
        if status == reqwest::StatusCode::NOT_FOUND {
            return Ok(false);
        }
        Err(MunaError::Api {
            message: format!("Failed to check resource: {status}"),
            status: status.as_u16(),
        })
    }

    /// Upload a resource using a single `PUT`.
    async fn upload_resource_single(&self, path: &Path, resource_hash: &str) -> Result<()> {
        let resource: CreateResourceResponse = self
            .request(RequestInput::post(format!("/resources/{resource_hash}")))
            .await?;
        let data = tokio::fs::read(path)
            .await
            .map_err(|e| MunaError::Native(format!("Failed to read resource: {e}")))?;
        upload_part(&self.http, &resource.url, data, Self::UPLOAD_MAX_RETRIES).await?;
        Ok(())
    }

    /// Upload a resource using multipart upload. Parts are uploaded over
    /// parallel connections; part order is preserved for the completion call.
    async fn upload_resource_multipart(
        &self,
        path: &Path,
        file_size: u64,
        resource_hash: &str,
    ) -> Result<()> {
        let num_parts = file_size.div_ceil(Self::MULTIPART_CHUNK_SIZE);
        let resource: CreateResourceMultipartResponse = self
            .request(
                RequestInput::post(format!("/resources/{resource_hash}/multipart"))
                    .body(serde_json::json!({ "parts": num_parts })),
            )
            .await?;
        match self.upload_parts(path, &resource.urls).await {
            Ok(etags) => {
                let parts: Vec<serde_json::Value> = etags
                    .iter()
                    .enumerate()
                    .map(|(i, etag)| serde_json::json!({ "partNumber": i + 1, "etag": etag }))
                    .collect();
                self.request_no_content(
                    RequestInput::post(format!(
                        "/resources/{resource_hash}/multipart/{}",
                        resource.upload_id
                    ))
                    .body(serde_json::json!({ "parts": parts })),
                )
                .await
            }
            Err(e) => {
                let _ = self
                    .request_no_content(RequestInput::delete(format!(
                        "/resources/{resource_hash}/multipart/{}",
                        resource.upload_id
                    )))
                    .await;
                Err(e)
            }
        }
    }

    /// Upload parts over parallel connections and return ETags in part order.
    /// Memory is bounded by one in-flight chunk per connection because each
    /// part is read from disk inside its own future.
    async fn upload_parts(&self, path: &Path, urls: &[String]) -> Result<Vec<String>> {
        use futures_util::stream::{StreamExt, TryStreamExt};
        futures_util::stream::iter(urls.iter().enumerate())
            .map(|(index, url)| {
                let http = self.http.clone();
                let url = url.clone();
                let path = path.to_path_buf();
                async move {
                    let chunk =
                        read_part(&path, index as u64 * Self::MULTIPART_CHUNK_SIZE).await?;
                    upload_part(&http, &url, chunk, Self::UPLOAD_MAX_RETRIES).await
                }
            })
            .buffered(Self::UPLOAD_MAX_PARALLEL)
            .try_collect::<Vec<String>>()
            .await
    }

    /// Make a request to a REST endpoint, discarding any response body.
    async fn request_no_content(&self, input: RequestInput) -> Result<()> {
        let url = format!("{}{}", self.url, input.path);
        let mut builder = self
            .http
            .request(input.method, &url)
            .header("Authorization", &self.auth);
        if let Some(body) = input.body {
            builder = builder
                .header("Content-Type", "application/json")
                .body(serde_json::to_string(&body)?);
        }
        let response = builder.send().await?;
        let status = response.status();
        if !status.is_success() {
            let payload: serde_json::Value = response.json().await.unwrap_or_default();
            let message = payload["errors"][0]["message"]
                .as_str()
                .unwrap_or("An unknown error occurred")
                .to_string();
            return Err(MunaError::Api {
                message,
                status: status.as_u16(),
            });
        }
        Ok(())
    }

    /// Download a resource to a file over a single connection.
    async fn download_stream(&self, url: &str, path: &Path) -> Result<()> {
        let mut response = self.http.get(url).send().await?;
        let status = response.status();
        if !status.is_success() {
            return Err(MunaError::Api {
                message: format!("Failed to download resource: {status}"),
                status: status.as_u16(),
            });
        }
        let mut file = tokio::fs::File::create(path)
            .await
            .map_err(|e| MunaError::Prediction(format!("Failed to create file: {e}")))?;
        while let Some(chunk) = response.chunk().await? {
            file.write_all(&chunk)
                .await
                .map_err(|e| MunaError::Prediction(format!("Failed to write chunk: {e}")))?;
        }
        file.flush()
            .await
            .map_err(|e| MunaError::Prediction(format!("Failed to flush file: {e}")))?;
        Ok(())
    }
}

/// Build a temporary download path in the destination's directory so the
/// final rename stays on the same filesystem (atomic, no cross-device move).
fn download_temp_path(path: &Path) -> PathBuf {
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("resource");
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    parent.join(format!(".{file_name}.{nonce}.part"))
}

/// Download a single byte range to a file.
async fn download_range(
    http: &reqwest::Client,
    url: &str,
    start: u64,
    end: u64,
    path: &Path,
) -> Result<()> {
    let mut response = http
        .get(url)
        .header(reqwest::header::RANGE, format!("bytes={start}-{end}"))
        .send()
        .await?;
    let status = response.status();
    if !status.is_success() {
        return Err(MunaError::Api {
            message: format!("Failed to download resource chunk: {status}"),
            status: status.as_u16(),
        });
    }
    let mut file = tokio::fs::File::create(path)
        .await
        .map_err(|e| MunaError::Prediction(format!("Failed to create file: {e}")))?;
    while let Some(chunk) = response.chunk().await? {
        file.write_all(&chunk)
            .await
            .map_err(|e| MunaError::Prediction(format!("Failed to write chunk: {e}")))?;
    }
    file.flush()
        .await
        .map_err(|e| MunaError::Prediction(format!("Failed to flush file: {e}")))?;
    Ok(())
}

/// Compute the SHA-256 hex digest of a file without loading it into memory.
async fn sha256_file(path: &Path) -> Result<String> {
    use sha2::{Digest, Sha256};
    use tokio::io::AsyncReadExt;
    let mut file = tokio::fs::File::open(path)
        .await
        .map_err(|e| MunaError::Native(format!("Failed to open resource: {e}")))?;
    let mut hasher = Sha256::new();
    let mut buffer = vec![0u8; 4 * 1024 * 1024];
    loop {
        let n = file
            .read(&mut buffer)
            .await
            .map_err(|e| MunaError::Native(format!("Failed to read resource: {e}")))?;
        if n == 0 {
            break;
        }
        hasher.update(&buffer[..n]);
    }
    Ok(format!("{:x}", hasher.finalize()))
}

/// Read one multipart chunk from a file at the given byte offset.
async fn read_part(path: &Path, offset: u64) -> Result<Vec<u8>> {
    use tokio::io::{AsyncReadExt, AsyncSeekExt};
    let mut file = tokio::fs::File::open(path)
        .await
        .map_err(|e| MunaError::Native(format!("Failed to open resource: {e}")))?;
    file.seek(std::io::SeekFrom::Start(offset))
        .await
        .map_err(|e| MunaError::Native(format!("Failed to seek resource: {e}")))?;
    let mut chunk = Vec::with_capacity(MunaClient::MULTIPART_CHUNK_SIZE as usize);
    file.take(MunaClient::MULTIPART_CHUNK_SIZE)
        .read_to_end(&mut chunk)
        .await
        .map_err(|e| MunaError::Native(format!("Failed to read resource: {e}")))?;
    Ok(chunk)
}

/// `PUT` a single part with exponential-backoff retries and return its ETag.
async fn upload_part(
    http: &reqwest::Client,
    url: &str,
    chunk: Vec<u8>,
    max_retries: u32,
) -> Result<String> {
    let mut attempt = 0u32;
    loop {
        let result = http.put(url).body(chunk.clone()).send().await;
        let error = match result {
            Ok(response) => {
                let status = response.status();
                if status.is_success() {
                    let etag = response
                        .headers()
                        .get(reqwest::header::ETAG)
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or_default()
                        .to_string();
                    return Ok(etag);
                }
                if !MunaClient::RETRYABLE_STATUS_CODES.contains(&status.as_u16()) {
                    return Err(MunaError::Api {
                        message: format!("Failed to upload resource part: {status}"),
                        status: status.as_u16(),
                    });
                }
                MunaError::Api {
                    message: format!("Failed to upload resource part: {status}"),
                    status: status.as_u16(),
                }
            }
            Err(e) => MunaError::Http(e),
        };
        if attempt >= max_retries - 1 {
            return Err(error);
        }
        tokio::time::sleep(std::time::Duration::from_secs(1 << attempt)).await;
        attempt += 1;
    }
}

/// Assemble downloaded part files into the destination in order.
async fn assemble_parts(
    path: &Path,
    part_path: &impl Fn(usize) -> PathBuf,
    part_count: usize,
) -> Result<()> {
    let mut file = tokio::fs::File::create(path)
        .await
        .map_err(|e| MunaError::Prediction(format!("Failed to create file: {e}")))?;
    for i in 0..part_count {
        let bytes = tokio::fs::read(part_path(i))
            .await
            .map_err(|e| MunaError::Prediction(format!("Failed to read part file: {e}")))?;
        file.write_all(&bytes)
            .await
            .map_err(|e| MunaError::Prediction(format!("Failed to write chunk: {e}")))?;
    }
    file.flush()
        .await
        .map_err(|e| MunaError::Prediction(format!("Failed to flush file: {e}")))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::sync::Arc;
    use std::thread;

    /// Start a minimal HTTP server that serves `data`, optionally honoring
    /// HTTP range requests, and return its base URL. When `support_ranges`
    /// is false the server ignores `Range` headers and always responds
    /// `200 OK`, which exercises the single-connection fallback path.
    fn start_server(data: Arc<Vec<u8>>, support_ranges: bool) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { continue };
                let data = data.clone();
                thread::spawn(move || {
                    let mut buf = Vec::new();
                    let mut tmp = [0u8; 1024];
                    loop {
                        match stream.read(&mut tmp) {
                            Ok(0) => break,
                            Ok(n) => {
                                buf.extend_from_slice(&tmp[..n]);
                                if buf.windows(4).any(|w| w == b"\r\n\r\n") {
                                    break;
                                }
                            }
                            Err(_) => return,
                        }
                    }
                    let request = String::from_utf8_lossy(&buf);
                    let range = request.lines().find_map(|line| {
                        line.strip_prefix("Range:")
                            .or_else(|| line.strip_prefix("range:"))
                            .map(|value| value.trim().to_string())
                    });
                    let total = data.len();
                    let (status, body, content_range) = match (support_ranges, range) {
                        (true, Some(range)) => {
                            let spec = range.trim_start_matches("bytes=");
                            let mut parts = spec.split('-');
                            let start: usize = parts.next().unwrap_or("0").parse().unwrap_or(0);
                            let end: usize = parts
                                .next()
                                .and_then(|end| end.parse().ok())
                                .unwrap_or(total - 1)
                                .min(total - 1);
                            (
                                "206 Partial Content",
                                data[start..=end].to_vec(),
                                Some(format!("bytes {start}-{end}/{total}")),
                            )
                        }
                        _ => ("200 OK", data.as_ref().clone(), None),
                    };
                    let mut header = format!(
                        "HTTP/1.1 {status}\r\nContent-Length: {}\r\nAccept-Ranges: bytes\r\nConnection: close\r\n",
                        body.len()
                    );
                    if let Some(content_range) = content_range {
                        header.push_str(&format!("Content-Range: {content_range}\r\n"));
                    }
                    header.push_str("\r\n");
                    let _ = stream.write_all(header.as_bytes());
                    let _ = stream.write_all(&body);
                    let _ = stream.flush();
                });
            }
        });
        format!("http://{addr}")
    }

    fn test_payload(size: usize) -> Arc<Vec<u8>> {
        Arc::new((0..size).map(|i| (i % 251) as u8).collect())
    }

    async fn download_to_temp(base: &str, data: &Arc<Vec<u8>>) -> Vec<u8> {
        let client = MunaClient::new(None, None);
        let dir = std::env::temp_dir().join(format!(
            "muna-dl-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("resource.bin");
        client
            .download(&format!("{base}/resource"), &path)
            .await
            .unwrap();
        let downloaded = std::fs::read(&path).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(downloaded.len(), data.len());
        downloaded
    }

    #[tokio::test]
    async fn test_download_to_file_parallel() {
        // 64 MiB exceeds the 50 MiB chunk size, exercising the parallel
        // multi-range path.
        let data = test_payload(64 * 1024 * 1024);
        let base = start_server(data.clone(), true);
        assert!(download_to_temp(&base, &data).await == *data);
    }

    #[tokio::test]
    async fn test_download_to_file_single_part() {
        // A small range-capable file takes the single-part fast path.
        let data = test_payload(1024 * 1024);
        let base = start_server(data.clone(), true);
        assert!(download_to_temp(&base, &data).await == *data);
    }

    #[tokio::test]
    async fn test_download_to_file_fallback() {
        // A server that ignores Range headers downloads via the
        // single-connection fallback.
        let data = test_payload(2 * 1024 * 1024);
        let base = start_server(data.clone(), false);
        assert!(download_to_temp(&base, &data).await == *data);
    }

    #[tokio::test]
    async fn test_http_accessor_fetches_bytes() {
        // The in-memory path (used by remote.rs) fetches via the shared HTTP
        // client exposed by `http()`.
        let data = test_payload(512 * 1024);
        let base = start_server(data.clone(), true);
        let client = MunaClient::new(None, None);
        let response = client
            .http()
            .get(format!("{base}/resource"))
            .send()
            .await
            .unwrap();
        let bytes = response.bytes().await.unwrap().to_vec();
        assert!(bytes == *data);
    }
}