supabase-client-storage 0.2.2

Storage HTTP client for supabase-client
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
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use serde::de::DeserializeOwned;
use serde_json::json;
use url::Url;

use crate::bucket_api::StorageBucketApi;
use crate::error::{StorageApiErrorResponse, StorageError};
use crate::types::*;

/// HTTP client for Supabase Storage API.
///
/// Communicates with Storage REST endpoints at `/storage/v1/...`.
///
/// # Example
/// ```ignore
/// use supabase_client_storage::StorageClient;
///
/// let storage = StorageClient::new("https://your-project.supabase.co", "your-anon-key")?;
/// let buckets = storage.list_buckets().await?;
/// let file_api = storage.from("avatars");
/// ```
#[derive(Debug, Clone)]
pub struct StorageClient {
    http: reqwest::Client,
    base_url: Url,
    api_key: String,
}

impl StorageClient {
    /// Create a new storage client.
    ///
    /// `supabase_url` is the project URL (e.g., `https://your-project.supabase.co`).
    /// `api_key` is the Supabase anon or service_role key.
    pub fn new(supabase_url: &str, api_key: &str) -> Result<Self, StorageError> {
        let base = supabase_url.trim_end_matches('/');
        let base_url = Url::parse(&format!("{}/storage/v1", base))?;

        let mut default_headers = HeaderMap::new();
        default_headers.insert(
            "apikey",
            HeaderValue::from_str(api_key)
                .map_err(|e| StorageError::InvalidConfig(format!("Invalid API key header: {}", e)))?,
        );
        default_headers.insert(
            reqwest::header::AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {}", api_key))
                .map_err(|e| StorageError::InvalidConfig(format!("Invalid auth header: {}", e)))?,
        );
        default_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        let http = reqwest::Client::builder()
            .default_headers(default_headers)
            .build()
            .map_err(StorageError::Http)?;

        Ok(Self {
            http,
            base_url,
            api_key: api_key.to_string(),
        })
    }

    /// Get the base URL for the storage API.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    // ─── Bucket Operations ───────────────────────────────────────

    /// List all buckets.
    pub async fn list_buckets(&self) -> Result<Vec<Bucket>, StorageError> {
        let url = self.url("/bucket");
        let resp = self.http.get(url).send().await?;
        self.handle_response(resp).await
    }

    /// Get a bucket by ID.
    pub async fn get_bucket(&self, id: &str) -> Result<Bucket, StorageError> {
        let url = self.url(&format!("/bucket/{}", id));
        let resp = self.http.get(url).send().await?;
        self.handle_response(resp).await
    }

    /// Create a new bucket.
    pub async fn create_bucket(
        &self,
        id: &str,
        options: BucketOptions,
    ) -> Result<CreateBucketResponse, StorageError> {
        let url = self.url("/bucket");
        let mut body = json!({
            "id": id,
            "name": id,
        });
        if let Some(public) = options.public {
            body["public"] = json!(public);
        }
        if let Some(limit) = options.file_size_limit {
            body["file_size_limit"] = json!(limit);
        }
        if let Some(types) = options.allowed_mime_types {
            body["allowed_mime_types"] = json!(types);
        }

        let resp = self.http.post(url).json(&body).send().await?;
        self.handle_response(resp).await
    }

    /// Update a bucket.
    pub async fn update_bucket(
        &self,
        id: &str,
        options: BucketOptions,
    ) -> Result<(), StorageError> {
        let url = self.url(&format!("/bucket/{}", id));
        let mut body = json!({
            "id": id,
            "name": id,
        });
        if let Some(public) = options.public {
            body["public"] = json!(public);
        }
        if let Some(limit) = options.file_size_limit {
            body["file_size_limit"] = json!(limit);
        }
        if let Some(types) = options.allowed_mime_types {
            body["allowed_mime_types"] = json!(types);
        }

        let resp = self.http.put(url).json(&body).send().await?;
        self.handle_empty_response(resp).await
    }

    /// Empty a bucket (remove all files).
    pub async fn empty_bucket(&self, id: &str) -> Result<(), StorageError> {
        let url = self.url(&format!("/bucket/{}/empty", id));
        let resp = self.http.post(url).json(&json!({})).send().await?;
        self.handle_empty_response(resp).await
    }

    /// Delete a bucket. The bucket must be empty first.
    pub async fn delete_bucket(&self, id: &str) -> Result<(), StorageError> {
        let url = self.url(&format!("/bucket/{}", id));
        let resp = self.http.delete(url).json(&json!({})).send().await?;
        self.handle_empty_response(resp).await
    }

    // ─── File API Factory ────────────────────────────────────────

    /// Create a file operations API scoped to a bucket.
    ///
    /// Mirrors `supabase.storage.from('bucket')`.
    pub fn from(&self, bucket: &str) -> StorageBucketApi {
        StorageBucketApi::new(self.clone(), bucket.to_string())
    }

    // ─── Internal Helpers ────────────────────────────────────────

    pub(crate) fn url(&self, path: &str) -> Url {
        let mut url = self.base_url.clone();
        let current = url.path().to_string();
        if let Some(query_start) = path.find('?') {
            url.set_path(&format!("{}{}", current, &path[..query_start]));
            url.set_query(Some(&path[query_start + 1..]));
        } else {
            url.set_path(&format!("{}{}", current, path));
        }
        url
    }

    pub(crate) fn http(&self) -> &reqwest::Client {
        &self.http
    }

    #[allow(dead_code)]
    pub(crate) fn api_key(&self) -> &str {
        &self.api_key
    }

    pub(crate) async fn handle_response<T: DeserializeOwned>(
        &self,
        resp: reqwest::Response,
    ) -> Result<T, StorageError> {
        let status = resp.status().as_u16();
        if status >= 400 {
            return Err(self.parse_error(status, resp).await);
        }
        let body: T = resp.json().await?;
        Ok(body)
    }

    pub(crate) async fn handle_empty_response(
        &self,
        resp: reqwest::Response,
    ) -> Result<(), StorageError> {
        let status = resp.status().as_u16();
        if status >= 400 {
            return Err(self.parse_error(status, resp).await);
        }
        Ok(())
    }

    pub(crate) async fn handle_bytes_response(
        &self,
        resp: reqwest::Response,
    ) -> Result<Vec<u8>, StorageError> {
        let status = resp.status().as_u16();
        if status >= 400 {
            return Err(self.parse_error(status, resp).await);
        }
        let bytes = resp.bytes().await?;
        Ok(bytes.to_vec())
    }

    async fn parse_error(&self, status: u16, resp: reqwest::Response) -> StorageError {
        match resp.json::<StorageApiErrorResponse>().await {
            Ok(err_resp) => StorageError::Api {
                status,
                message: err_resp.error_message(),
            },
            Err(_) => StorageError::Api {
                status,
                message: format!("HTTP {}", status),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn client_new_ok() {
        let client = StorageClient::new("https://example.supabase.co", "test-key");
        assert!(client.is_ok());
    }

    #[test]
    fn client_base_url() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        assert_eq!(client.base_url().path(), "/storage/v1");
    }

    #[test]
    fn client_base_url_trailing_slash() {
        let client = StorageClient::new("https://example.supabase.co/", "test-key").unwrap();
        assert_eq!(client.base_url().path(), "/storage/v1");
    }

    #[test]
    fn url_building() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();

        let url = client.url("/bucket");
        assert_eq!(url.path(), "/storage/v1/bucket");
        assert!(url.query().is_none());

        let url = client.url("/bucket/avatars");
        assert_eq!(url.path(), "/storage/v1/bucket/avatars");
    }

    #[test]
    fn url_building_with_query() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let url = client.url("/object/upload/sign/bucket/path?token=abc");
        assert_eq!(url.path(), "/storage/v1/object/upload/sign/bucket/path");
        assert_eq!(url.query(), Some("token=abc"));
    }

    #[test]
    fn public_url_construction() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("avatars");
        let url = api.get_public_url("folder/photo.png");
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/object/public/avatars/folder/photo.png"
        );
    }

    #[test]
    fn public_url_with_transform_all_options() {
        use crate::types::{TransformOptions, ResizeMode, ImageFormat};

        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("photos");
        let transform = TransformOptions::new()
            .width(200)
            .height(150)
            .resize(ResizeMode::Cover)
            .quality(80)
            .format(ImageFormat::Origin);
        let url = api.get_public_url_with_transform("photo.jpg", &transform);
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/render/image/public/photos/photo.jpg?width=200&height=150&resize=cover&quality=80&format=origin"
        );
    }

    #[test]
    fn public_url_with_transform_partial() {
        use crate::types::TransformOptions;

        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("photos");
        let transform = TransformOptions::new().width(300);
        let url = api.get_public_url_with_transform("img.png", &transform);
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/render/image/public/photos/img.png?width=300"
        );
    }

    #[test]
    fn public_url_with_empty_transform() {
        use crate::types::TransformOptions;

        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("photos");
        let transform = TransformOptions::default();
        let url = api.get_public_url_with_transform("img.png", &transform);
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/render/image/public/photos/img.png"
        );
    }

    // ─── Phase 10: Download URL Tests ────────────────────────

    #[test]
    fn public_url_with_download_filename() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("docs");
        let url = api.get_public_url_with_download("report.pdf", Some("my-report.pdf"));
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/object/public/docs/report.pdf?download=my-report.pdf"
        );
    }

    #[test]
    fn public_url_with_download_default() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("docs");
        let url = api.get_public_url_with_download("report.pdf", Some(""));
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/object/public/docs/report.pdf?download="
        );
    }

    #[test]
    fn public_url_with_download_none() {
        let client = StorageClient::new("https://example.supabase.co", "test-key").unwrap();
        let api = client.from("docs");
        let url = api.get_public_url_with_download("report.pdf", None);
        assert_eq!(
            url,
            "https://example.supabase.co/storage/v1/object/public/docs/report.pdf"
        );
    }

    // ─── Wiremock Tests ──────────────────────────────────────

    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// Helper: create a StorageClient pointing at the given mock server.
    fn mock_client(server: &MockServer) -> StorageClient {
        StorageClient::new(&server.uri(), "test-anon-key").unwrap()
    }

    #[tokio::test]
    async fn wiremock_exists_returns_false_on_404() {
        let server = MockServer::start().await;
        Mock::given(method("HEAD"))
            .and(path("/storage/v1/object/avatars/missing.png"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let api = client.from("avatars");
        let exists = api.exists("missing.png").await.unwrap();
        assert!(!exists);
    }

    #[tokio::test]
    async fn wiremock_exists_returns_false_on_400() {
        let server = MockServer::start().await;
        Mock::given(method("HEAD"))
            .and(path("/storage/v1/object/avatars/bad-path"))
            .respond_with(ResponseTemplate::new(400))
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let api = client.from("avatars");
        let exists = api.exists("bad-path").await.unwrap();
        assert!(!exists);
    }

    #[tokio::test]
    async fn wiremock_exists_returns_true_on_200() {
        let server = MockServer::start().await;
        Mock::given(method("HEAD"))
            .and(path("/storage/v1/object/avatars/photo.png"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let api = client.from("avatars");
        let exists = api.exists("photo.png").await.unwrap();
        assert!(exists);
    }

    #[tokio::test]
    async fn wiremock_exists_returns_error_on_500() {
        let server = MockServer::start().await;
        Mock::given(method("HEAD"))
            .and(path("/storage/v1/object/avatars/error.png"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let api = client.from("avatars");
        let err = api.exists("error.png").await.unwrap_err();
        match err {
            StorageError::Api { status, .. } => assert_eq!(status, 500),
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn wiremock_list_buckets_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/storage/v1/bucket"))
            .respond_with(
                ResponseTemplate::new(403)
                    .set_body_json(serde_json::json!({"message": "Forbidden"})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let err = client.list_buckets().await.unwrap_err();
        match err {
            StorageError::Api { status, message } => {
                assert_eq!(status, 403);
                assert_eq!(message, "Forbidden");
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn wiremock_download_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/storage/v1/object/docs/secret.pdf"))
            .respond_with(
                ResponseTemplate::new(401)
                    .set_body_json(serde_json::json!({"message": "Unauthorized"})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let api = client.from("docs");
        let err = api.download("secret.pdf").await.unwrap_err();
        match err {
            StorageError::Api { status, message } => {
                assert_eq!(status, 401);
                assert_eq!(message, "Unauthorized");
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn wiremock_delete_bucket_error_non_json() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/storage/v1/bucket/locked"))
            .respond_with(ResponseTemplate::new(409).set_body_string("conflict"))
            .mount(&server)
            .await;

        let client = mock_client(&server);
        let err = client.delete_bucket("locked").await.unwrap_err();
        match err {
            StorageError::Api { status, message } => {
                assert_eq!(status, 409);
                // Falls back to "HTTP 409" when JSON parsing fails
                assert_eq!(message, "HTTP 409");
            }
            other => panic!("Expected Api error, got: {:?}", other),
        }
    }
}