raps-cli 4.15.0

RAPS (rapeseed) - Rust Autodesk Platform Services CLI
Documentation
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! Bucket management commands
//!
//! Commands for creating, listing, and deleting OSS buckets.

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use serde::Serialize;
use std::str::FromStr;

use crate::commands::tracked::tracked_op;
use crate::output::OutputFormat;
// use raps_kernel::output::OutputFormat;
use raps_kernel::prompts;
use raps_oss::{OssClient, Region, RetentionPolicy};

#[derive(Debug, Subcommand)]
pub enum BucketCommands {
    /// Create a new bucket (interactive)
    Create {
        /// Bucket key (optional, will prompt if not provided)
        #[arg(short, long)]
        key: Option<String>,

        /// Retention policy: transient, temporary, or persistent
        #[arg(short, long)]
        policy: Option<String>,

        /// Region: US or EMEA
        #[arg(short, long)]
        region: Option<String>,
    },

    /// List all buckets
    List,

    /// Show bucket details
    Info {
        /// Bucket key
        bucket_key: String,
    },

    /// Delete a bucket
    Delete {
        /// Bucket key to delete
        bucket_key: Option<String>,

        /// Skip confirmation prompt
        #[arg(short = 'y', long)]
        yes: bool,
    },
}

impl BucketCommands {
    pub async fn execute(self, client: &OssClient, output_format: OutputFormat) -> Result<()> {
        match self {
            BucketCommands::Create {
                key,
                policy,
                region,
            } => create_bucket(client, key, policy, region, output_format).await,
            BucketCommands::List => list_buckets(client, output_format).await,
            BucketCommands::Info { bucket_key } => {
                bucket_info(client, &bucket_key, output_format).await
            }
            BucketCommands::Delete { bucket_key, yes } => {
                delete_bucket(client, bucket_key, yes, output_format).await
            }
        }
    }
}

/// Serializable bucket representation for output
#[derive(Debug, Serialize)]
struct BucketOutput {
    bucket_key: String,
    policy_key: String,
    bucket_owner: String,
    created_date: u64,
    created_date_human: String,
    region: String,
}

/// Serializable bucket info representation
#[derive(Debug, Serialize)]
struct BucketInfoOutput {
    bucket_key: String,
    bucket_owner: String,
    policy_key: String,
    created_date: u64,
    created_date_human: String,
    permissions: Vec<PermissionOutput>,
}

#[derive(Debug, Serialize)]
struct PermissionOutput {
    auth_id: String,
    access: String,
}

async fn create_bucket(
    client: &OssClient,
    key: Option<String>,
    policy: Option<String>,
    region: Option<String>,
    output_format: OutputFormat,
) -> Result<()> {
    // Generate a unique prefix suggestion based on timestamp
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let suggested_prefix = format!("aps-{}", timestamp);

    // Get bucket key interactively if not provided
    let bucket_key = match key {
        Some(k) => k,
        None => {
            println!(
                "{}",
                "Note: Bucket keys must be globally unique across all APS applications.".yellow()
            );
            println!(
                "{}",
                format!(
                    "Suggestion: Use a prefix like '{}-yourname'",
                    suggested_prefix
                )
                .dimmed()
            );

            prompts::input_validated(
                "Enter bucket key",
                Some(&suggested_prefix),
                |input: &String| {
                    if input.len() < 3 {
                        Err("Bucket key must be at least 3 characters")
                    } else if input.len() > 128 {
                        Err("Bucket key must be at most 128 characters")
                    } else if !input.chars().all(|c| {
                        c.is_ascii_lowercase()
                            || c.is_ascii_digit()
                            || c == '-'
                            || c == '_'
                            || c == '.'
                    }) {
                        Err(
                            "Bucket key can only contain lowercase letters, numbers, hyphens, underscores, and dots",
                        )
                    } else {
                        Ok(())
                    }
                },
            )?
        }
    };

    // Get region interactively if not provided
    let selected_region = match region {
        Some(r) => {
            // Try to find matching region from the enum list
            let regions = Region::all();
            regions
                .iter()
                .find(|reg| reg.to_string().to_uppercase() == r.to_uppercase())
                .cloned()
                .ok_or_else(|| {
                    let available = regions
                        .iter()
                        .map(|reg| reg.to_string())
                        .collect::<Vec<_>>()
                        .join(", ");
                    anyhow::anyhow!("Invalid region. Available regions: {}", available)
                })?
        }
        None => {
            // Default to US, or prompt if interactive
            let regions = Region::all();
            let region_labels: Vec<String> = regions.iter().map(|r| r.to_string()).collect();
            let selection = prompts::select_with_default("Select region", &region_labels, 0)?;
            regions[selection]
        }
    };

    // Get retention policy interactively if not provided
    let selected_policy = match policy {
        Some(p) => RetentionPolicy::from_str(&p).map_err(|_| {
            anyhow::anyhow!("Invalid policy. Use transient, temporary, or persistent.")
        })?,
        None => {
            // Default to transient, or prompt if interactive
            let policies = RetentionPolicy::all();
            let policy_labels: Vec<String> = policies
                .iter()
                .map(|p| match p {
                    RetentionPolicy::Transient => "transient (deleted after 24 hours)".to_string(),
                    RetentionPolicy::Temporary => "temporary (deleted after 30 days)".to_string(),
                    RetentionPolicy::Persistent => "persistent (kept until deleted)".to_string(),
                })
                .collect();

            let selection =
                prompts::select_with_default("Select retention policy", &policy_labels, 0)?;
            policies[selection]
        }
    };

    if output_format.supports_colors() {
        println!("{}", "Creating bucket...".dimmed());
    }

    let bucket = client
        .create_bucket(&bucket_key, selected_policy, selected_region)
        .await
        .context(format!(
            "Failed to create bucket '{}'. Bucket keys must be globally unique",
            bucket_key
        ))?;

    let bucket_output = BucketInfoOutput {
        bucket_key: bucket.bucket_key.clone(),
        bucket_owner: bucket.bucket_owner.clone(),
        policy_key: bucket.policy_key.clone(),
        created_date: bucket.created_date,
        created_date_human: chrono_humanize(bucket.created_date),
        permissions: bucket
            .permissions
            .iter()
            .map(|p| PermissionOutput {
                auth_id: p.auth_id.clone(),
                access: p.access.clone(),
            })
            .collect(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("{} Bucket created successfully!", "".green().bold());
            println!("  {} {}", "Key:".bold(), bucket.bucket_key);
            println!("  {} {}", "Policy:".bold(), bucket.policy_key);
            println!("  {} {}", "Owner:".bold(), bucket.bucket_owner);
        }
        _ => {
            output_format.write(&bucket_output)?;
        }
    }

    Ok(())
}

async fn list_buckets(client: &OssClient, output_format: OutputFormat) -> Result<()> {
    match output_format {
        OutputFormat::Table => list_buckets_streaming(client).await,
        _ => list_buckets_batch(client, output_format).await,
    }
}

/// Streaming bucket listing for Table mode — displays results per-region as they arrive.
async fn list_buckets_streaming(client: &OssClient) -> Result<()> {
    use raps_kernel::api_health;

    let spinner = raps_kernel::progress::spinner("Fetching buckets from US, EMEA...");
    let start = std::time::Instant::now();

    let region_results = client.list_buckets_streaming().await;
    let elapsed = start.elapsed();

    let snap = api_health::snapshot();
    let status_suffix = if snap.sample_count > 0 {
        format!(
            " ({}, avg: {}, API: {})",
            api_health::format_duration_ms(elapsed),
            api_health::format_duration_ms(snap.avg_latency),
            snap.health_status,
        )
    } else {
        format!(" ({})", api_health::format_duration_ms(elapsed))
    };
    spinner.finish_with_message(format!(
        "\u{2713} Fetching buckets from all regions{}",
        status_suffix
    ));

    let mut all_outputs = Vec::new();

    for rr in &region_results {
        match &rr.buckets {
            Ok(buckets) => {
                println!(
                    "{} {} responded ({}) \u{2014} {} buckets",
                    "\u{2713}".green().bold(),
                    rr.region,
                    api_health::format_duration_ms(rr.elapsed),
                    buckets.len(),
                );
                for b in buckets {
                    all_outputs.push(BucketOutput {
                        bucket_key: b.bucket_key.clone(),
                        policy_key: b.policy_key.clone(),
                        bucket_owner: String::new(),
                        created_date: b.created_date,
                        created_date_human: chrono_humanize(b.created_date),
                        region: b.region.as_deref().unwrap_or("US").to_string(),
                    });
                }
            }
            Err(e) => {
                println!(
                    "{} {} failed ({}) \u{2014} {}",
                    "\u{2717}".red().bold(),
                    rr.region,
                    api_health::format_duration_ms(rr.elapsed),
                    e,
                );
            }
        }
    }

    if all_outputs.is_empty() {
        println!("{}", "No buckets found.".yellow());
        return Ok(());
    }

    println!("\n{}", "Buckets:".bold());
    println!("{}", "-".repeat(90));
    println!(
        "{:<40} {:<12} {:<8} {}",
        "Bucket Key".bold(),
        "Policy".bold(),
        "Region".bold(),
        "Created".bold()
    );
    println!("{}", "-".repeat(90));

    for bucket in &all_outputs {
        println!(
            "{:<40} {:<12} {:<8} {}",
            bucket.bucket_key.cyan(),
            bucket.policy_key,
            bucket.region.yellow(),
            bucket.created_date_human.dimmed()
        );
    }

    println!("{}", "-".repeat(90));
    Ok(())
}

/// Batch bucket listing for structured output (JSON/YAML/CSV).
async fn list_buckets_batch(client: &OssClient, output_format: OutputFormat) -> Result<()> {
    let buckets = client
        .list_buckets()
        .await
        .context("Failed to list buckets. Check your authentication with 'raps auth test'")?;

    if buckets.is_empty() {
        output_format.write(&Vec::<BucketOutput>::new())?;
        return Ok(());
    }

    let bucket_outputs: Vec<BucketOutput> = buckets
        .iter()
        .map(|b| BucketOutput {
            bucket_key: b.bucket_key.clone(),
            policy_key: b.policy_key.clone(),
            bucket_owner: String::new(),
            created_date: b.created_date,
            created_date_human: chrono_humanize(b.created_date),
            region: b.region.as_deref().unwrap_or("US").to_string(),
        })
        .collect();

    output_format.write(&bucket_outputs)?;
    Ok(())
}

async fn bucket_info(
    client: &OssClient,
    bucket_key: &str,
    output_format: OutputFormat,
) -> Result<()> {
    let bucket = tracked_op("Fetching bucket details", output_format, || async {
        client.get_bucket_details(bucket_key).await.context(format!(
            "Failed to get bucket details for '{}'. Verify the bucket key is correct",
            bucket_key
        ))
    })
    .await?;

    let bucket_output = BucketInfoOutput {
        bucket_key: bucket.bucket_key.clone(),
        bucket_owner: bucket.bucket_owner.clone(),
        policy_key: bucket.policy_key.clone(),
        created_date: bucket.created_date,
        created_date_human: chrono_humanize(bucket.created_date),
        permissions: bucket
            .permissions
            .iter()
            .map(|p| PermissionOutput {
                auth_id: p.auth_id.clone(),
                access: p.access.clone(),
            })
            .collect(),
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Bucket Details".bold());
            println!("{}", "-".repeat(60));

            println!("  {} {}", "Key:".bold(), bucket.bucket_key.cyan());
            println!("  {} {}", "Owner:".bold(), bucket.bucket_owner);
            println!("  {} {}", "Policy:".bold(), bucket.policy_key);
            println!(
                "  {} {}",
                "Created:".bold(),
                bucket_output.created_date_human
            );

            if !bucket.permissions.is_empty() {
                println!("\n  {}:", "Permissions".bold());
                for perm in &bucket.permissions {
                    println!(
                        "    {} {}: {}",
                        "-".cyan(),
                        perm.auth_id.dimmed(),
                        perm.access
                    );
                }
            }

            println!("{}", "-".repeat(60));
        }
        _ => {
            output_format.write(&bucket_output)?;
        }
    }

    Ok(())
}

async fn delete_bucket(
    client: &OssClient,
    bucket_key: Option<String>,
    skip_confirm: bool,
    output_format: OutputFormat,
) -> Result<()> {
    // Get bucket key interactively if not provided
    let key = match bucket_key {
        Some(k) => k,
        None => {
            // List buckets and let user select
            let buckets = client
                .list_buckets()
                .await
                .context("Failed to list buckets")?;
            if buckets.is_empty() {
                println!("{}", "No buckets found to delete.".yellow());
                return Ok(());
            }

            let bucket_keys: Vec<String> = buckets.iter().map(|b| b.bucket_key.clone()).collect();

            let selection = prompts::select("Select bucket to delete", &bucket_keys)?;
            bucket_keys[selection].clone()
        }
    };

    // Confirm deletion (respects --yes flag in non-interactive mode)
    if !skip_confirm {
        let confirmed = prompts::confirm_destructive(format!(
            "Are you sure you want to delete bucket '{}'?",
            key.red()
        ))?;

        if !confirmed {
            println!("{}", "Deletion cancelled.".yellow());
            return Ok(());
        }
    }

    if output_format.supports_colors() {
        println!("{}", "Deleting bucket...".dimmed());
    }

    client.delete_bucket(&key).await.context(format!(
        "Failed to delete bucket '{}'. The bucket must be empty before deletion",
        key
    ))?;

    #[derive(Serialize)]
    struct DeleteResult {
        success: bool,
        bucket_key: String,
        message: String,
    }

    let result = DeleteResult {
        success: true,
        bucket_key: key.clone(),
        message: format!("Bucket '{}' deleted successfully!", key),
    };

    match output_format {
        OutputFormat::Table => {
            println!(
                "{} Bucket '{}' deleted successfully!",
                "".green().bold(),
                key
            );
        }
        _ => {
            output_format.write(&result)?;
        }
    }

    Ok(())
}

/// Convert millisecond timestamp to human-readable format
fn chrono_humanize(timestamp_ms: u64) -> String {
    use std::time::{Duration, UNIX_EPOCH};

    let duration = Duration::from_millis(timestamp_ms);
    let datetime = UNIX_EPOCH + duration;

    if let Ok(elapsed) = datetime.elapsed() {
        let secs = elapsed.as_secs();
        if secs < 60 {
            format!("{} seconds ago", secs)
        } else if secs < 3600 {
            format!("{} minutes ago", secs / 60)
        } else if secs < 86400 {
            format!("{} hours ago", secs / 3600)
        } else {
            format!("{} days ago", secs / 86400)
        }
    } else {
        "in the future".to_string()
    }
}