rusty_cat/upload_trait.rs
1use bytes::Bytes;
2
3use crate::http_breakpoint::UploadResumeInfo;
4use crate::{MeowError, TransferTask};
5use async_trait::async_trait;
6
7/// Context for upload prepare stage.
8#[derive(Debug, Clone, Copy)]
9pub struct UploadPrepareCtx<'a> {
10 /// HTTP client used for requests.
11 pub client: &'a reqwest::Client,
12 /// Immutable task snapshot.
13 pub task: &'a TransferTask,
14 /// Locally confirmed uploaded offset in bytes.
15 ///
16 /// Range: `>= 0`.
17 pub local_offset: u64,
18}
19
20/// Context for upload chunk stage.
21///
22/// [`UploadChunkCtx::chunk`] is a [`bytes::Bytes`] handle. Cloning it is an
23/// O(1) refcount bump, and passing it into [`reqwest::Body`] never copies the
24/// underlying buffer. This lets protocol implementations send the same chunk
25/// multiple times (for example during retries) without re-allocating.
26#[derive(Debug, Clone)]
27pub struct UploadChunkCtx<'a> {
28 /// HTTP client used for requests.
29 pub client: &'a reqwest::Client,
30 /// Immutable task snapshot.
31 pub task: &'a TransferTask,
32 /// Raw bytes for the current chunk.
33 ///
34 /// `Bytes` is cheap to clone and can be converted into `reqwest::Body`
35 /// without copying. Avoid calling [`bytes::Bytes::to_vec`] on hot paths.
36 pub chunk: Bytes,
37 /// Start offset of this chunk in the full file.
38 ///
39 /// Range: `>= 0`.
40 pub offset: u64,
41}
42
43/// Custom breakpoint upload protocol.
44///
45/// Implementors are responsible for request construction and response parsing.
46/// The executor handles file I/O, chunking, retries, progress, and scheduling.
47///
48/// # Examples
49///
50/// ```no_run
51/// use async_trait::async_trait;
52/// use rusty_cat::api::{
53/// BreakpointUpload, MeowError, UploadChunkCtx, UploadPrepareCtx, UploadResumeInfo,
54/// };
55///
56/// struct MyUploadProtocol;
57///
58/// #[async_trait]
59/// impl BreakpointUpload for MyUploadProtocol {
60/// async fn prepare(&self, _ctx: UploadPrepareCtx<'_>) -> Result<UploadResumeInfo, MeowError> {
61/// Ok(UploadResumeInfo::default())
62/// }
63///
64/// async fn upload_chunk(&self, ctx: UploadChunkCtx<'_>) -> Result<UploadResumeInfo, MeowError> {
65/// let _ = (ctx.task.file_name(), ctx.offset);
66/// Ok(UploadResumeInfo {
67/// completed_file_id: None,
68/// next_byte: Some(ctx.offset + ctx.chunk.len() as u64),
69/// })
70/// }
71/// }
72/// ```
73///
74/// # Executor integration contract
75///
76/// - If [`UploadResumeInfo::completed_file_id`] is `Some`, the executor treats
77/// the upload as fully completed and stops sending further chunks.
78/// - [`UploadResumeInfo::next_byte`] is a server-suggested next offset; the
79/// executor merges it with local offset before continuing.
80/// - When computed next offset reaches `task.total_size()`, the executor calls
81/// [`BreakpointUpload::complete_upload`] unless completion was already
82/// indicated by `completed_file_id`.
83/// - When user cancels an upload task, executor calls
84/// [`BreakpointUpload::abort_upload`].
85#[async_trait]
86pub trait BreakpointUpload: Send + Sync {
87 /// Prepare stage before first chunk upload.
88 ///
89 /// Typical responsibilities include creating upload session and querying
90 /// already uploaded offset on remote side.
91 ///
92 /// # Parameters
93 ///
94 /// - `client`: Shared HTTP client used by executor.
95 /// - `task`: Upload task snapshot with URL/method/headers/file metadata.
96 /// - `local_offset`: Locally confirmed uploaded offset.
97 ///
98 /// # Returns
99 ///
100 /// - `Ok(info)`: Server resume info used by executor to compute next offset.
101 /// - `Err`: Prepare failed and task enters error path.
102 ///
103 /// # Errors
104 ///
105 /// Return [`MeowError`] when remote session creation/checkpoint probing
106 /// fails, request signing fails, or protocol payload parsing fails.
107 ///
108 /// # Examples
109 ///
110 /// ```no_run
111 /// use rusty_cat::api::UploadPrepareCtx;
112 ///
113 /// fn read_prepare_ctx(ctx: UploadPrepareCtx<'_>) {
114 /// let _ = (ctx.task.url(), ctx.local_offset);
115 /// }
116 /// ```
117 async fn prepare(&self, ctx: UploadPrepareCtx<'_>) -> Result<UploadResumeInfo, MeowError>;
118
119 /// Uploads a single chunk.
120 ///
121 /// Executor guarantees chunk bounds are valid and chunk bytes match the
122 /// provided `offset`.
123 ///
124 /// # Errors
125 ///
126 /// Return [`MeowError`] when chunk request fails, server rejects the chunk,
127 /// or protocol response parsing fails.
128 ///
129 /// # Examples
130 ///
131 /// ```no_run
132 /// use rusty_cat::api::UploadChunkCtx;
133 ///
134 /// fn read_chunk_ctx(ctx: &UploadChunkCtx<'_>) {
135 /// // `ctx.chunk` is a `bytes::Bytes`; cloning is a cheap refcount bump.
136 /// let _ = (ctx.offset, ctx.chunk.len(), ctx.task.total_size());
137 /// }
138 /// ```
139 async fn upload_chunk(&self, ctx: UploadChunkCtx<'_>) -> Result<UploadResumeInfo, MeowError>;
140
141 /// Finalization step after all chunk bytes are uploaded.
142 ///
143 /// Typical use case: multipart-complete API calls. Return value is an
144 /// optional provider-defined payload that will be forwarded to
145 /// `MeowClient::try_enqueue` complete callback.
146 ///
147 /// Default implementation is a no-op (`Ok(None)`).
148 ///
149 /// # Errors
150 ///
151 /// Implementations should return [`MeowError`] if final commit/merge API
152 /// fails.
153 async fn complete_upload(
154 &self,
155 _client: &reqwest::Client,
156 _task: &TransferTask,
157 ) -> Result<Option<String>, MeowError> {
158 Ok(None)
159 }
160
161 /// Abort/cleanup hook called when user cancels an upload task.
162 ///
163 /// Typical use case: abort multipart session or remove temporary objects.
164 /// Default implementation is a no-op.
165 ///
166 /// # Errors
167 ///
168 /// Implementations should return [`MeowError`] when cleanup or abort API
169 /// calls fail.
170 async fn abort_upload(
171 &self,
172 _client: &reqwest::Client,
173 _task: &TransferTask,
174 ) -> Result<(), MeowError> {
175 Ok(())
176 }
177}