morpheus_network/state/
download.rs

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
//! ISO download orchestration state machine.
//!
//! Composes DHCP → HTTP state machines for complete ISO download workflow.
//!
//! # Architecture
//!
//! ```text
//! Init → WaitingForNetwork → Downloading → WritingToDisk → Done
//!   ↓           ↓                 ↓              ↓            
//! Failed     Failed           Failed         Failed
//! ```
//!
//! # Streaming Support
//!
//! For large ISO downloads (often 1-4GB), data is streamed directly to disk
//! rather than buffered in memory. The state machine coordinates:
//!
//! 1. DHCP: Obtain network configuration
//! 2. HTTP: Download ISO with streaming callbacks
//! 3. Disk: Write chunks to VirtIO-blk as they arrive
//!
//! # Reference
//! NETWORK_IMPL_GUIDE.md §5.6

use alloc::string::{String, ToString};
use core::net::Ipv4Addr;

use super::dhcp::{DhcpConfig, DhcpError, DhcpState};
use super::http::{HttpDownloadState, HttpError, HttpProgress, HttpResponseInfo};
use super::tcp::TcpSocketState;
use super::{Progress, StateError, StepResult, TscTimestamp};
use crate::url::Url;

// ═══════════════════════════════════════════════════════════════════════════
// DOWNLOAD ERROR
// ═══════════════════════════════════════════════════════════════════════════

/// Errors during ISO download.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DownloadError {
    /// DHCP failed to obtain address
    NetworkError(DhcpError),
    /// HTTP download failed
    HttpError(HttpError),
    /// Invalid URL
    InvalidUrl,
    /// Checksum verification failed
    ChecksumMismatch,
    /// Disk write failed
    DiskWriteError,
    /// Not enough disk space
    InsufficientSpace,
    /// ISO too large for available memory
    IsoTooLarge,
    /// Download cancelled
    Cancelled,
}

impl From<DhcpError> for DownloadError {
    fn from(e: DhcpError) -> Self {
        DownloadError::NetworkError(e)
    }
}

impl From<HttpError> for DownloadError {
    fn from(e: HttpError) -> Self {
        DownloadError::HttpError(e)
    }
}

impl From<DownloadError> for StateError {
    fn from(e: DownloadError) -> Self {
        match e {
            DownloadError::NetworkError(_) => StateError::InterfaceError,
            DownloadError::HttpError(ref he) => StateError::from(he.clone()),
            DownloadError::InvalidUrl => StateError::InvalidResponse,
            DownloadError::ChecksumMismatch => StateError::InvalidResponse,
            DownloadError::DiskWriteError => StateError::Internal,
            DownloadError::InsufficientSpace => StateError::Internal,
            DownloadError::IsoTooLarge => StateError::BufferTooSmall,
            DownloadError::Cancelled => StateError::Internal,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DOWNLOAD CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════

/// Configuration for ISO download.
#[derive(Debug, Clone)]
pub struct DownloadConfig {
    /// URL of ISO to download
    pub url: Url,
    /// Expected SHA-256 hash (optional, for verification)
    pub expected_hash: Option<[u8; 32]>,
    /// Maximum file size (bytes)
    pub max_size: Option<usize>,
    /// Target disk sector offset for writing
    pub disk_start_sector: u64,
    /// Sector size (usually 512)
    pub sector_size: usize,
}

impl DownloadConfig {
    /// Create new download config.
    pub fn new(url: Url) -> Self {
        Self {
            url,
            expected_hash: None,
            max_size: None,
            disk_start_sector: 0,
            sector_size: 512,
        }
    }

    /// Set expected SHA-256 hash for verification.
    pub fn with_hash(mut self, hash: [u8; 32]) -> Self {
        self.expected_hash = Some(hash);
        self
    }

    /// Set maximum allowed file size.
    pub fn with_max_size(mut self, max_size: usize) -> Self {
        self.max_size = Some(max_size);
        self
    }

    /// Set target disk location.
    pub fn with_disk_location(mut self, start_sector: u64, sector_size: usize) -> Self {
        self.disk_start_sector = start_sector;
        self.sector_size = sector_size;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DOWNLOAD PROGRESS
// ═══════════════════════════════════════════════════════════════════════════

/// Overall download progress.
#[derive(Debug, Clone, Copy)]
pub struct DownloadProgress {
    /// Current phase
    pub phase: DownloadPhase,
    /// Bytes downloaded
    pub bytes_downloaded: usize,
    /// Total expected bytes (if known)
    pub total_bytes: Option<usize>,
    /// Bytes written to disk
    pub bytes_written: usize,
}

/// Download phase for progress tracking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DownloadPhase {
    /// Waiting for network
    WaitingForNetwork,
    /// Connecting to server
    Connecting,
    /// Downloading data
    Downloading,
    /// Writing to disk
    WritingToDisk,
    /// Verifying checksum
    Verifying,
    /// Complete
    Complete,
}

impl DownloadProgress {
    /// Calculate overall percentage (0-100).
    pub fn percent(&self) -> Option<u8> {
        match self.phase {
            DownloadPhase::WaitingForNetwork => Some(0),
            DownloadPhase::Connecting => Some(5),
            DownloadPhase::Downloading | DownloadPhase::WritingToDisk => {
                self.total_bytes.map(|total| {
                    if total == 0 {
                        100
                    } else {
                        let pct = (self.bytes_downloaded as u64 * 90) / total as u64;
                        (5 + pct).min(95) as u8
                    }
                })
            }
            DownloadPhase::Verifying => Some(95),
            DownloadPhase::Complete => Some(100),
        }
    }
}

impl From<DownloadProgress> for Progress {
    fn from(p: DownloadProgress) -> Self {
        Progress {
            bytes_done: p.bytes_downloaded as u64,
            bytes_total: p.total_bytes.unwrap_or(0) as u64,
            start_tsc: 0,
            last_update_tsc: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DOWNLOAD RESULT
// ═══════════════════════════════════════════════════════════════════════════

/// Result of successful download.
#[derive(Debug, Clone)]
pub struct DownloadResult {
    /// Total bytes downloaded
    pub total_bytes: usize,
    /// HTTP response info
    pub response_info: HttpResponseInfo,
    /// Starting sector on disk
    pub disk_start_sector: u64,
    /// Number of sectors written
    pub sectors_written: u64,
}

// ═══════════════════════════════════════════════════════════════════════════
// ISO DOWNLOAD STATE MACHINE
// ═══════════════════════════════════════════════════════════════════════════

/// ISO download orchestration state machine.
///
/// Coordinates DHCP → HTTP → Disk Write workflow.
#[derive(Debug)]
pub enum IsoDownloadState {
    /// Initial state with configuration.
    Init { config: DownloadConfig },

    /// Waiting for DHCP to obtain network configuration.
    WaitingForNetwork {
        /// DHCP state machine
        dhcp: DhcpState,
        /// Download configuration
        config: DownloadConfig,
    },

    /// Network ready, downloading ISO.
    Downloading {
        /// HTTP download state machine
        http: HttpDownloadState,
        /// Network configuration from DHCP
        network_config: DhcpConfig,
        /// Download configuration
        config: DownloadConfig,
        /// Current disk write position (sectors)
        disk_position: u64,
        /// Bytes pending disk write
        pending_write: usize,
        /// Total bytes written to disk
        bytes_written: usize,
    },

    /// Download complete, verifying checksum (if hash provided).
    Verifying {
        /// Download result so far
        result: DownloadResult,
        /// Expected hash
        expected_hash: [u8; 32],
        /// Verification progress (bytes checked)
        verified_bytes: usize,
        /// When verification started
        start_tsc: TscTimestamp,
    },

    /// Download and verification complete.
    Done { result: DownloadResult },

    /// Download failed.
    Failed { error: DownloadError },
}

impl IsoDownloadState {
    /// Create new download state machine.
    pub fn new(config: DownloadConfig) -> Self {
        IsoDownloadState::Init { config }
    }

    /// Start the download.
    ///
    /// If already have network config, skip DHCP.
    /// Otherwise, start DHCP first.
    pub fn start(&mut self, existing_network: Option<DhcpConfig>, now_tsc: u64) {
        if let IsoDownloadState::Init { config } = self {
            let config = core::mem::replace(
                config,
                DownloadConfig::new(Url {
                    scheme: crate::url::parser::Scheme::Http,
                    host: String::new(),
                    port: None,
                    path: String::new(),
                    query: None,
                }),
            );

            if let Some(network_config) = existing_network {
                // Already have network, start HTTP download
                match HttpDownloadState::new(config.url.clone()) {
                    Ok(mut http) => {
                        http.start(now_tsc);
                        *self = IsoDownloadState::Downloading {
                            http,
                            network_config,
                            config,
                            disk_position: 0,
                            pending_write: 0,
                            bytes_written: 0,
                        };
                    }
                    Err(e) => {
                        *self = IsoDownloadState::Failed {
                            error: DownloadError::HttpError(e),
                        };
                    }
                }
            } else {
                // Need DHCP first
                let mut dhcp = DhcpState::new();
                dhcp.start(now_tsc);
                *self = IsoDownloadState::WaitingForNetwork { dhcp, config };
            }
        }
    }

    /// Step the state machine.
    ///
    /// # Arguments
    /// - `dhcp_event`: DHCP event from smoltcp (if any)
    /// - `dns_result`: DNS query result (if resolving)
    /// - `tcp_state`: TCP socket state (if connected)
    /// - `recv_data`: Data received from HTTP socket
    /// - `can_send`: Whether socket can send
    /// - `disk_write_result`: Result of disk write (Ok(written) or Err)
    /// - `now_tsc`: Current TSC value
    /// - `timeouts`: Timeout values
    ///
    /// # Returns
    /// StepResult indicating current status
    pub fn step(
        &mut self,
        dhcp_event: Option<Result<DhcpConfig, ()>>,
        dns_result: Result<Option<Ipv4Addr>, ()>,
        tcp_state: TcpSocketState,
        recv_data: Option<&[u8]>,
        can_send: bool,
        disk_write_result: Option<Result<usize, ()>>,
        now_tsc: u64,
        dhcp_timeout: u64,
        dns_timeout: u64,
        tcp_timeout: u64,
        http_send_timeout: u64,
        http_recv_timeout: u64,
    ) -> StepResult {
        // Take ownership for state transitions
        let current = core::mem::replace(
            self,
            IsoDownloadState::Init {
                config: DownloadConfig::new(Url {
                    scheme: crate::url::parser::Scheme::Http,
                    host: String::new(),
                    port: None,
                    path: String::new(),
                    query: None,
                }),
            },
        );

        let (new_state, result) = self.step_inner(
            current,
            dhcp_event,
            dns_result,
            tcp_state,
            recv_data,
            can_send,
            disk_write_result,
            now_tsc,
            dhcp_timeout,
            dns_timeout,
            tcp_timeout,
            http_send_timeout,
            http_recv_timeout,
        );

        *self = new_state;
        result
    }

    /// Internal step implementation.
    #[allow(clippy::too_many_arguments)]
    fn step_inner(
        &self,
        current: IsoDownloadState,
        dhcp_event: Option<Result<DhcpConfig, ()>>,
        dns_result: Result<Option<Ipv4Addr>, ()>,
        tcp_state: TcpSocketState,
        recv_data: Option<&[u8]>,
        can_send: bool,
        disk_write_result: Option<Result<usize, ()>>,
        now_tsc: u64,
        dhcp_timeout: u64,
        dns_timeout: u64,
        tcp_timeout: u64,
        http_send_timeout: u64,
        http_recv_timeout: u64,
    ) -> (IsoDownloadState, StepResult) {
        match current {
            IsoDownloadState::Init { config } => {
                // Not started yet
                (IsoDownloadState::Init { config }, StepResult::Pending)
            }

            IsoDownloadState::WaitingForNetwork { mut dhcp, config } => {
                // Step DHCP state machine
                // Convert Option<Result<DhcpConfig, ()>> to Option<DhcpConfig>
                let dhcp_config = dhcp_event.and_then(|r| r.ok());
                let result = dhcp.step(dhcp_config, now_tsc, dhcp_timeout);

                match result {
                    StepResult::Done => {
                        // Network ready, start HTTP download
                        let network_config = dhcp.config().unwrap().clone();

                        match HttpDownloadState::new(config.url.clone()) {
                            Ok(mut http) => {
                                http.start(now_tsc);
                                (
                                    IsoDownloadState::Downloading {
                                        http,
                                        network_config,
                                        config,
                                        disk_position: 0,
                                        pending_write: 0,
                                        bytes_written: 0,
                                    },
                                    StepResult::Pending,
                                )
                            }
                            Err(e) => (
                                IsoDownloadState::Failed {
                                    error: DownloadError::HttpError(e),
                                },
                                StepResult::Failed,
                            ),
                        }
                    }
                    StepResult::Pending => (
                        IsoDownloadState::WaitingForNetwork { dhcp, config },
                        StepResult::Pending,
                    ),
                    StepResult::Timeout => (
                        IsoDownloadState::Failed {
                            error: DownloadError::NetworkError(DhcpError::Timeout),
                        },
                        StepResult::Timeout,
                    ),
                    StepResult::Failed => {
                        let error = dhcp.error().unwrap_or(DhcpError::Timeout);
                        (
                            IsoDownloadState::Failed {
                                error: DownloadError::NetworkError(error),
                            },
                            StepResult::Failed,
                        )
                    }
                }
            }

            IsoDownloadState::Downloading {
                mut http,
                network_config,
                config,
                mut disk_position,
                mut pending_write,
                mut bytes_written,
            } => {
                // Process disk write result first
                if let Some(write_result) = disk_write_result {
                    match write_result {
                        Ok(written) => {
                            bytes_written += written;
                            pending_write = pending_write.saturating_sub(written);
                            disk_position += (written / config.sector_size) as u64;
                        }
                        Err(()) => {
                            return (
                                IsoDownloadState::Failed {
                                    error: DownloadError::DiskWriteError,
                                },
                                StepResult::Failed,
                            );
                        }
                    }
                }

                // Check max size before proceeding
                if let (Some(max_size), Some(content_length)) = (
                    config.max_size,
                    http.response_info().and_then(|r| r.content_length),
                ) {
                    if content_length > max_size {
                        return (
                            IsoDownloadState::Failed {
                                error: DownloadError::IsoTooLarge,
                            },
                            StepResult::Failed,
                        );
                    }
                }

                // Step HTTP state machine
                let result = http.step(
                    dns_result,
                    tcp_state,
                    recv_data,
                    can_send,
                    now_tsc,
                    dns_timeout,
                    tcp_timeout,
                    http_send_timeout,
                    http_recv_timeout,
                );

                // Track pending writes from received data
                if let Some(data) = recv_data {
                    if http.response_info().is_some() {
                        // We're in body reception phase
                        pending_write += data.len();
                    }
                }

                match result {
                    StepResult::Done => {
                        // HTTP complete
                        let (response_info, total_bytes) = http.result().unwrap();
                        let sectors_written = (bytes_written / config.sector_size) as u64;

                        let download_result = DownloadResult {
                            total_bytes,
                            response_info: response_info.clone(),
                            disk_start_sector: config.disk_start_sector,
                            sectors_written,
                        };

                        // Check if we need verification
                        if let Some(expected_hash) = config.expected_hash {
                            (
                                IsoDownloadState::Verifying {
                                    result: download_result,
                                    expected_hash,
                                    verified_bytes: 0,
                                    start_tsc: TscTimestamp::new(now_tsc),
                                },
                                StepResult::Pending,
                            )
                        } else {
                            (
                                IsoDownloadState::Done {
                                    result: download_result,
                                },
                                StepResult::Done,
                            )
                        }
                    }
                    StepResult::Pending => (
                        IsoDownloadState::Downloading {
                            http,
                            network_config,
                            config,
                            disk_position,
                            pending_write,
                            bytes_written,
                        },
                        StepResult::Pending,
                    ),
                    StepResult::Timeout => {
                        let error = http.error().cloned().unwrap_or(HttpError::ReceiveTimeout);
                        (
                            IsoDownloadState::Failed {
                                error: DownloadError::HttpError(error),
                            },
                            StepResult::Timeout,
                        )
                    }
                    StepResult::Failed => {
                        let error = http.error().cloned().unwrap_or(HttpError::ConnectionClosed);
                        (
                            IsoDownloadState::Failed {
                                error: DownloadError::HttpError(error),
                            },
                            StepResult::Failed,
                        )
                    }
                }
            }

            IsoDownloadState::Verifying {
                result,
                expected_hash: _,
                verified_bytes: _,
                start_tsc: _,
            } => {
                // TODO: Implement actual hash verification
                // For now, skip verification (always pass)
                // In real implementation, would read sectors back and compute SHA-256

                // Just mark as done for now
                (IsoDownloadState::Done { result }, StepResult::Done)
            }

            IsoDownloadState::Done { result } => {
                (IsoDownloadState::Done { result }, StepResult::Done)
            }

            IsoDownloadState::Failed { error } => {
                let result = match &error {
                    DownloadError::NetworkError(DhcpError::Timeout)
                    | DownloadError::HttpError(HttpError::SendTimeout)
                    | DownloadError::HttpError(HttpError::ReceiveTimeout) => StepResult::Timeout,
                    _ => StepResult::Failed,
                };
                (IsoDownloadState::Failed { error }, result)
            }
        }
    }

    /// Get current progress.
    pub fn progress(&self) -> DownloadProgress {
        match self {
            IsoDownloadState::Init { .. } => DownloadProgress {
                phase: DownloadPhase::WaitingForNetwork,
                bytes_downloaded: 0,
                total_bytes: None,
                bytes_written: 0,
            },
            IsoDownloadState::WaitingForNetwork { .. } => DownloadProgress {
                phase: DownloadPhase::WaitingForNetwork,
                bytes_downloaded: 0,
                total_bytes: None,
                bytes_written: 0,
            },
            IsoDownloadState::Downloading {
                http,
                bytes_written,
                ..
            } => {
                let http_progress = http.progress();
                DownloadProgress {
                    phase: if http_progress.is_some() {
                        DownloadPhase::Downloading
                    } else {
                        DownloadPhase::Connecting
                    },
                    bytes_downloaded: http_progress.map(|p| p.received).unwrap_or(0),
                    total_bytes: http_progress.and_then(|p| p.total),
                    bytes_written: *bytes_written,
                }
            }
            IsoDownloadState::Verifying { result, .. } => DownloadProgress {
                phase: DownloadPhase::Verifying,
                bytes_downloaded: result.total_bytes,
                total_bytes: Some(result.total_bytes),
                bytes_written: result.total_bytes,
            },
            IsoDownloadState::Done { result } => DownloadProgress {
                phase: DownloadPhase::Complete,
                bytes_downloaded: result.total_bytes,
                total_bytes: Some(result.total_bytes),
                bytes_written: result.total_bytes,
            },
            IsoDownloadState::Failed { .. } => DownloadProgress {
                phase: DownloadPhase::Downloading, // Keep last known phase
                bytes_downloaded: 0,
                total_bytes: None,
                bytes_written: 0,
            },
        }
    }

    /// Get download result (if complete).
    pub fn result(&self) -> Option<&DownloadResult> {
        if let IsoDownloadState::Done { result } = self {
            Some(result)
        } else {
            None
        }
    }

    /// Get error (if failed).
    pub fn error(&self) -> Option<&DownloadError> {
        if let IsoDownloadState::Failed { error } = self {
            Some(error)
        } else {
            None
        }
    }

    /// Get network config (if obtained).
    pub fn network_config(&self) -> Option<&DhcpConfig> {
        match self {
            IsoDownloadState::Downloading { network_config, .. } => Some(network_config),
            _ => None,
        }
    }

    /// Get HTTP socket handle (if downloading).
    pub fn socket_handle(&self) -> Option<usize> {
        if let IsoDownloadState::Downloading { http, .. } = self {
            http.socket_handle()
        } else {
            None
        }
    }

    /// Get bytes to send (if in send phase).
    pub fn pending_send(&self) -> Option<(&[u8], usize)> {
        if let IsoDownloadState::Downloading { http, .. } = self {
            http.request_bytes()
        } else {
            None
        }
    }

    /// Mark bytes as sent.
    pub fn mark_sent(&mut self, bytes: usize) {
        if let IsoDownloadState::Downloading { http, .. } = self {
            http.mark_sent(bytes);
        }
    }

    /// Get data pending disk write.
    ///
    /// Returns (current_sector, bytes_pending)
    pub fn pending_disk_write(&self) -> Option<(u64, usize)> {
        if let IsoDownloadState::Downloading {
            config,
            disk_position,
            pending_write,
            ..
        } = self
        {
            if *pending_write > 0 {
                Some((config.disk_start_sector + disk_position, *pending_write))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Check if download is complete (success or failure).
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            IsoDownloadState::Done { .. } | IsoDownloadState::Failed { .. }
        )
    }

    /// Check if download is in progress.
    pub fn is_active(&self) -> bool {
        !matches!(
            self,
            IsoDownloadState::Init { .. }
                | IsoDownloadState::Done { .. }
                | IsoDownloadState::Failed { .. }
        )
    }

    /// Cancel the download.
    pub fn cancel(&mut self) {
        *self = IsoDownloadState::Failed {
            error: DownloadError::Cancelled,
        };
    }
}

impl Default for IsoDownloadState {
    fn default() -> Self {
        IsoDownloadState::Init {
            config: DownloadConfig::new(Url {
                scheme: crate::url::parser::Scheme::Http,
                host: String::new(),
                port: None,
                path: String::new(),
                query: None,
            }),
        }
    }
}