102 lines
3.9 KiB
Rust
102 lines
3.9 KiB
Rust
//! Backblaze B2 file storage via S3-compatible API.
|
|
//!
|
|
//! Configuration (environment variables):
|
|
//! B2_ACCESS_KEY_ID — Application Key ID (preferred)
|
|
//! B2_SECRET_ACCESS_KEY — Application Key secret (preferred)
|
|
//! B2_KEY_ID — Legacy alias for access key ID
|
|
//! B2_APPLICATION_KEY — Legacy alias for secret key
|
|
//! B2_BUCKET_NAME — Bucket name (e.g. Nxtgauge-object)
|
|
//! B2_ENDPOINT — S3 endpoint (e.g. s3.eu-central-003.backblazeb2.com)
|
|
//! B2_REGION — Region (e.g. eu-central-003)
|
|
//! B2_USE_PATH_STYLE — true/false (default true)
|
|
|
|
use anyhow::{Context, Result};
|
|
use aws_config::Region;
|
|
use aws_credential_types::Credentials;
|
|
use aws_sdk_s3::Client;
|
|
use aws_sdk_s3::config::{Builder as S3ConfigBuilder, SharedCredentialsProvider};
|
|
use aws_sdk_s3::primitives::ByteStream;
|
|
use bytes::Bytes;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Clone)]
|
|
pub struct StorageClient {
|
|
client: Client,
|
|
bucket: String,
|
|
public_base_url: String,
|
|
}
|
|
|
|
impl StorageClient {
|
|
fn env_required(primary: &str, legacy: &str) -> String {
|
|
std::env::var(primary)
|
|
.or_else(|_| std::env::var(legacy))
|
|
.unwrap_or_else(|_| panic!("{} (or {}) must be set", primary, legacy))
|
|
}
|
|
|
|
/// Build from environment variables. Panics if required vars are missing.
|
|
pub async fn from_env() -> Self {
|
|
let key_id = Self::env_required("B2_ACCESS_KEY_ID", "B2_KEY_ID");
|
|
let app_key = Self::env_required("B2_SECRET_ACCESS_KEY", "B2_APPLICATION_KEY");
|
|
let bucket = std::env::var("B2_BUCKET_NAME").expect("B2_BUCKET_NAME must be set");
|
|
let endpoint = std::env::var("B2_ENDPOINT")
|
|
.expect("B2_ENDPOINT must be set")
|
|
.trim_start_matches("https://")
|
|
.trim_start_matches("http://")
|
|
.to_string();
|
|
let region = std::env::var("B2_REGION").expect("B2_REGION must be set");
|
|
let use_path_style = std::env::var("B2_USE_PATH_STYLE")
|
|
.ok()
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "y"))
|
|
.unwrap_or(true);
|
|
|
|
let creds = Credentials::new(key_id, app_key, None, None, "nxtgauge-storage");
|
|
let endpoint_url = format!("https://{}", endpoint);
|
|
let public_base_url = format!("https://{}/{}", endpoint, bucket);
|
|
|
|
let s3_config = S3ConfigBuilder::new()
|
|
.endpoint_url(endpoint_url)
|
|
.region(Region::new(region))
|
|
.credentials_provider(SharedCredentialsProvider::new(creds))
|
|
.force_path_style(use_path_style)
|
|
.build();
|
|
|
|
let client = Client::from_conf(s3_config);
|
|
Self { client, bucket, public_base_url }
|
|
}
|
|
|
|
/// Upload bytes to B2. Returns the public URL.
|
|
///
|
|
/// `prefix` — e.g. "portfolio", "resume", "profile"
|
|
/// `ext` — file extension without dot, e.g. "jpg", "pdf"
|
|
pub async fn upload(&self, prefix: &str, ext: &str, data: Bytes, content_type: &str) -> Result<String> {
|
|
let key = format!("{}/{}.{}", prefix, Uuid::new_v4(), ext);
|
|
|
|
self.client
|
|
.put_object()
|
|
.bucket(&self.bucket)
|
|
.key(&key)
|
|
.body(ByteStream::from(data))
|
|
.content_type(content_type)
|
|
.send()
|
|
.await
|
|
.context("B2 upload failed")?;
|
|
|
|
Ok(format!("{}/{}", self.public_base_url, key))
|
|
}
|
|
|
|
/// Delete a file by its full public URL (best-effort — logs on failure).
|
|
pub async fn delete_by_url(&self, url: &str) {
|
|
let prefix = format!("{}/", self.public_base_url);
|
|
if let Some(key) = url.strip_prefix(&prefix) {
|
|
if let Err(e) = self.client
|
|
.delete_object()
|
|
.bucket(&self.bucket)
|
|
.key(key)
|
|
.send()
|
|
.await
|
|
{
|
|
tracing::warn!("B2 delete failed for key={}: {}", key, e);
|
|
}
|
|
}
|
|
}
|
|
}
|