File size: 10,593 Bytes
2156b71
a8673cc
2156b71
 
 
 
5beeefc
 
2156b71
 
 
 
 
 
 
 
 
 
5beeefc
2156b71
 
 
 
 
 
 
 
5beeefc
2156b71
a8673cc
 
2156b71
5beeefc
2156b71
 
 
5beeefc
2156b71
 
5beeefc
2156b71
5beeefc
2156b71
 
 
 
 
 
 
 
 
5beeefc
a8673cc
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
5beeefc
 
a8673cc
5beeefc
 
 
 
 
 
 
 
a8673cc
5beeefc
 
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beeefc
a8673cc
 
 
 
 
5beeefc
a8673cc
5beeefc
 
a8673cc
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
5beeefc
 
 
 
a8673cc
5beeefc
a8673cc
 
5beeefc
 
 
a8673cc
5beeefc
 
 
51913a2
5beeefc
 
 
 
a8673cc
5beeefc
 
a8673cc
5beeefc
a8673cc
5beeefc
 
 
 
 
 
 
 
 
 
a8673cc
5beeefc
 
a8673cc
 
5beeefc
 
 
 
 
 
 
 
a8673cc
5beeefc
 
 
 
 
 
 
 
a8673cc
5beeefc
 
 
 
 
 
 
 
a8673cc
5beeefc
 
a8673cc
 
5beeefc
 
 
 
 
 
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beeefc
 
a8673cc
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
a8673cc
 
 
 
 
 
 
 
 
2156b71
 
 
 
 
5beeefc
2156b71
 
 
 
 
 
 
 
 
5beeefc
2156b71
 
 
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
use std::sync::Arc;
use tokio::sync::{mpsc, Semaphore};
use sysinfo::{System, SystemExt};
use crate::queue::WeightedScheduler;
use fred::interfaces::KeysInterface;
use crate::transcoder;
use crate::models::{TaskStatus, VideoTask};
use crate::storage::StorageManager;

pub struct WorkerPool {
    scheduler: WeightedScheduler,
    semaphore: Arc<Semaphore>,
}

impl WorkerPool {
    pub fn new(scheduler: WeightedScheduler) -> Self {
        let max_procs = calculate_max_processes();
        println!("Initializing Worker Pool with {} slots", max_procs);

        Self {
            scheduler,
            semaphore: Arc::new(Semaphore::new(max_procs)),
        }
    }

    pub async fn start(&self) {
        println!("Worker Pool started. Polling for tasks...");

        loop {
            // Wait for a slot to be available before even pulling a task.
            // This prevents filling RAM with tasks that are just waiting.
            let permit = self.semaphore.clone().acquire_owned().await.unwrap();

            match self.scheduler.next_task().await {
                Ok(task) => {
                    let scheduler = self.scheduler.clone();

                    tokio::spawn(async move {
                        let _permit = permit; // Hold permit until done
                        process_video_job(scheduler, task).await;
                    });
                }
                Err(_) => {
                    // No tasks or wait timeout
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                }
            }
        }
    }
}

/// Process one queued video job end-to-end:
/// download β†’ package/transcode β†’ cover β†’ Redis status.
async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
    let task_id = task.task_id.clone();
    let s3_key = task.video_id.clone();
    let tier = task.tier.clone();
    let target_format = task.target_format.clone();

    // 1) cover_source from payload β€” missing/empty β‡’ "auto" (backward compatible)
    let cover_source = {
        let raw = task.cover_source.trim().to_lowercase();
        if raw.is_empty() {
            "auto".to_string()
        } else {
            raw
        }
    };
    let cover_s3_key = task.cover_s3_key.clone();
    let is_custom = cover_source == "custom";

    let storage = match StorageManager::new().await {
        Ok(s) => Arc::new(s),
        Err(e) => {
            eprintln!("Failed to initialize StorageManager for task {}: {}", task_id, e);
            fail_task(&scheduler, &task_id, &cover_source, format!("Storage initialization failed: {}", e)).await;
            return;
        }
    };

    let temp_file = match tempfile::NamedTempFile::new() {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Failed to create temp file for task {}: {}", task_id, e);
            fail_task(&scheduler, &task_id, &cover_source, format!("Temp file failed: {}", e)).await;
            return;
        }
    };
    let temp_path = temp_file.path().to_str().unwrap().to_string();

    // 2) Stream the source to disk, reporting progress so the UI starts moving
    // immediately instead of sitting at 0% until the encode begins.
    transcoder::set_job_progress(&scheduler, &task_id, 2).await;
    write_status(
        &scheduler,
        &task_id,
        TaskStatus {
            progress: 2,
            status: "processing".to_string(),
            message: "Downloading source video...".to_string(),
            cover_url: None,
            cover_source: Some(cover_source.clone()),
            variants: None,
        },
    )
    .await;

    let (tx, mut rx) = mpsc::unbounded_channel::<(u64, u64)>();
    let progress_sched = scheduler.clone();
    let progress_task = task_id.clone();
    let progress_pump = tokio::spawn(async move {
        let mut last_pct = 0u32;
        while let Some((done, total)) = rx.recv().await {
            let pct = if total > 0 {
                (2.0 + (done as f64 / total as f64) * 12.0) as u32
            } else {
                8
            };
            let pct = pct.min(14);
            if pct != last_pct {
                last_pct = pct;
                transcoder::set_job_progress(&progress_sched, &progress_task, pct).await;
            }
        }
    });

    println!("Downloading {} from S3 to {}", s3_key, temp_path);
    if let Err(e) = storage
        .download_file(&s3_key, temp_file.path(), Some(tx))
        .await
    {
        progress_pump.await.ok();
        eprintln!("Download failed for task {}: {}", task_id, e);
        fail_task(&scheduler, &task_id, &cover_source, format!("Download failed: {}", e)).await;
        return;
    }
    progress_pump.await.ok();
    transcoder::set_job_progress(&scheduler, &task_id, 15).await;

    // Transcode only β€” cover handling is separate (skip legacy thumbnail/{task_id}.jpg path)
    for attempt in 1..=3 {
        if attempt > 1 {
            println!("Retrying {} (Attempt {})", task_id, attempt);
        }

        let res = transcoder::process(
            task_id.clone(),
            &temp_path,
            &target_format,
            tier.clone(),
            true, // always skip legacy concurrent thumb; we resolve cover below
            Some(scheduler.clone()),
            task_id.clone(),
            storage.clone(),
        )
        .await;

        match res {
            Ok((output_dir, variants)) => {
                println!(
                    "Completed transcode for task {} (variants={:?}, cover_source={})",
                    task_id, variants, cover_source
                );
                transcoder::set_job_progress(&scheduler, &task_id, 100).await;

                // 3) Resolve cover_url
                let cover_url = if is_custom {
                    // Custom: no generation β€” pass through already-uploaded S3 key
                    let key = cover_s3_key.clone().unwrap_or_else(|| {
                        format!("thumbnails/{}.jpg", task_id)
                    });
                    println!("Using custom cover (skip generation): {}", key);
                    key
                } else {
                    // Auto: grab a frame from an encoded segment, fall back to the source
                    match transcoder::generate_and_upload_auto_cover(
                        &temp_path,
                        &output_dir,
                        &task_id,
                        storage.as_ref(),
                    )
                    .await
                    {
                        Ok(key) => key,
                        Err(e) => {
                            eprintln!(
                                "Auto cover generation failed for {}: {} β€” marking error",
                                task_id, e
                            );
                            transcoder::clear_job_progress(&scheduler, &task_id).await;
                            fail_task(
                                &scheduler,
                                &task_id,
                                &cover_source,
                                format!("Cover generation failed: {}", e),
                            )
                            .await;
                            return;
                        }
                    }
                };

                // 4) Completion payload for Celery /status consumers
                write_status(
                    &scheduler,
                    &task_id,
                    TaskStatus {
                        progress: 100,
                        status: "completed".to_string(),
                        message: "Video live and distributed globally!".to_string(),
                        cover_url: Some(cover_url),
                        cover_source: Some(cover_source.clone()),
                        variants: Some(variants),
                    },
                )
                .await;
                break;
            }
            Err(e) if attempt == 3 => {
                eprintln!("Failed Task {} after 3 attempts: {}", task_id, e);
                transcoder::clear_job_progress(&scheduler, &task_id).await;
                fail_task(
                    &scheduler,
                    &task_id,
                    &cover_source,
                    format!("Final error: {}", e),
                )
                .await;
            }
            Err(_) => {
                transcoder::clear_job_progress(&scheduler, &task_id).await;
                tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
            }
        }
    }

    // Explicitly drop the temp file so disk space is returned before the slot frees.
    drop(temp_file);
}

async fn fail_task(
    scheduler: &WeightedScheduler,
    task_id: &str,
    cover_source: &str,
    message: String,
) {
    write_status(
        scheduler,
        task_id,
        TaskStatus {
            progress: 0,
            status: "error".to_string(),
            message,
            cover_url: None,
            cover_source: Some(cover_source.to_string()),
            variants: None,
        },
    )
    .await;
}

async fn write_status(scheduler: &WeightedScheduler, task_id: &str, status: TaskStatus) {
    let status_json = serde_json::to_string(&status).unwrap_or_else(|_| {
        r#"{"progress":0,"status":"error","message":"serialize failed"}"#.to_string()
    });
    let _: () = scheduler
        .client()
        .set(
            format!("task:status:{}", task_id),
            status_json,
            Some(fred::types::Expiration::EX(86400)),
            None,
            false,
        )
        .await
        .unwrap_or_default();
}

fn calculate_max_processes() -> usize {
    // Explicit override wins (useful when the host reports shared/throttled CPUs).
    if let Ok(raw) = std::env::var("MAX_CONCURRENT_JOBS") {
        if let Ok(v) = raw.parse::<usize>() {
            if v > 0 {
                return v;
            }
        }
    }

    let mut sys = System::new_all();
    sys.refresh_all();

    let cpus = sys.cpus().len();
    let total_ram_gb = sys.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);

    // Formula: min(cpus/2, ram/1.5, disk_limit)
    let cpu_limit = (cpus as f64 / 2.0).floor() as usize;
    let ram_limit = (total_ram_gb / 1.5).floor() as usize;
    let disk_limit = std::env::var("DISK_IO_LIMIT")
        .unwrap_or_else(|_| "4".to_string())
        .parse::<usize>()
        .unwrap_or(4);

    let calculated = cpu_limit.min(ram_limit).min(disk_limit);

    // Ensure at least 1 worker
    calculated.max(1)
}