pub mod local;
pub mod s3;
pub use local::LocalStorage;
pub use s3::{S3Config, S3Storage};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
static GLOBAL_STORAGE: OnceLock<Arc<Storage>> = OnceLock::new();
#[async_trait]
pub trait StorageDriver: Send + Sync {
async fn put(&self, path: &str, contents: &[u8]) -> Result<(), String>;
async fn get(&self, path: &str) -> Result<Vec<u8>, String>;
async fn exists(&self, path: &str) -> bool;
async fn delete(&self, path: &str) -> Result<(), String>;
fn url(&self, path: &str) -> String;
fn temporary_url(&self, path: &str, ttl: Duration) -> Result<String, String>;
}
pub struct Storage {
disks: HashMap<String, Arc<dyn StorageDriver>>,
default_disk: String,
}
impl Storage {
pub fn new(default_disk: &str) -> Self {
Self {
disks: HashMap::new(),
default_disk: default_disk.to_string(),
}
}
pub fn set_global(storage: Arc<Storage>) {
let _ = GLOBAL_STORAGE.set(storage);
}
pub fn global() -> Option<Arc<Storage>> {
GLOBAL_STORAGE.get().cloned()
}
pub fn add_disk(&mut self, name: &str, driver: Arc<dyn StorageDriver>) {
self.disks.insert(name.to_string(), driver);
}
pub fn disk(&self, name: &str) -> Arc<dyn StorageDriver> {
self.disks
.get(name)
.cloned()
.unwrap_or_else(|| panic!("Storage disk '{}' tidak ditemukan. Pastikan disk sudah dikonfigurasi.", name))
}
pub fn default(&self) -> Arc<dyn StorageDriver> {
self.disk(&self.default_disk)
}
pub fn disk_named(name: &str) -> Arc<dyn StorageDriver> {
let storage = GLOBAL_STORAGE
.get()
.expect("Global Storage belum diinisialisasi. Pastikan Application::build() telah dijalankan.");
storage.disk(name)
}
pub async fn put_file(path: &str, contents: &[u8]) -> Result<(), String> {
let storage = GLOBAL_STORAGE
.get()
.expect("Global Storage belum diinisialisasi.");
storage.default().put(path, contents).await
}
pub async fn get_file(path: &str) -> Result<Vec<u8>, String> {
let storage = GLOBAL_STORAGE
.get()
.expect("Global Storage belum diinisialisasi.");
storage.default().get(path).await
}
pub fn file_url(path: &str) -> String {
let storage = GLOBAL_STORAGE
.get()
.expect("Global Storage belum diinisialisasi.");
storage.default().url(path)
}
pub async fn put(&self, path: &str, contents: &[u8]) -> Result<(), String> {
self.default().put(path, contents).await
}
pub async fn get(&self, path: &str) -> Result<Vec<u8>, String> {
self.default().get(path).await
}
pub async fn exists(&self, path: &str) -> bool {
self.default().exists(path).await
}
pub async fn delete(&self, path: &str) -> Result<(), String> {
self.default().delete(path).await
}
pub fn url(&self, path: &str) -> String {
self.default().url(path)
}
pub fn temporary_url(&self, path: &str, ttl: Duration) -> Result<String, String> {
self.default().temporary_url(path, ttl)
}
}