Skip to main content

shaul_core/
backend.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use tokio_util::sync::CancellationToken;
7
8use crate::checksum::Checksum;
9use crate::config::ResolvedOptions;
10use crate::error::Result;
11use crate::event::EventSink;
12use crate::resource::Resource;
13use crate::task::{TaskId, TaskResume};
14
15/// Feature flags a backend advertises about the transfers it supports.
16///
17/// The values are descriptive: callers use them for policy decisions and
18/// diagnostics rather than to gate routing. `Default` means "none".
19#[derive(Clone, Debug, Default, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct BackendCapabilities {
22    /// Whether a file can be fetched as multiple byte ranges in parallel.
23    pub segmented: bool,
24    /// Whether an interrupted transfer can continue from a saved
25    /// [`TaskResume`] instead of starting over.
26    pub resume: bool,
27    /// Whether a single resource may produce several output files, such as a
28    /// repository snapshot.
29    pub multi_file: bool,
30}
31
32impl BackendCapabilities {
33    /// Creates a capability set from the individual flags.
34    pub fn new(segmented: bool, resume: bool, multi_file: bool) -> Self {
35        Self {
36            segmented,
37            resume,
38            multi_file,
39        }
40    }
41}
42
43/// Transfers the files described by a [`Resource`].
44///
45/// Backends are registered on a [`Router`](crate::router::Router) and selected
46/// with first-match semantics through [`supports`](DownloadBackend::supports).
47/// Implementations must honor [`DownloadRequest::cancel`], emit progress on
48/// [`DownloadRequest::events`], and persist resumable state through
49/// [`DownloadRequest::checkpoint`].
50#[async_trait]
51pub trait DownloadBackend: Send + Sync {
52    /// Short, stable identifier such as `http`; it is recorded on the task for
53    /// diagnostics.
54    fn name(&self) -> &'static str;
55    /// Describes the transfer features this backend provides.
56    fn capabilities(&self) -> BackendCapabilities;
57    /// Returns `true` when this backend can download `resource`. The check
58    /// must be cheap and free of side effects.
59    fn supports(&self, resource: &Resource) -> bool;
60    /// Performs the transfer. Returns `Completed` with one [`FileOutcome`] per
61    /// written file, or `Paused` when progress was checkpointed and the task
62    /// should stay paused.
63    async fn download(&self, request: DownloadRequest) -> Result<DownloadOutcome>;
64}
65
66/// Persistence hook used by backends to checkpoint partial progress without
67/// knowing how tasks are stored.
68#[async_trait]
69pub trait ResumeCheckpoint: Send + Sync {
70    /// Stores the latest resume manifest for the running task.
71    async fn save(&self, resume: &TaskResume) -> Result<()>;
72}
73
74/// Everything a backend needs for one download attempt.
75#[derive(Clone)]
76pub struct DownloadRequest {
77    /// Id of the task being executed.
78    pub task_id: TaskId,
79    /// Parsed resource to download.
80    pub resource: Resource,
81    /// Root directory that all output paths must stay under.
82    pub destination: PathBuf,
83    /// Fully resolved download, verification and extraction options.
84    pub options: ResolvedOptions,
85    /// Manifest from a previous attempt, when the task is resuming.
86    pub resume: Option<TaskResume>,
87    /// Cancellation signal; the backend must stop promptly once it fires.
88    pub cancel: CancellationToken,
89    /// Sink for progress, file and warning events.
90    pub events: EventSink,
91    /// Hook for persisting partial progress so a later attempt can resume.
92    pub checkpoint: Arc<dyn ResumeCheckpoint>,
93}
94
95/// One file written by a backend.
96#[derive(Clone, Debug)]
97#[non_exhaustive]
98pub struct FileOutcome {
99    /// Path of the file on disk, under the task destination.
100    pub path: PathBuf,
101    /// Relative to the task destination, using `/`.
102    pub relative_path: String,
103    /// Size of the written file in bytes.
104    pub size: u64,
105    /// Checksum the engine should verify this file against when the task has
106    /// no checksum of its own.
107    pub checksum: Option<Checksum>,
108    /// Set when the backend itself proved integrity, so the engine's verify
109    /// finalizer can skip re-hashing.
110    pub checksum_verified: bool,
111}
112
113impl FileOutcome {
114    /// Builds an outcome; use this rather than a struct literal because the
115    /// struct is `#[non_exhaustive]`.
116    pub fn new(
117        path: PathBuf,
118        relative_path: String,
119        size: u64,
120        checksum: Option<Checksum>,
121        checksum_verified: bool,
122    ) -> Self {
123        Self {
124            path,
125            relative_path,
126            size,
127            checksum,
128            checksum_verified,
129        }
130    }
131}
132
133/// Result of a single backend download attempt.
134#[derive(Clone, Debug)]
135pub enum DownloadOutcome {
136    /// All selected files were transferred.
137    Completed(Vec<FileOutcome>),
138    /// Progress has been checkpointed and the task should be left paused.
139    Paused,
140}