1use std::path::{Path, PathBuf};
19
20use clap::{Parser, Subcommand, ValueEnum};
21use serde_json::json;
22use uuid::Uuid;
23
24use super::{CmdError, CmdResult, Ctx};
25use crate::envelope::Envelope;
26use crate::Environment;
27
28use taskfast_client::api::types::{
29 Artifact, SubmitArtifactCidBody, UpdateArtifactCidStatusBody,
30 UpdateArtifactCidStatusBodyCidStatus,
31};
32use taskfast_client::{map_api_error, put_presigned_upload, ArtifactUpload, TaskFastClient};
33
34#[derive(Debug, Subcommand)]
35pub enum Command {
36 List(ListArgs),
38 Get(GetArgs),
40 Upload(UploadArgs),
42 Delete(GetArgs),
44 Cid(CidArgs),
46 CidStatus(CidStatusArgs),
48}
49
50#[derive(Debug, Parser)]
51pub struct ListArgs {
52 pub task_id: String,
53
54 #[arg(long)]
55 pub cursor: Option<String>,
56
57 #[arg(long)]
58 pub limit: Option<i64>,
59}
60
61#[derive(Debug, Parser)]
62pub struct GetArgs {
63 pub task_id: String,
64
65 pub artifact_id: String,
66}
67
68#[derive(Debug, Parser)]
69pub struct UploadArgs {
70 pub task_id: String,
71
72 pub file: PathBuf,
74}
75
76#[derive(Debug, Parser)]
77pub struct CidArgs {
78 pub task_id: String,
79
80 pub output_cid: String,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
89pub enum CidStatusArg {
90 Witnessed,
92 Unverifiable,
94}
95
96impl From<CidStatusArg> for UpdateArtifactCidStatusBodyCidStatus {
97 fn from(v: CidStatusArg) -> Self {
98 match v {
99 CidStatusArg::Witnessed => Self::Witnessed,
100 CidStatusArg::Unverifiable => Self::Unverifiable,
101 }
102 }
103}
104
105#[derive(Debug, Parser)]
106pub struct CidStatusArgs {
107 pub task_id: String,
108
109 pub artifact_id: String,
110
111 pub status: CidStatusArg,
113}
114
115pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
116 match cmd {
117 Command::List(a) => list(ctx, a).await,
118 Command::Get(a) => get(ctx, a).await,
119 Command::Upload(a) => upload(ctx, a).await,
120 Command::Delete(a) => delete(ctx, a).await,
121 Command::Cid(a) => submit_cid(ctx, a).await,
122 Command::CidStatus(a) => update_cid_status(ctx, a).await,
123 }
124}
125
126async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
127 let task_id = parse_uuid(&args.task_id, "task id")?;
128 let client = ctx.client()?;
129 let resp = match client
130 .inner()
131 .list_artifacts(
132 &task_id,
133 args.cursor.as_deref(),
134 args.limit.and_then(taskfast_client::page_limit),
135 )
136 .await
137 {
138 Ok(v) => v.into_inner(),
139 Err(e) => return Err(map_api_error(e).await.into()),
140 };
141 Ok(Envelope::success(
142 ctx.environment,
143 ctx.dry_run,
144 json!({
145 "task_id": task_id.to_string(),
146 "artifacts": resp.data,
147 "meta": resp.meta,
148 }),
149 ))
150}
151
152async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
153 let task_id = parse_uuid(&args.task_id, "task id")?;
154 let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
155 let client = ctx.client()?;
156 let resp = match client.inner().get_artifact(&task_id, &artifact_id).await {
157 Ok(v) => v.into_inner(),
158 Err(e) => return Err(map_api_error(e).await.into()),
159 };
160 Ok(Envelope::success(
161 ctx.environment,
162 ctx.dry_run,
163 json!({ "artifact": resp }),
164 ))
165}
166
167async fn upload(ctx: &Ctx, args: UploadArgs) -> CmdResult {
168 let task_id = parse_uuid(&args.task_id, "task id")?;
169 let file = ResolvedArtifact::from_path(&args.file)?;
170
171 if ctx.dry_run {
172 return Ok(Envelope::success(
173 ctx.environment,
174 ctx.dry_run,
175 json!({
176 "action": "would_upload_artifact",
177 "task_id": task_id.to_string(),
178 "filename": file.filename,
179 "content_type": file.content_type,
180 "path": file.display_path(),
181 }),
182 ));
183 }
184
185 let client = ctx.client()?;
186 let artifact = upload_file(ctx, &client, &task_id, &file).await?;
187 Ok(Envelope::success(
188 ctx.environment,
189 ctx.dry_run,
190 json!({
191 "task_id": task_id.to_string(),
192 "artifact": {
193 "id": artifact.id,
194 "filename": artifact.filename,
195 "content_type": artifact.content_type,
196 "size_bytes": artifact.size_bytes,
197 },
198 }),
199 ))
200}
201
202pub(super) async fn upload_file(
210 ctx: &Ctx,
211 client: &TaskFastClient,
212 task_id: &Uuid,
213 artifact: &ResolvedArtifact,
214) -> Result<Artifact, CmdError> {
215 let ResolvedArtifact {
216 path,
217 filename,
218 content_type,
219 } = artifact;
220 let read_err = |e: std::io::Error| CmdError::Usage(format!("read {}: {e}", path.display()));
221 let file = std::fs::File::open(path).map_err(read_err)?;
222 let size_bytes = file.metadata().map_err(read_err)?.len();
223 match client
224 .initiate_artifact_upload(task_id, filename, content_type, size_bytes)
225 .await?
226 {
227 Some(ArtifactUpload::Put {
228 upload_id,
229 url,
230 headers,
231 expires_at,
232 }) => {
233 check_upload_url(&url, ctx.allow_custom_endpoints)?;
234 put_presigned_upload(&url, &headers, file, size_bytes).await?;
235 Ok(client
236 .complete_artifact_upload(task_id, &upload_id, expires_at)
237 .await?)
238 }
239 _ if ctx.environment == Environment::Local => {
240 let bytes = std::fs::read(path).map_err(read_err)?;
241 Ok(client
242 .upload_artifact(task_id, filename.into(), content_type.into(), bytes)
243 .await?)
244 }
245 _ => Err(CmdError::Server(
246 "this server does not offer direct uploads".into(),
247 )),
248 }
249}
250
251pub(super) struct ResolvedArtifact {
254 path: PathBuf,
255 filename: String,
256 content_type: String,
257}
258
259impl ResolvedArtifact {
260 pub(super) fn from_path(p: &Path) -> Result<Self, CmdError> {
261 if !p.exists() {
262 return Err(CmdError::Usage(format!(
263 "artifact file not found: {}",
264 p.display()
265 )));
266 }
267 let filename = p
268 .file_name()
269 .and_then(|s| s.to_str())
270 .ok_or_else(|| {
271 CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
272 })?
273 .to_string();
274 let ext = p
275 .extension()
276 .and_then(|s| s.to_str())
277 .map(|s| s.to_ascii_lowercase())
278 .unwrap_or_default();
279 let content_type = super::task::content_type_for_ext(&ext).to_string();
280 Ok(Self {
281 path: p.to_path_buf(),
282 filename,
283 content_type,
284 })
285 }
286
287 pub(super) fn display_path(&self) -> String {
288 self.path.display().to_string()
289 }
290}
291
292fn check_upload_url(url: &str, allow_custom: bool) -> Result<(), CmdError> {
296 let is_r2 = reqwest::Url::parse(url).is_ok_and(|u| {
297 u.scheme() == "https"
298 && u.host_str()
299 .is_some_and(|h| h.ends_with(".r2.cloudflarestorage.com"))
300 });
301 if is_r2 || allow_custom {
302 return Ok(());
303 }
304 Err(CmdError::Usage(
305 "refusing presigned upload URL: must be https on *.r2.cloudflarestorage.com".into(),
306 ))
307}
308
309async fn delete(ctx: &Ctx, args: GetArgs) -> CmdResult {
310 let task_id = parse_uuid(&args.task_id, "task id")?;
311 let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
312 if ctx.dry_run {
313 return Ok(Envelope::success(
314 ctx.environment,
315 ctx.dry_run,
316 json!({
317 "action": "would_delete_artifact",
318 "task_id": task_id.to_string(),
319 "artifact_id": artifact_id.to_string(),
320 }),
321 ));
322 }
323 let client = ctx.client()?;
324 match client.inner().delete_artifact(&task_id, &artifact_id).await {
325 Ok(_) => {}
326 Err(e) => return Err(map_api_error(e).await.into()),
327 }
328 Ok(Envelope::success(
329 ctx.environment,
330 ctx.dry_run,
331 json!({
332 "task_id": task_id.to_string(),
333 "artifact_id": artifact_id.to_string(),
334 "deleted": true,
335 }),
336 ))
337}
338
339async fn submit_cid(ctx: &Ctx, args: CidArgs) -> CmdResult {
340 let task_id = parse_uuid(&args.task_id, "task id")?;
341 let output_cid = args.output_cid.trim();
345 if output_cid.is_empty() {
346 return Err(CmdError::Usage("output_cid must not be empty".into()));
347 }
348 if ctx.dry_run {
349 return Ok(Envelope::success(
350 ctx.environment,
351 ctx.dry_run,
352 json!({
353 "action": "would_submit_cid",
354 "task_id": task_id.to_string(),
355 "output_cid": output_cid,
356 }),
357 ));
358 }
359 let client = ctx.client()?;
360 let body = SubmitArtifactCidBody {
361 output_cid: output_cid.to_string(),
362 };
363 let resp = match client.inner().submit_artifact_cid(&task_id, &body).await {
364 Ok(v) => v.into_inner(),
365 Err(e) => return Err(map_api_error(e).await.into()),
366 };
367 Ok(Envelope::success(
368 ctx.environment,
369 ctx.dry_run,
370 json!({
371 "task_id": task_id.to_string(),
372 "artifact": resp,
373 }),
374 ))
375}
376
377async fn update_cid_status(ctx: &Ctx, args: CidStatusArgs) -> CmdResult {
378 let task_id = parse_uuid(&args.task_id, "task id")?;
379 let artifact_id = parse_uuid(&args.artifact_id, "artifact id")?;
380 let cid_status: UpdateArtifactCidStatusBodyCidStatus = args.status.into();
381 if ctx.dry_run {
382 return Ok(Envelope::success(
383 ctx.environment,
384 ctx.dry_run,
385 json!({
386 "action": "would_update_cid_status",
387 "task_id": task_id.to_string(),
388 "artifact_id": artifact_id.to_string(),
389 "cid_status": cid_status.to_string(),
390 }),
391 ));
392 }
393 let client = ctx.client()?;
394 let body = UpdateArtifactCidStatusBody { cid_status };
395 let resp = match client
396 .inner()
397 .update_artifact_cid_status(&task_id, &artifact_id, &body)
398 .await
399 {
400 Ok(v) => v.into_inner(),
401 Err(e) => return Err(map_api_error(e).await.into()),
402 };
403 Ok(Envelope::success(
404 ctx.environment,
405 ctx.dry_run,
406 json!({
407 "task_id": task_id.to_string(),
408 "artifact": resp,
409 }),
410 ))
411}
412
413fn parse_uuid(raw: &str, label: &str) -> Result<Uuid, CmdError> {
414 Uuid::parse_str(raw).map_err(|e| CmdError::Usage(format!("{label} must be a UUID: {e}")))
415}
416
417#[cfg(test)]
418mod tests {
419 use super::check_upload_url;
420
421 #[test]
422 fn upload_url_must_be_https_r2() {
423 assert!(
424 check_upload_url("https://acct.r2.cloudflarestorage.com/pending/x?s=1", false).is_ok()
425 );
426 for bad in [
427 "http://acct.r2.cloudflarestorage.com/pending/x",
428 "https://acct.r2.cloudflarestorage.com.evil.com/x",
429 "https://acct.r2.cloudflarestorage.com@evil.com/x",
430 "https://r2.cloudflarestorage.com/x",
431 "https://evil.com/acct.r2.cloudflarestorage.com",
432 "not a url",
433 ] {
434 assert!(check_upload_url(bad, false).is_err(), "{bad}");
435 }
436 assert!(check_upload_url("http://127.0.0.1:9/x", true).is_ok());
437 }
438}