aurabase 0.1.1

Official Rust SDK for Aurabase: high-performance open-source Backend-as-a-Service (BaaS)
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
use crate::client::{AuraClient, RequestBody};
use crate::error::AuraError;
use crate::types::{AuraResponse, FileEntry, ObjectMeta, StorageBucket, UploadResult};

pub struct StorageService {
    client: AuraClient,
}

#[derive(Debug, Clone, Default)]
pub struct UploadOptions {
    pub content_type: Option<String>,
    pub upsert: Option<bool>,
}

impl StorageService {
    pub fn new(client: AuraClient) -> Self {
        Self { client }
    }

    fn prefix(&self) -> String {
        "/v1/storage".to_string()
    }

    // -- Buckets -------------------------------------------------------------

    pub async fn list_buckets(&self) -> Result<AuraResponse<Vec<StorageBucket>>, AuraError> {
        self.client
            .request(
                reqwest::Method::GET,
                &format!("{}/buckets", self.prefix()),
                RequestBody::None,
            )
            .await
    }

    pub async fn get_bucket(&self, id: &str) -> Result<AuraResponse<StorageBucket>, AuraError> {
        self.client
            .request(
                reqwest::Method::GET,
                &format!("{}/buckets/{}", self.prefix(), id),
                RequestBody::None,
            )
            .await
    }

    pub async fn create_bucket(
        &self,
        name: &str,
        public: Option<bool>,
        file_size_limit: Option<u64>,
        allowed_mime_types: Option<Vec<String>>,
    ) -> Result<AuraResponse<StorageBucket>, AuraError> {
        let body = serde_json::json!({
            "name": name,
            "public": public.unwrap_or(false),
            "file_size_limit": file_size_limit,
            "allowed_mime_types": allowed_mime_types,
        });

        self.client
            .request(
                reqwest::Method::POST,
                &format!("{}/buckets", self.prefix()),
                RequestBody::Json(body),
            )
            .await
    }

    pub async fn delete_bucket(
        &self,
        id: &str,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        self.client
            .request(
                reqwest::Method::DELETE,
                &format!("{}/buckets/{}", self.prefix(), id),
                RequestBody::None,
            )
            .await
    }

    // -- Objects -------------------------------------------------------------

    pub async fn upload(
        &self,
        bucket_id: &str,
        path: &str,
        file_data: Vec<u8>,
        options: Option<UploadOptions>,
    ) -> Result<AuraResponse<UploadResult>, AuraError> {
        let mut form = reqwest::multipart::Form::new();

        let mime = options
            .as_ref()
            .and_then(|o| o.content_type.clone())
            .unwrap_or_else(|| "application/octet-stream".to_string());

        let part = reqwest::multipart::Part::bytes(file_data)
            .file_name(path.to_string())
            .mime_str(&mime)
            .map_err(|e| AuraError::serialization(&e.to_string()))?;

        form = form.part("file", part);

        if let Some(opts) = options {
            if opts.upsert.unwrap_or(false) {
                form = form.text("upsert", "true");
            }
        }

        self.client
            .request(
                reqwest::Method::POST,
                &format!("{}/{}", self.prefix(), bucket_id),
                RequestBody::Multipart(form),
            )
            .await
    }

    pub async fn download(
        &self,
        bucket_id: &str,
        path: &str,
    ) -> Result<AuraResponse<Vec<u8>>, AuraError> {
        let base = self.client.base_url().trim_end_matches('/');
        let prefix = self.prefix();
        let prefix_clean = prefix.trim_start_matches('/');
        let full_url = format!("{}/{}/{}/{}", base, prefix_clean, bucket_id, path);
        let mut builder = self.client.inner.http_client.get(&full_url);

        if let Some(ref api_key) = self.client.inner.api_key {
            builder = builder.header("apikey", api_key);
        }
        if let Some(token) = self.client.inner.auth_store.token() {
            builder = builder.header("Authorization", format!("Bearer {}", token));
        }

        let res = builder
            .send()
            .await
            .map_err(|e| AuraError::network(&e.to_string()))?;

        let status = res.status().as_u16();

        if !res.status().is_success() {
            let body_val: Option<serde_json::Value> = res.json().await.ok();
            let mut code = format!("http_{}", status);
            let mut message = format!("HTTP {}", status);
            let mut details = None;

            if let Some(ref body) = body_val {
                details = Some(body.clone());
                if let Some(err_obj) = body.get("error") {
                    if let Some(c) = err_obj.get("code").and_then(|v| v.as_str()) {
                        code = c.to_string();
                    }
                    if let Some(m) = err_obj.get("message").and_then(|v| v.as_str()) {
                        message = m.to_string();
                    }
                }
            }

            return Ok(AuraResponse {
                data: None,
                error: Some(AuraError::new(status, &code, &message, details)),
                meta: None,
            });
        }

        let bytes = res
            .bytes()
            .await
            .map_err(|e| AuraError::network(&e.to_string()))?;

        Ok(AuraResponse {
            data: Some(bytes.to_vec()),
            error: None,
            meta: None,
        })
    }

    pub async fn list(
        &self,
        bucket_id: &str,
        prefix: Option<&str>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<AuraResponse<Vec<FileEntry>>, AuraError> {
        let mut query = Vec::new();
        if let Some(p) = prefix {
            query.push(format!("prefix={}", urlencoding::encode(p)));
        }
        if let Some(l) = limit {
            query.push(format!("limit={}", l));
        }
        if let Some(o) = offset {
            query.push(format!("offset={}", o));
        }

        let qs = if query.is_empty() {
            "".to_string()
        } else {
            format!("?{}", query.join("&"))
        };

        let mut res: AuraResponse<Vec<FileEntry>> = self
            .client
            .request(
                reqwest::Method::GET,
                &format!("{}/{}{}", self.prefix(), bucket_id, qs),
                RequestBody::None,
            )
            .await?;

        // Le backend renvoie une clé préfixée du bucket LOGIQUE (s3.rs
        // strip_project_prefix ne retire que `{project_id}/`). On la rend
        // RELATIVE, pour qu'elle soit réutilisable telle quelle avec
        // download()/remove()/copy() — comme la clé que renvoie upload().
        if let Some(entries) = res.data.as_mut() {
            let bucket_prefix = format!("{}/", bucket_id);
            for entry in entries.iter_mut() {
                if let Some(stripped) = entry.name.strip_prefix(bucket_prefix.as_str()) {
                    entry.name = stripped.to_string();
                }
            }
        }

        Ok(res)
    }

    pub async fn remove(
        &self,
        bucket_id: &str,
        paths: Vec<String>,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        if paths.len() == 1 {
            return self
                .client
                .request(
                    reqwest::Method::DELETE,
                    &format!("{}/{}/{}", self.prefix(), bucket_id, paths[0]),
                    RequestBody::None,
                )
                .await;
        }

        // Suppression multiple séquentielle comme le fait le SDK JS
        let mut last_res = AuraResponse {
            data: None,
            error: None,
            meta: None,
        };

        for p in paths {
            let res = self
                .client
                .request::<serde_json::Value>(
                    reqwest::Method::DELETE,
                    &format!("{}/{}/{}", self.prefix(), bucket_id, p),
                    RequestBody::None,
                )
                .await?;

            if res.error.is_some() {
                return Ok(res);
            }
            last_res = res;
        }

        Ok(last_res)
    }

    /// Copy a file within a bucket (or to another logical bucket of the same project).
    ///
    /// `from_path`/`to_path` sont relatifs au bucket (cohérent avec `download`/
    /// `remove`/`upload`, et avec la clé que `upload()` renvoie) et sont envoyés
    /// TELS QUELS : c'est le backend qui les préfixe du bucket issu du path
    /// (`manage.rs` `copy_file` : `format!("{}/{}", bucket_name, body.src_key)`).
    /// Les préfixer ici produisait `bucket/bucket/clé` — clé physique
    /// inexistante, d'où un échec systématique « Copie S3: service error ».
    pub async fn copy(
        &self,
        bucket_id: &str,
        from_path: &str,
        to_path: &str,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        let body = serde_json::json!({
            "src_key": from_path,
            "dst_key": to_path,
        });

        self.client
            .request(
                reqwest::Method::POST,
                &format!("{}/{}/copy", self.prefix(), bucket_id),
                RequestBody::Json(body),
            )
            .await
    }

    /// Move/rename a file within a bucket.
    ///
    /// `from_path`/`to_path` sont relatifs au bucket et envoyés TELS QUELS —
    /// voir `copy()` : c'est le backend (`manage.rs` `move_file`) qui les
    /// préfixe du bucket issu du path.
    pub async fn move_object(
        &self,
        bucket_id: &str,
        from_path: &str,
        to_path: &str,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        let body = serde_json::json!({
            "src_key": from_path,
            "dst_key": to_path,
        });

        self.client
            .request(
                reqwest::Method::POST,
                &format!("{}/{}/move", self.prefix(), bucket_id),
                RequestBody::Json(body),
            )
            .await
    }

    pub async fn get_metadata(
        &self,
        bucket_id: &str,
        path: &str,
    ) -> Result<AuraResponse<ObjectMeta>, AuraError> {
        self.client
            .request(
                reqwest::Method::GET,
                &format!("{}/{}/meta/{}", self.prefix(), bucket_id, path),
                RequestBody::None,
            )
            .await
    }

    pub async fn create_signed_url(
        &self,
        bucket_id: &str,
        path: &str,
        expires_in_seconds: Option<u32>,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        let ttl = expires_in_seconds.unwrap_or(3600);
        self.client
            .request(
                reqwest::Method::GET,
                &format!(
                    "{}/{}/signed-url?key={}&ttl_secs={}",
                    self.prefix(),
                    bucket_id,
                    urlencoding::encode(path),
                    ttl
                ),
                RequestBody::None,
            )
            .await
    }

    pub async fn create_signed_upload_url(
        &self,
        bucket_id: &str,
        path: &str,
        expires_in_seconds: Option<u32>,
    ) -> Result<AuraResponse<serde_json::Value>, AuraError> {
        let ttl = expires_in_seconds.unwrap_or(3600);
        self.client
            .request(
                reqwest::Method::GET,
                &format!(
                    "{}/{}/upload-url?key={}&ttl_secs={}",
                    self.prefix(),
                    bucket_id,
                    urlencoding::encode(path),
                    ttl
                ),
                RequestBody::None,
            )
            .await
    }

    /// Construit l'URL de lecture directe d'un objet. Aucun appel réseau.
    ///
    /// ⚠️ Si le bucket a été créé avec `public: true`, cette URL est RÉELLEMENT publique : elle
    /// répond **sans aucune clé API**. Le gateway laisse passer les `GET` d'objet dépourvus de
    /// clé (bypass « public bucket downloads ») et c'est le service storage qui vérifie le
    /// drapeau du bucket, en fail-closed. Ne mettez donc dans un bucket public que ce qui peut
    /// être servi à tout Internet.
    ///
    /// Sur un bucket PRIVÉ, cette URL répond 401/403 : utilisez `create_signed_url()` pour un
    /// partage temporaire (URL signée HMAC, vérifiée sans clé API, avec expiration).
    ///
    /// L'URL est construite localement, donc jamais validée : un chemin inexistant produit une
    /// URL qui répondra 404.
    pub fn get_public_url(&self, bucket_id: &str, path: &str) -> String {
        let base = self.client.base_url().trim_end_matches('/');
        let prefix = self.prefix();
        let prefix_clean = prefix.trim_start_matches('/');
        format!("{}/{}/{}/{}", base, prefix_clean, bucket_id, path)
    }
}