supabase-lib-rs 0.5.3

A comprehensive, production-ready Rust client library for Supabase with full cross-platform support (native + WASM)
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Session storage backends
//!
//! This module provides different storage backends for session persistence:
//! - MemoryStorage: In-memory storage for testing and temporary sessions
//! - LocalStorage: Browser localStorage backend for WASM
//! - FileSystemStorage: Filesystem backend for native applications
//! - EncryptedStorage: Wrapper for encrypted storage

// Type alias for complex storage type
#[cfg(feature = "session-management")]
type SessionEntry = (SessionData, Option<DateTime<Utc>>);

#[cfg(feature = "session-management")]
use crate::error::{Error, Result};
#[cfg(feature = "session-management")]
use crate::session::{SessionData, SessionStorage};
#[cfg(feature = "session-management")]
use chrono::{DateTime, Utc};
#[cfg(feature = "session-management")]
use std::collections::HashMap;
#[cfg(feature = "session-management")]
use std::sync::{Arc, RwLock};

/// In-memory session storage (not persistent across restarts)
#[cfg(feature = "session-management")]
#[derive(Debug)]
pub struct MemoryStorage {
    sessions: Arc<RwLock<HashMap<String, SessionEntry>>>,
}

#[cfg(feature = "session-management")]
impl MemoryStorage {
    pub fn new() -> Self {
        Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Clean up expired sessions
    pub fn cleanup_expired(&self) {
        let now = Utc::now();
        let mut sessions = self.sessions.write().unwrap();
        sessions.retain(|_, (_, expires_at)| {
            match expires_at {
                Some(expiry) => *expiry > now,
                None => true, // Keep sessions without expiry
            }
        });
    }
}

#[cfg(feature = "session-management")]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl SessionStorage for MemoryStorage {
    async fn store_session(
        &self,
        key: &str,
        session: &SessionData,
        expires_at: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let mut sessions = self
            .sessions
            .write()
            .map_err(|_| Error::storage("Failed to acquire write lock for memory storage"))?;
        sessions.insert(key.to_string(), (session.clone(), expires_at));
        Ok(())
    }

    async fn get_session(&self, key: &str) -> Result<Option<SessionData>> {
        let sessions = self
            .sessions
            .read()
            .map_err(|_| Error::storage("Failed to acquire read lock for memory storage"))?;

        if let Some((session_data, expires_at)) = sessions.get(key) {
            // Check if session is expired
            if let Some(expiry) = expires_at {
                if *expiry <= Utc::now() {
                    return Ok(None);
                }
            }
            Ok(Some(session_data.clone()))
        } else {
            Ok(None)
        }
    }

    async fn remove_session(&self, key: &str) -> Result<()> {
        let mut sessions = self
            .sessions
            .write()
            .map_err(|_| Error::storage("Failed to acquire write lock for memory storage"))?;
        sessions.remove(key);
        Ok(())
    }

    async fn clear_all_sessions(&self) -> Result<()> {
        let mut sessions = self
            .sessions
            .write()
            .map_err(|_| Error::storage("Failed to acquire write lock for memory storage"))?;
        sessions.clear();
        Ok(())
    }

    async fn list_session_keys(&self) -> Result<Vec<String>> {
        let sessions = self
            .sessions
            .read()
            .map_err(|_| Error::storage("Failed to acquire read lock for memory storage"))?;
        Ok(sessions.keys().cloned().collect())
    }

    fn is_available(&self) -> bool {
        true
    }
}

#[cfg(feature = "session-management")]
impl Default for MemoryStorage {
    fn default() -> Self {
        Self::new()
    }
}

/// Browser localStorage backend for WASM
#[cfg(all(
    feature = "session-management",
    target_arch = "wasm32",
    feature = "wasm"
))]
#[derive(Debug)]
pub struct LocalStorage {
    key_prefix: String,
}

// WASM is single-threaded, so Send and Sync are safe to implement
#[cfg(all(
    feature = "session-management",
    target_arch = "wasm32",
    feature = "wasm"
))]
unsafe impl Send for LocalStorage {}
#[cfg(all(
    feature = "session-management",
    target_arch = "wasm32",
    feature = "wasm"
))]
unsafe impl Sync for LocalStorage {}

#[cfg(all(
    feature = "session-management",
    target_arch = "wasm32",
    feature = "wasm"
))]
impl LocalStorage {
    pub fn new(key_prefix: Option<String>) -> Result<Self> {
        // Check if localStorage is available
        if !Self::is_storage_available() {
            return Err(Error::storage(
                "localStorage is not available in this environment",
            ));
        }

        Ok(Self {
            key_prefix: key_prefix.unwrap_or_else(|| "supabase_".to_string()),
        })
    }

    fn is_storage_available() -> bool {
        web_sys::window()
            .and_then(|w| w.local_storage().ok().flatten())
            .is_some()
    }

    fn get_storage() -> Result<web_sys::Storage> {
        web_sys::window()
            .ok_or_else(|| Error::storage("No window object available"))?
            .local_storage()
            .map_err(|_| Error::storage("Failed to access localStorage"))?
            .ok_or_else(|| Error::storage("localStorage is not available"))
    }

    fn make_key(&self, key: &str) -> String {
        format!("{}{}", self.key_prefix, key)
    }
}

#[cfg(all(
    feature = "session-management",
    target_arch = "wasm32",
    feature = "wasm"
))]
#[async_trait::async_trait(?Send)]
impl SessionStorage for LocalStorage {
    async fn store_session(
        &self,
        key: &str,
        session: &SessionData,
        _expires_at: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let storage = Self::get_storage()?;
        let storage_key = self.make_key(key);
        let serialized = serde_json::to_string(session)
            .map_err(|e| Error::storage(format!("Failed to serialize session: {}", e)))?;

        storage
            .set_item(&storage_key, &serialized)
            .map_err(|_| Error::storage("Failed to store session in localStorage"))?;

        Ok(())
    }

    async fn get_session(&self, key: &str) -> Result<Option<SessionData>> {
        let storage = Self::get_storage()?;
        let storage_key = self.make_key(key);

        match storage.get_item(&storage_key) {
            Ok(Some(serialized)) => {
                let session_data: SessionData = serde_json::from_str(&serialized)
                    .map_err(|e| Error::storage(format!("Failed to deserialize session: {}", e)))?;

                // Check if session is expired
                if session_data.session.expires_at <= Utc::now() {
                    // Remove expired session
                    let _ = self.remove_session(key).await;
                    Ok(None)
                } else {
                    Ok(Some(session_data))
                }
            }
            Ok(None) => Ok(None),
            Err(_) => Err(Error::storage("Failed to read from localStorage")),
        }
    }

    async fn remove_session(&self, key: &str) -> Result<()> {
        let storage = Self::get_storage()?;
        let storage_key = self.make_key(key);
        storage
            .remove_item(&storage_key)
            .map_err(|_| Error::storage("Failed to remove session from localStorage"))?;
        Ok(())
    }

    async fn clear_all_sessions(&self) -> Result<()> {
        let storage = Self::get_storage()?;
        let keys_to_remove: Vec<String> = (0..storage.length().unwrap_or(0))
            .filter_map(|i| storage.key(i).ok().flatten())
            .filter(|key| key.starts_with(&self.key_prefix))
            .collect();

        for key in keys_to_remove {
            storage
                .remove_item(&key)
                .map_err(|_| Error::storage("Failed to clear session from localStorage"))?;
        }

        Ok(())
    }

    async fn list_session_keys(&self) -> Result<Vec<String>> {
        let storage = Self::get_storage()?;
        let keys: Vec<String> = (0..storage.length().unwrap_or(0))
            .filter_map(|i| storage.key(i).ok().flatten())
            .filter(|key| key.starts_with(&self.key_prefix))
            .map(|key| {
                key.strip_prefix(&self.key_prefix)
                    .unwrap_or(&key)
                    .to_string()
            })
            .collect();

        Ok(keys)
    }

    fn is_available(&self) -> bool {
        Self::is_storage_available()
    }
}

/// Filesystem-based storage for native applications
#[cfg(all(feature = "session-management", not(target_arch = "wasm32")))]
#[derive(Debug)]
pub struct FileSystemStorage {
    base_dir: std::path::PathBuf,
}

#[cfg(all(feature = "session-management", not(target_arch = "wasm32")))]
impl FileSystemStorage {
    pub fn new(base_dir: Option<std::path::PathBuf>) -> Result<Self> {
        let base_dir = match base_dir {
            Some(dir) => dir,
            None => {
                // Use OS-appropriate data directory
                dirs::data_local_dir()
                    .ok_or_else(|| Error::storage("Could not determine data directory"))?
                    .join("supabase-sessions")
            }
        };

        // Create directory if it doesn't exist
        std::fs::create_dir_all(&base_dir)
            .map_err(|e| Error::storage(format!("Failed to create session directory: {}", e)))?;

        Ok(Self { base_dir })
    }

    fn get_session_path(&self, key: &str) -> std::path::PathBuf {
        self.base_dir.join(format!("{}.json", key))
    }
}

#[cfg(all(feature = "session-management", not(target_arch = "wasm32")))]
#[async_trait::async_trait]
impl SessionStorage for FileSystemStorage {
    async fn store_session(
        &self,
        key: &str,
        session: &SessionData,
        _expires_at: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let path = self.get_session_path(key);
        let serialized = serde_json::to_string_pretty(session)
            .map_err(|e| Error::storage(format!("Failed to serialize session: {}", e)))?;

        tokio::fs::write(&path, serialized)
            .await
            .map_err(|e| Error::storage(format!("Failed to write session file: {}", e)))?;

        Ok(())
    }

    async fn get_session(&self, key: &str) -> Result<Option<SessionData>> {
        let path = self.get_session_path(key);

        match tokio::fs::read_to_string(&path).await {
            Ok(serialized) => {
                let session_data: SessionData = serde_json::from_str(&serialized)
                    .map_err(|e| Error::storage(format!("Failed to deserialize session: {}", e)))?;

                // Check if session is expired
                if session_data.session.expires_at <= Utc::now() {
                    // Remove expired session
                    let _ = self.remove_session(key).await;
                    Ok(None)
                } else {
                    Ok(Some(session_data))
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(Error::storage(format!(
                "Failed to read session file: {}",
                e
            ))),
        }
    }

    async fn remove_session(&self, key: &str) -> Result<()> {
        let path = self.get_session_path(key);
        match tokio::fs::remove_file(&path).await {
            Ok(_) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), // Already removed
            Err(e) => Err(Error::storage(format!(
                "Failed to remove session file: {}",
                e
            ))),
        }
    }

    async fn clear_all_sessions(&self) -> Result<()> {
        let mut dir_entries = tokio::fs::read_dir(&self.base_dir)
            .await
            .map_err(|e| Error::storage(format!("Failed to read session directory: {}", e)))?;

        while let Some(entry) = dir_entries
            .next_entry()
            .await
            .map_err(|e| Error::storage(format!("Failed to read directory entry: {}", e)))?
        {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("json") {
                match tokio::fs::remove_file(&path).await {
                    Ok(_) => {}
                    Err(e) => {
                        tracing::warn!("Failed to remove session file {:?}: {}", path, e);
                    }
                }
            }
        }

        Ok(())
    }

    async fn list_session_keys(&self) -> Result<Vec<String>> {
        let mut dir_entries = tokio::fs::read_dir(&self.base_dir)
            .await
            .map_err(|e| Error::storage(format!("Failed to read session directory: {}", e)))?;

        let mut keys = Vec::new();

        while let Some(entry) = dir_entries
            .next_entry()
            .await
            .map_err(|e| Error::storage(format!("Failed to read directory entry: {}", e)))?
        {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("json") {
                if let Some(file_stem) = path.file_stem().and_then(|s| s.to_str()) {
                    keys.push(file_stem.to_string());
                }
            }
        }

        Ok(keys)
    }

    fn is_available(&self) -> bool {
        self.base_dir.exists() && self.base_dir.is_dir()
    }
}

/// Encrypted storage wrapper
#[cfg(all(feature = "session-management", feature = "session-encryption"))]
pub struct EncryptedStorage {
    inner: Arc<dyn SessionStorage>,
    encryptor: Arc<crate::session::encryption::SessionEncryptor>,
}

#[cfg(all(feature = "session-management", feature = "session-encryption"))]
impl std::fmt::Debug for EncryptedStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EncryptedStorage")
            .field("inner", &"Arc<dyn SessionStorage>")
            .field("encryptor", &"Arc<SessionEncryptor>")
            .finish()
    }
}

#[cfg(all(feature = "session-management", feature = "session-encryption"))]
impl EncryptedStorage {
    pub fn new(inner: Arc<dyn SessionStorage>, encryption_key: [u8; 32]) -> Result<Self> {
        let encryptor = Arc::new(crate::session::encryption::SessionEncryptor::new(
            encryption_key,
        )?);
        Ok(Self { inner, encryptor })
    }
}

#[cfg(all(feature = "session-management", feature = "session-encryption"))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl SessionStorage for EncryptedStorage {
    async fn store_session(
        &self,
        key: &str,
        session: &SessionData,
        expires_at: Option<DateTime<Utc>>,
    ) -> Result<()> {
        let encrypted_session = self.encryptor.encrypt_session(session)?;
        self.inner
            .store_session(key, &encrypted_session, expires_at)
            .await
    }

    async fn get_session(&self, key: &str) -> Result<Option<SessionData>> {
        if let Some(encrypted_session) = self.inner.get_session(key).await? {
            let decrypted_session = self.encryptor.decrypt_session(&encrypted_session)?;
            Ok(Some(decrypted_session))
        } else {
            Ok(None)
        }
    }

    async fn remove_session(&self, key: &str) -> Result<()> {
        self.inner.remove_session(key).await
    }

    async fn clear_all_sessions(&self) -> Result<()> {
        self.inner.clear_all_sessions().await
    }

    async fn list_session_keys(&self) -> Result<Vec<String>> {
        self.inner.list_session_keys().await
    }

    fn is_available(&self) -> bool {
        self.inner.is_available()
    }
}

/// Enum-based storage backend for dyn compatibility
#[cfg(feature = "session-management")]
#[derive(Debug)]
pub enum StorageBackend {
    Memory(MemoryStorage),
    #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
    LocalStorage(LocalStorage),
    #[cfg(not(target_arch = "wasm32"))]
    FileSystem(FileSystemStorage),
    #[cfg(feature = "session-encryption")]
    Encrypted(EncryptedStorage),
}

#[cfg(feature = "session-management")]
impl StorageBackend {
    /// Store a session with optional expiry
    pub async fn store_session(
        &self,
        key: &str,
        session: &SessionData,
        expires_at: Option<DateTime<Utc>>,
    ) -> Result<()> {
        match self {
            StorageBackend::Memory(storage) => {
                storage.store_session(key, session, expires_at).await
            }
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => {
                storage.store_session(key, session, expires_at).await
            }
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => {
                storage.store_session(key, session, expires_at).await
            }
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => {
                storage.store_session(key, session, expires_at).await
            }
        }
    }

    /// Retrieve a session by key
    pub async fn get_session(&self, key: &str) -> Result<Option<SessionData>> {
        match self {
            StorageBackend::Memory(storage) => storage.get_session(key).await,
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => storage.get_session(key).await,
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => storage.get_session(key).await,
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => storage.get_session(key).await,
        }
    }

    /// Remove a session by key
    pub async fn remove_session(&self, key: &str) -> Result<()> {
        match self {
            StorageBackend::Memory(storage) => storage.remove_session(key).await,
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => storage.remove_session(key).await,
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => storage.remove_session(key).await,
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => storage.remove_session(key).await,
        }
    }

    /// Clear all sessions
    pub async fn clear_all_sessions(&self) -> Result<()> {
        match self {
            StorageBackend::Memory(storage) => storage.clear_all_sessions().await,
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => storage.clear_all_sessions().await,
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => storage.clear_all_sessions().await,
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => storage.clear_all_sessions().await,
        }
    }

    /// List all session keys
    pub async fn list_session_keys(&self) -> Result<Vec<String>> {
        match self {
            StorageBackend::Memory(storage) => storage.list_session_keys().await,
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => storage.list_session_keys().await,
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => storage.list_session_keys().await,
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => storage.list_session_keys().await,
        }
    }

    /// Check if storage is available
    pub fn is_available(&self) -> bool {
        match self {
            StorageBackend::Memory(storage) => storage.is_available(),
            #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
            StorageBackend::LocalStorage(storage) => storage.is_available(),
            #[cfg(not(target_arch = "wasm32"))]
            StorageBackend::FileSystem(storage) => storage.is_available(),
            #[cfg(feature = "session-encryption")]
            StorageBackend::Encrypted(storage) => storage.is_available(),
        }
    }
}

/// Factory function to create the appropriate storage backend
#[cfg(feature = "session-management")]
pub fn create_default_storage() -> Result<Arc<StorageBackend>> {
    #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
    {
        if let Ok(storage) = LocalStorage::new(None) {
            Ok(Arc::new(StorageBackend::LocalStorage(storage)))
        } else {
            // Fallback to memory storage
            Ok(Arc::new(StorageBackend::Memory(MemoryStorage::new())))
        }
    }

    #[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
    {
        // Without wasm feature, only memory storage is available
        Ok(Arc::new(StorageBackend::Memory(MemoryStorage::new())))
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        if let Ok(storage) = FileSystemStorage::new(None) {
            Ok(Arc::new(StorageBackend::FileSystem(storage)))
        } else {
            // Fallback to memory storage
            Ok(Arc::new(StorageBackend::Memory(MemoryStorage::new())))
        }
    }
}