File size: 7,999 Bytes
2156b71
 
 
 
a8673cc
2156b71
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
2156b71
 
 
 
 
 
 
 
a8673cc
2156b71
a8673cc
a010e8e
2156b71
a010e8e
 
 
 
 
 
 
 
a468b11
2156b71
 
 
 
 
 
a8673cc
2156b71
 
 
 
a8673cc
2156b71
 
a8673cc
a010e8e
 
 
a8673cc
2156b71
 
 
a8673cc
 
2156b71
a8673cc
2156b71
a8673cc
 
2156b71
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
2156b71
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
 
 
a8673cc
 
 
 
 
 
 
2156b71
 
a8673cc
 
 
 
 
 
 
 
 
2156b71
a8673cc
 
2156b71
 
 
 
 
 
 
a8673cc
 
 
 
 
 
2156b71
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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(),
        }
    }
}