Skip to main content

brows3_lib/commands/
buckets.rs

1use crate::commands::profiles::ProfileState;
2use crate::s3::{self, BucketInfo, S3State};
3use futures::StreamExt;
4use serde::{Deserialize, Serialize};
5use tauri::State;
6
7#[derive(Debug, Serialize, Deserialize)]
8pub struct BucketWithRegion {
9    pub name: String,
10    pub region: String,
11    pub creation_date: Option<String>,
12    pub object_count: Option<u64>,
13    pub total_size: Option<u64>,
14    pub total_size_formatted: Option<String>,
15}
16
17/// List all accessible S3 buckets
18#[tauri::command]
19pub async fn list_buckets(
20    profile_state: State<'_, ProfileState>,
21    s3_state: State<'_, S3State>,
22) -> Result<Vec<BucketInfo>, String> {
23    // Get active profile
24    let profile_manager = profile_state.read().await;
25    let active_profile = profile_manager
26        .get_active_profile()
27        .await
28        .map_err(|e| e.to_string())?
29        .ok_or_else(|| "No active profile selected".to_string())?;
30
31    drop(profile_manager);
32
33    // Get S3 client
34    let mut s3_manager = s3_state.write().await;
35    let client = s3_manager
36        .get_client(&active_profile)
37        .await
38        .map_err(|e| e.to_string())?
39        .clone();
40    drop(s3_manager);
41
42    // List buckets
43    let buckets = s3::client::list_buckets(&client)
44        .await
45        .map_err(|e| e.to_string())?;
46
47    Ok(buckets)
48}
49
50/// List buckets with their regions
51#[tauri::command]
52pub async fn list_buckets_with_regions(
53    profile_state: State<'_, ProfileState>,
54    s3_state: State<'_, S3State>,
55) -> Result<Vec<BucketWithRegion>, String> {
56    // Get active profile
57    let profile_manager = profile_state.read().await;
58    let active_profile = profile_manager
59        .get_active_profile()
60        .await
61        .map_err(|e| e.to_string())?
62        .ok_or_else(|| "No active profile selected".to_string())?;
63
64    drop(profile_manager);
65
66    // Get S3 client
67    let mut s3_manager = s3_state.write().await;
68    let client = s3_manager
69        .get_client(&active_profile)
70        .await
71        .map_err(|e| e.to_string())?
72        .clone();
73    drop(s3_manager);
74
75    // List buckets
76    let buckets = s3::client::list_buckets(&client)
77        .await
78        .map_err(|e| e.to_string())?;
79
80    // For custom endpoints (non-AWS providers like Linode, DigitalOcean, MinIO, etc.),
81    // the GetBucketLocation API is often unsupported and causes "dispatch failure" errors.
82    // Use the profile's configured region directly instead of querying per-bucket.
83    let is_custom_endpoint = matches!(
84        &active_profile.credential_type,
85        crate::credentials::CredentialType::CustomEndpoint { .. }
86    );
87    let profile_region = active_profile
88        .region
89        .clone()
90        .unwrap_or_else(|| "us-east-1".to_string());
91
92    if is_custom_endpoint {
93        // Skip GetBucketLocation entirely for custom endpoints
94        s3_state.write().await.set_bucket_regions(
95            &active_profile,
96            buckets.iter().map(|bucket| bucket.name.as_str()),
97            &profile_region,
98        );
99        let buckets_with_regions: Vec<BucketWithRegion> = buckets
100            .into_iter()
101            .map(|bucket| BucketWithRegion {
102                name: bucket.name,
103                region: profile_region.clone(),
104                creation_date: bucket.creation_date,
105                object_count: bucket.object_count,
106                total_size: bucket.total_size,
107                total_size_formatted: bucket.total_size_formatted,
108            })
109            .collect();
110
111        return Ok(buckets_with_regions);
112    }
113
114    // For standard AWS profiles, fetch regions in PARALLEL for much faster startup
115    let client_clone = client.clone();
116    let fallback_region = profile_region.clone();
117    let futures: Vec<_> = buckets
118        .into_iter()
119        .map(|bucket| {
120            let client_ref = client_clone.clone();
121            let bucket_name = bucket.name.clone();
122            let fallback = fallback_region.clone();
123            async move {
124                let region = match s3::client::get_bucket_region(&client_ref, &bucket_name).await {
125                    Ok(r) => r,
126                    Err(_) => fallback,
127                };
128                BucketWithRegion {
129                    name: bucket.name,
130                    region,
131                    creation_date: bucket.creation_date,
132                    object_count: bucket.object_count,
133                    total_size: bucket.total_size,
134                    total_size_formatted: bucket.total_size_formatted,
135                }
136            }
137        })
138        .collect();
139
140    let buckets_with_regions = futures::stream::iter(futures)
141        .buffered(8)
142        .collect::<Vec<_>>()
143        .await;
144
145    Ok(buckets_with_regions)
146}
147
148/// Get the region for a specific bucket
149#[tauri::command]
150pub async fn get_bucket_region(
151    bucket_name: String,
152    profile_state: State<'_, ProfileState>,
153    s3_state: State<'_, S3State>,
154) -> Result<String, String> {
155    // Get active profile
156    let profile_manager = profile_state.read().await;
157    let active_profile = profile_manager
158        .get_active_profile()
159        .await
160        .map_err(|e| e.to_string())?
161        .ok_or_else(|| "No active profile selected".to_string())?;
162
163    drop(profile_manager);
164
165    if matches!(
166        &active_profile.credential_type,
167        crate::credentials::CredentialType::CustomEndpoint { .. }
168    ) {
169        let region = active_profile
170            .region
171            .clone()
172            .unwrap_or_else(|| "us-east-1".to_string());
173        let mut s3_manager = s3_state.write().await;
174        s3_manager.set_bucket_region(&active_profile, &bucket_name, region.clone());
175        return Ok(region);
176    }
177
178    // Get S3 client
179    let mut s3_manager = s3_state.write().await;
180    let client = s3_manager
181        .get_client(&active_profile)
182        .await
183        .map_err(|e| e.to_string())?
184        .clone();
185    drop(s3_manager);
186
187    // Get region
188    s3::client::get_bucket_region(&client, &bucket_name)
189        .await
190        .map_err(|e| e.to_string())
191}
192
193/// Refresh the S3 client (clear cache)
194#[tauri::command]
195pub async fn refresh_s3_client(s3_state: State<'_, S3State>) -> Result<(), String> {
196    let mut s3_manager = s3_state.write().await;
197    s3_manager.clear_cache();
198    Ok(())
199}