README / src /storage.rs
Monteeq CI
πŸš€ Deploy from GitHub @ 4eb79b5e42a5d81d582a63b79ba4afd35d266c0b
a8673cc
Raw History Blame Contribute Delete
8 kB
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use anyhow::{Result, anyhow};
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::task::JoinSet;
/// How many segment PUTs may be in flight at once.
/// Sequential uploads were the bulk of the post-encode tail; 12 keeps the
/// connection pool busy without hammering S3 from a small Space.
fn upload_concurrency() -> usize {
std::env::var("UPLOAD_CONCURRENCY")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|v| *v > 0)
.unwrap_or(12)
}
pub struct StorageManager {
client: Client,
bucket: String,
}
use aws_config::Region;
impl StorageManager {
pub async fn new() -> Result<Self> {
let region_name = std::env::var("S3_REGION").ok()
.or_else(|| std::env::var("AWS_S3_REGION_NAME").ok())
.or_else(|| std::env::var("AWS_REGION").ok());
let region_provider = RegionProviderChain::first_try(region_name.map(Region::new))
.or_default_provider()
.or_else(Region::new("eu-west-1"));
let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
.region(region_provider)
.load()
.await;
let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&config);
// Custom endpoint only when non-empty (empty S3_ENDPOINT β†’ native AWS)
if let Ok(endpoint) = std::env::var("S3_ENDPOINT") {
let endpoint = endpoint.trim().to_string();
if !endpoint.is_empty() {
println!("Rust: Using custom S3 endpoint: {}", endpoint);
s3_config_builder = s3_config_builder.endpoint_url(endpoint.clone());
if !endpoint.contains("amazonaws.com") {
println!("Rust: Enabling force_path_style for custom endpoint");
s3_config_builder = s3_config_builder.force_path_style(true);
}
}
}
// Build S3 config with optional Transfer Acceleration
let use_accelerate = std::env::var("AWS_S3_USE_ACCELERATE")
.map(|v| v.to_lowercase() == "true")
.unwrap_or(false);
if use_accelerate {
println!("Rust: Enabling S3 Transfer Acceleration");
s3_config_builder = s3_config_builder.accelerate(true);
}
let s3_config = s3_config_builder.build();
let client = Client::from_conf(s3_config);
let bucket = std::env::var("AWS_STORAGE_BUCKET_NAME")
.or_else(|_| std::env::var("S3_BUCKET_NAME"))
.map_err(|_| anyhow!("Storage bucket name not set (AWS_STORAGE_BUCKET_NAME or S3_BUCKET_NAME)"))?;
Ok(Self { client, bucket })
}
/// Upload every file in `local_dir` to `s3_prefix`, several at a time.
#[allow(dead_code)]
pub async fn upload_hls_dir(&self, local_dir: &str, s3_prefix: &str) -> Result<()> {
let concurrency = upload_concurrency();
let mut entries = fs::read_dir(local_dir).await?;
let mut join: JoinSet<Result<()>> = JoinSet::new();
let mut first_err: Option<anyhow::Error> = None;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if !path.is_file() {
continue;
}
let filename = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n.to_string(),
None => continue,
};
while join.len() >= concurrency {
if let Some(res) = join.join_next().await {
record(&mut first_err, res);
}
}
let client = self.client.clone();
let bucket = self.bucket.clone();
let key = format!("{}/{}", s3_prefix, filename);
join.spawn(async move { put_file(client, bucket, path, key).await });
}
while let Some(res) = join.join_next().await {
record(&mut first_err, res);
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
pub async fn upload_file(&self, local_path: &Path, key: &str) -> Result<()> {
put_file(
self.client.clone(),
self.bucket.clone(),
local_path.to_path_buf(),
key.to_string(),
)
.await
}
/// Stream an S3 object to disk instead of buffering the whole file in RAM.
/// `progress` receives `(bytes_written, total_bytes)`; total is 0 when the
/// server did not report a Content-Length.
pub async fn download_file(
&self,
key: &str,
local_path: &Path,
progress: Option<tokio::sync::mpsc::UnboundedSender<(u64, u64)>>,
) -> Result<()> {
println!("Attempting to download from S3: bucket={}, key={}", self.bucket, key);
let res = self
.client
.get_object()
.bucket(&self.bucket)
.key(key)
.send()
.await
.map_err(|e| {
let service_err = e.into_service_error();
anyhow!(
"S3 Download Error [Bucket: {}, Key: {}]: {}",
self.bucket,
key,
service_err
)
})?;
let total = res.content_length().unwrap_or(0) as u64;
let mut reader = res.body.into_async_read();
let mut file = fs::File::create(local_path).await?;
let mut buf = vec![0u8; 256 * 1024];
let mut written: u64 = 0;
let mut last_report = 0u64;
loop {
let n = reader.read(&mut buf).await?;
if n == 0 {
break;
}
file.write_all(&buf[..n]).await?;
written += n as u64;
if let Some(tx) = progress.as_ref() {
// Report at most ~every 4 MiB to keep Redis writes cheap.
if written - last_report >= 4 * 1024 * 1024 {
last_report = written;
let _ = tx.send((written, total));
}
}
}
file.flush().await?;
if let Some(tx) = progress.as_ref() {
let _ = tx.send((written, total.max(written)));
}
Ok(())
}
}
fn record(first_err: &mut Option<anyhow::Error>, res: Result<Result<()>, tokio::task::JoinError>) {
match res {
Ok(Ok(())) => {}
Ok(Err(e)) => {
if first_err.is_none() {
*first_err = Some(e);
}
}
Err(e) => {
if first_err.is_none() {
*first_err = Some(anyhow!("upload task failed: {}", e));
}
}
}
}
async fn put_file(client: Client, bucket: String, path: PathBuf, key: String) -> Result<()> {
let mime_type = match path.extension().and_then(|s| s.to_str()) {
Some("m3u8") => "application/x-mpegURL",
Some("ts") => "video/MP2T",
Some("m4s") => "video/iso.segment",
Some("mp4") => "video/mp4",
Some("jpg") | Some("jpeg") => "image/jpeg",
_ => "application/octet-stream",
};
// Streamed from disk β€” no full-file read into memory.
let body = ByteStream::from_path(&path)
.await
.map_err(|e| anyhow!("Failed to open {} for upload: {}", path.display(), e))?;
client
.put_object()
.bucket(bucket)
.key(&key)
.body(body)
.content_type(mime_type)
.send()
.await
.map_err(|e| anyhow!("Upload failed for {}: {}", key, e))?;
Ok(())
}
/// Cheap clone so callers can share one manager across spawned tasks.
impl Clone for StorageManager {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
bucket: self.bucket.clone(),
}
}
}