vibesql-storage 0.2.0

Storage engine for vibesql SQL database
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
545
546
use std::{sync::Arc, time::Duration};

use bytes::Bytes;
#[cfg(feature = "opendal")]
use opendal::{services, Operator};

/// Blob storage service
///
/// Manages storing and retrieving blobs with support for multiple backends
/// via OpenDAL abstraction layer.
use super::{BlobId, BlobMetadata, BlobStorageConfig};
use crate::{
    database::Database,
    error::{StorageError, StorageResult},
};

/// Blob storage service for file/blob operations
pub struct BlobStorageService {
    #[cfg(feature = "opendal")]
    operator: Option<Operator>,
    config: BlobStorageConfig,
    #[allow(dead_code)]
    db: Arc<Database>,
}

impl BlobStorageService {
    /// Create a new blob storage service
    #[cfg(feature = "opendal")]
    pub fn new(config: BlobStorageConfig, db: Arc<Database>) -> Self {
        let operator = Self::create_operator(&config).ok();
        Self { operator, config, db }
    }

    /// Create a new blob storage service (non-opendal build)
    #[cfg(not(feature = "opendal"))]
    pub fn new(config: BlobStorageConfig, db: Arc<Database>) -> Self {
        Self { config, db }
    }

    /// Create with default configuration (local filesystem)
    pub fn new_default(db: Arc<Database>) -> Self {
        Self::new(BlobStorageConfig::default(), db)
    }

    /// Create an OpenDAL operator based on the configuration
    #[cfg(feature = "opendal")]
    fn create_operator(config: &BlobStorageConfig) -> StorageResult<Operator> {
        match config.backend.as_str() {
            #[cfg(feature = "storage-fs")]
            "fs" | "filesystem" => Self::create_fs_operator(config),

            #[cfg(feature = "storage-s3")]
            "s3" => Self::create_s3_operator(config),

            #[cfg(feature = "storage-gcs")]
            "gcs" => Self::create_gcs_operator(config),

            #[cfg(feature = "storage-azure")]
            "azure" | "azblob" => Self::create_azure_operator(config),

            #[cfg(feature = "storage-memory")]
            "memory" => Self::create_memory_operator(),

            backend => Err(StorageError::Other(format!(
                "Unknown or unsupported storage backend: '{}'. Enable the appropriate feature flag (storage-fs, storage-s3, storage-gcs, storage-azure, storage-memory).",
                backend
            ))),
        }
    }

    /// Create filesystem operator
    #[cfg(all(feature = "opendal", feature = "storage-fs"))]
    fn create_fs_operator(config: &BlobStorageConfig) -> StorageResult<Operator> {
        let root =
            config.config.get("root").and_then(|v| v.as_str()).unwrap_or("/var/vibesql/storage");

        let builder = services::Fs::default().root(root);

        Operator::new(builder).map(|op| op.finish()).map_err(|e| {
            StorageError::Other(format!("Failed to create filesystem operator: {}", e))
        })
    }

    /// Create S3-compatible operator (works with AWS S3, MinIO, Cloudflare R2, etc.)
    #[cfg(all(feature = "opendal", feature = "storage-s3"))]
    fn create_s3_operator(config: &BlobStorageConfig) -> StorageResult<Operator> {
        let bucket = config.config.get("bucket").and_then(|v| v.as_str()).ok_or_else(|| {
            StorageError::Other("S3 backend requires 'bucket' configuration".to_string())
        })?;

        let mut builder = services::S3::default().bucket(bucket);

        // Optional configurations
        if let Some(endpoint) = config.config.get("endpoint").and_then(|v| v.as_str()) {
            builder = builder.endpoint(endpoint);
        }

        if let Some(region) = config.config.get("region").and_then(|v| v.as_str()) {
            builder = builder.region(region);
        }

        if let Some(access_key_id) = config.config.get("access_key_id").and_then(|v| v.as_str()) {
            builder = builder.access_key_id(access_key_id);
        }

        if let Some(secret_access_key) =
            config.config.get("secret_access_key").and_then(|v| v.as_str())
        {
            builder = builder.secret_access_key(secret_access_key);
        }

        if let Some(root) = config.config.get("root").and_then(|v| v.as_str()) {
            builder = builder.root(root);
        }

        Operator::new(builder)
            .map(|op| op.finish())
            .map_err(|e| StorageError::Other(format!("Failed to create S3 operator: {}", e)))
    }

    /// Create Google Cloud Storage operator
    #[cfg(all(feature = "opendal", feature = "storage-gcs"))]
    fn create_gcs_operator(config: &BlobStorageConfig) -> StorageResult<Operator> {
        let bucket = config.config.get("bucket").and_then(|v| v.as_str()).ok_or_else(|| {
            StorageError::Other("GCS backend requires 'bucket' configuration".to_string())
        })?;

        let mut builder = services::Gcs::default().bucket(bucket);

        if let Some(credential) = config.config.get("credential").and_then(|v| v.as_str()) {
            builder = builder.credential(credential);
        }

        if let Some(credential_path) = config.config.get("credential_path").and_then(|v| v.as_str())
        {
            builder = builder.credential_path(credential_path);
        }

        if let Some(root) = config.config.get("root").and_then(|v| v.as_str()) {
            builder = builder.root(root);
        }

        Operator::new(builder)
            .map(|op| op.finish())
            .map_err(|e| StorageError::Other(format!("Failed to create GCS operator: {}", e)))
    }

    /// Create Azure Blob Storage operator
    #[cfg(all(feature = "opendal", feature = "storage-azure"))]
    fn create_azure_operator(config: &BlobStorageConfig) -> StorageResult<Operator> {
        let container =
            config.config.get("container").and_then(|v| v.as_str()).ok_or_else(|| {
                StorageError::Other("Azure backend requires 'container' configuration".to_string())
            })?;

        let mut builder = services::Azblob::default().container(container);

        if let Some(account_name) = config.config.get("account_name").and_then(|v| v.as_str()) {
            builder = builder.account_name(account_name);
        }

        if let Some(account_key) = config.config.get("account_key").and_then(|v| v.as_str()) {
            builder = builder.account_key(account_key);
        }

        if let Some(endpoint) = config.config.get("endpoint").and_then(|v| v.as_str()) {
            builder = builder.endpoint(endpoint);
        }

        if let Some(root) = config.config.get("root").and_then(|v| v.as_str()) {
            builder = builder.root(root);
        }

        Operator::new(builder)
            .map(|op| op.finish())
            .map_err(|e| StorageError::Other(format!("Failed to create Azure operator: {}", e)))
    }

    /// Create in-memory operator (useful for testing)
    #[cfg(all(feature = "opendal", feature = "storage-memory"))]
    fn create_memory_operator() -> StorageResult<Operator> {
        let builder = services::Memory::default();

        Operator::new(builder)
            .map(|op| op.finish())
            .map_err(|e| StorageError::Other(format!("Failed to create memory operator: {}", e)))
    }

    /// Store a blob and return its ID
    #[cfg(feature = "opendal")]
    pub async fn store(&self, data: Bytes, content_type: String) -> StorageResult<BlobId> {
        let id = BlobId::new();
        let size = data.len() as i64;
        let path = id.to_path();

        // Write to backend using OpenDAL operator
        if let Some(ref op) = self.operator {
            op.write(&path, data.to_vec())
                .await
                .map_err(|e| StorageError::Other(format!("Failed to write blob: {}", e)))?;
        } else {
            return Err(StorageError::Other(
                "Storage operator not initialized. Check your configuration.".to_string(),
            ));
        }

        // Store metadata in database
        let metadata = BlobMetadata::new(id.clone(), size, content_type);
        self.store_metadata(&metadata).await?;

        Ok(id)
    }

    /// Store a blob and return its ID (non-opendal build - stub)
    #[cfg(not(feature = "opendal"))]
    pub async fn store(&self, _data: Bytes, _content_type: String) -> StorageResult<BlobId> {
        Err(StorageError::Other(
            "Blob storage requires the 'opendal' feature to be enabled".to_string(),
        ))
    }

    /// Retrieve a blob by ID
    #[cfg(feature = "opendal")]
    pub async fn get(&self, id: &BlobId) -> StorageResult<Bytes> {
        let path = id.to_path();

        if let Some(ref op) = self.operator {
            let data = op
                .read(&path)
                .await
                .map_err(|e| StorageError::Other(format!("Failed to read blob {}: {}", id, e)))?;
            Ok(Bytes::from(data.to_vec()))
        } else {
            Err(StorageError::Other(
                "Storage operator not initialized. Check your configuration.".to_string(),
            ))
        }
    }

    /// Retrieve a blob by ID (non-opendal build - stub)
    #[cfg(not(feature = "opendal"))]
    pub async fn get(&self, id: &BlobId) -> StorageResult<Bytes> {
        Err(StorageError::Other(format!(
            "Blob storage requires the 'opendal' feature to be enabled (blob: {})",
            id
        )))
    }

    /// Get metadata for a blob
    pub async fn get_metadata(&self, id: &BlobId) -> StorageResult<BlobMetadata> {
        // TODO: Query vibesql_storage system table when it's implemented
        Err(StorageError::Other(format!("blob metadata not found: {}", id)))
    }

    /// Delete a blob
    #[cfg(feature = "opendal")]
    pub async fn delete(&self, id: &BlobId) -> StorageResult<()> {
        let path = id.to_path();

        // Delete from backend using OpenDAL operator
        if let Some(ref op) = self.operator {
            op.delete(&path)
                .await
                .map_err(|e| StorageError::Other(format!("Failed to delete blob {}: {}", id, e)))?;
        } else {
            return Err(StorageError::Other(
                "Storage operator not initialized. Check your configuration.".to_string(),
            ));
        }

        // Delete metadata from database
        // TODO: DELETE FROM vibesql_storage when system table is implemented
        Ok(())
    }

    /// Delete a blob (non-opendal build - stub)
    #[cfg(not(feature = "opendal"))]
    pub async fn delete(&self, id: &BlobId) -> StorageResult<()> {
        Err(StorageError::Other(format!(
            "Blob storage requires the 'opendal' feature to be enabled (blob: {})",
            id
        )))
    }

    /// Check if a blob exists
    #[cfg(feature = "opendal")]
    pub async fn exists(&self, id: &BlobId) -> StorageResult<bool> {
        let path = id.to_path();

        if let Some(ref op) = self.operator {
            match op.stat(&path).await {
                Ok(_) => Ok(true),
                Err(e) if e.kind() == opendal::ErrorKind::NotFound => Ok(false),
                Err(e) => {
                    Err(StorageError::Other(format!("Failed to check blob existence: {}", e)))
                }
            }
        } else {
            Err(StorageError::Other(
                "Storage operator not initialized. Check your configuration.".to_string(),
            ))
        }
    }

    /// Check if a blob exists (non-opendal build - stub)
    #[cfg(not(feature = "opendal"))]
    pub async fn exists(&self, id: &BlobId) -> StorageResult<bool> {
        Err(StorageError::Other(format!(
            "Blob storage requires the 'opendal' feature to be enabled (blob: {})",
            id
        )))
    }

    /// Store blob metadata in database
    #[allow(dead_code)]
    async fn store_metadata(&self, _metadata: &BlobMetadata) -> StorageResult<()> {
        // TODO: INSERT into vibesql_storage table when system table is implemented (#3482)
        Ok(())
    }

    /// Generate a URL for accessing a blob
    ///
    /// For local filesystem, returns a relative path.
    /// For cloud storage, returns the storage-specific URL format.
    pub fn get_url(&self, id: &BlobId) -> String {
        match self.config.backend.as_str() {
            "fs" | "filesystem" => format!("/storage/blobs/{}", id.to_url_safe()),
            "s3" => {
                if let Some(bucket) = self.config.config.get("bucket").and_then(|v| v.as_str()) {
                    if let Some(endpoint) =
                        self.config.config.get("endpoint").and_then(|v| v.as_str())
                    {
                        format!("{}/{}/{}", endpoint, bucket, id.to_path())
                    } else {
                        format!("s3://{}/{}", bucket, id.to_path())
                    }
                } else {
                    format!("s3://unknown/{}", id.to_path())
                }
            }
            "gcs" => {
                if let Some(bucket) = self.config.config.get("bucket").and_then(|v| v.as_str()) {
                    format!("gs://{}/{}", bucket, id.to_path())
                } else {
                    format!("gs://unknown/{}", id.to_path())
                }
            }
            "azure" | "azblob" => {
                if let Some(container) =
                    self.config.config.get("container").and_then(|v| v.as_str())
                {
                    if let Some(account) =
                        self.config.config.get("account_name").and_then(|v| v.as_str())
                    {
                        format!(
                            "https://{}.blob.core.windows.net/{}/{}",
                            account,
                            container,
                            id.to_path()
                        )
                    } else {
                        format!("azure://{}/{}", container, id.to_path())
                    }
                } else {
                    format!("azure://unknown/{}", id.to_path())
                }
            }
            "memory" => format!("memory://{}", id.to_path()),
            _ => format!("/storage/blobs/{}", id.to_url_safe()),
        }
    }

    /// Generate a presigned URL for temporary access to a blob
    ///
    /// This is primarily useful for cloud backends (S3, GCS, Azure) where you want to
    /// give temporary, direct access to a blob without going through the application.
    #[cfg(feature = "opendal")]
    pub async fn get_presigned_url(
        &self,
        id: &BlobId,
        expires_in: Duration,
    ) -> StorageResult<String> {
        let path = id.to_path();

        if let Some(ref op) = self.operator {
            // Check if the operator supports presigning
            let presigned = op
                .presign_read(&path, expires_in)
                .await
                .map_err(|e| {
                    StorageError::Other(format!(
                        "Failed to generate presigned URL for blob {}: {}. Note: presigned URLs are only supported for cloud backends (S3, GCS, Azure).",
                        id, e
                    ))
                })?;

            Ok(presigned.uri().to_string())
        } else {
            Err(StorageError::Other(
                "Storage operator not initialized. Check your configuration.".to_string(),
            ))
        }
    }

    /// Generate a presigned URL (non-opendal build - stub)
    #[cfg(not(feature = "opendal"))]
    pub async fn get_presigned_url(
        &self,
        id: &BlobId,
        _expires_in: Duration,
    ) -> StorageResult<String> {
        Err(StorageError::Other(format!(
            "Presigned URLs require the 'opendal' feature to be enabled (blob: {})",
            id
        )))
    }

    /// Get the configured backend type
    pub fn backend(&self) -> &str {
        &self.config.backend
    }

    /// Check if the service is properly initialized
    #[cfg(feature = "opendal")]
    pub fn is_initialized(&self) -> bool {
        self.operator.is_some()
    }

    /// Check if the service is properly initialized (non-opendal build)
    #[cfg(not(feature = "opendal"))]
    pub fn is_initialized(&self) -> bool {
        false
    }
}

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

    #[test]
    fn test_blob_url_generation_fs() {
        let config = BlobStorageConfig::default();
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        let id = BlobId::new();
        let url = service.get_url(&id);
        assert!(url.starts_with("/storage/blobs/"));
    }

    #[test]
    fn test_blob_url_generation_s3() {
        let config = BlobStorageConfig {
            backend: "s3".to_string(),
            config: serde_json::json!({
                "bucket": "my-bucket",
                "region": "us-east-1"
            }),
        };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        let id = BlobId::new();
        let url = service.get_url(&id);
        assert!(url.starts_with("s3://my-bucket/"));
    }

    #[test]
    fn test_blob_url_generation_gcs() {
        let config = BlobStorageConfig {
            backend: "gcs".to_string(),
            config: serde_json::json!({
                "bucket": "my-gcs-bucket"
            }),
        };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        let id = BlobId::new();
        let url = service.get_url(&id);
        assert!(url.starts_with("gs://my-gcs-bucket/"));
    }

    #[test]
    fn test_blob_url_generation_azure() {
        let config = BlobStorageConfig {
            backend: "azure".to_string(),
            config: serde_json::json!({
                "container": "my-container",
                "account_name": "myaccount"
            }),
        };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        let id = BlobId::new();
        let url = service.get_url(&id);
        assert!(url.starts_with("https://myaccount.blob.core.windows.net/my-container/"));
    }

    #[test]
    fn test_backend_accessor() {
        let config = BlobStorageConfig { backend: "s3".to_string(), config: serde_json::json!({}) };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        assert_eq!(service.backend(), "s3");
    }

    #[cfg(all(feature = "opendal", feature = "storage-memory"))]
    #[tokio::test]
    async fn test_memory_backend_store_and_get() {
        let config =
            BlobStorageConfig { backend: "memory".to_string(), config: serde_json::json!({}) };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        assert!(service.is_initialized());

        let data = Bytes::from("Hello, World!");
        let id = service.store(data.clone(), "text/plain".to_string()).await.unwrap();

        let retrieved = service.get(&id).await.unwrap();
        assert_eq!(retrieved, data);

        // Test exists
        assert!(service.exists(&id).await.unwrap());

        // Test delete
        service.delete(&id).await.unwrap();
        assert!(!service.exists(&id).await.unwrap());
    }

    #[cfg(all(feature = "opendal", feature = "storage-memory"))]
    #[tokio::test]
    async fn test_memory_backend_not_found() {
        let config =
            BlobStorageConfig { backend: "memory".to_string(), config: serde_json::json!({}) };
        let db = Arc::new(Database::new());
        let service = BlobStorageService::new(config, db);

        let id = BlobId::new();
        let result = service.get(&id).await;
        assert!(result.is_err());
    }
}