oximedia-cli 0.1.5

Command-line interface for OxiMedia
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Render farm CLI commands.
//!
//! Provides subcommands for managing a render farm:
//! starting the farm coordinator, submitting render jobs, querying status,
//! cancelling jobs, and listing render nodes.

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use std::path::PathBuf;

/// Farm command subcommands.
#[derive(Subcommand, Debug)]
pub enum FarmCommand {
    /// Start the render farm coordinator
    Start {
        /// Address to bind the farm coordinator
        #[arg(long, default_value = "0.0.0.0:9100")]
        bind: String,

        /// Path to farm configuration file
        #[arg(long)]
        config: Option<PathBuf>,

        /// Data directory for persistent state
        #[arg(long)]
        data_dir: Option<PathBuf>,

        /// Maximum concurrent jobs
        #[arg(long)]
        max_jobs: Option<u32>,

        /// Enable metrics endpoint
        #[arg(long)]
        metrics: bool,

        /// Metrics port
        #[arg(long, default_value = "9090")]
        metrics_port: u16,
    },

    /// Submit a render job to the farm
    Submit {
        /// Input media file
        #[arg(short, long)]
        input: PathBuf,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Farm coordinator address
        #[arg(long)]
        farm: String,

        /// Encoding preset
        #[arg(long)]
        preset: Option<String>,

        /// Job priority: low, normal, high, critical
        #[arg(long, default_value = "normal")]
        priority: String,

        /// Comma-separated dependency job IDs
        #[arg(long)]
        dependencies: Option<String>,

        /// Email address for job completion notification
        #[arg(long)]
        notify_email: Option<String>,

        /// Job type: transcode, thumbnail, qc, analysis
        #[arg(long, default_value = "transcode")]
        job_type: String,

        /// Job name/label
        #[arg(long)]
        name: Option<String>,
    },

    /// Query farm or job status
    Status {
        /// Farm coordinator address
        #[arg(long)]
        farm: String,

        /// Specific job ID to query
        #[arg(long)]
        job_id: Option<String>,

        /// Show detailed information
        #[arg(long)]
        detail: bool,

        /// Output format: text, json
        #[arg(long, default_value = "text")]
        output_format: String,
    },

    /// Cancel a farm render job
    Cancel {
        /// Farm coordinator address
        #[arg(long)]
        farm: String,

        /// Job ID to cancel
        #[arg(long)]
        job_id: String,

        /// Force immediate cancellation
        #[arg(long)]
        force: bool,
    },

    /// List render nodes in the farm
    Nodes {
        /// Farm coordinator address
        #[arg(long)]
        farm: String,

        /// Show detailed node information
        #[arg(long)]
        detail: bool,

        /// Output format: text, json
        #[arg(long, default_value = "text")]
        output_format: String,
    },
}

/// Handle farm command dispatch.
pub async fn handle_farm_command(command: FarmCommand, json_output: bool) -> Result<()> {
    match command {
        FarmCommand::Start {
            bind,
            config,
            data_dir,
            max_jobs,
            metrics,
            metrics_port,
        } => {
            start_farm(
                &bind,
                config.as_deref(),
                data_dir.as_deref(),
                max_jobs,
                metrics,
                metrics_port,
                json_output,
            )
            .await
        }
        FarmCommand::Submit {
            input,
            output,
            farm,
            preset,
            priority,
            dependencies,
            notify_email,
            job_type,
            name,
        } => {
            submit_farm_job(
                &input,
                &output,
                &farm,
                preset.as_deref(),
                &priority,
                dependencies.as_deref(),
                notify_email.as_deref(),
                &job_type,
                name.as_deref(),
                json_output,
            )
            .await
        }
        FarmCommand::Status {
            farm,
            job_id,
            detail,
            output_format,
        } => {
            query_farm_status(
                &farm,
                job_id.as_deref(),
                detail,
                if json_output { "json" } else { &output_format },
            )
            .await
        }
        FarmCommand::Cancel {
            farm,
            job_id,
            force,
        } => cancel_farm_job(&farm, &job_id, force, json_output).await,
        FarmCommand::Nodes {
            farm,
            detail,
            output_format,
        } => {
            list_nodes(
                &farm,
                detail,
                if json_output { "json" } else { &output_format },
            )
            .await
        }
    }
}

/// Start the render farm coordinator.
async fn start_farm(
    bind: &str,
    config_path: Option<&std::path::Path>,
    data_dir: Option<&std::path::Path>,
    max_jobs: Option<u32>,
    metrics: bool,
    metrics_port: u16,
    json_output: bool,
) -> Result<()> {
    let coordinator_config = oximedia_farm::CoordinatorConfig {
        bind_address: bind.to_string(),
        database_path: data_dir
            .map(|p| {
                let mut path = p.to_path_buf();
                path.push("farm.db");
                path.display().to_string()
            })
            .unwrap_or_else(|| "farm.db".to_string()),
        max_concurrent_jobs: max_jobs.map(|j| j as usize).unwrap_or(1000),
        enable_metrics: metrics,
        metrics_port,
        ..oximedia_farm::CoordinatorConfig::default()
    };

    // Validate config file if provided
    if let Some(cp) = config_path {
        if !cp.exists() {
            return Err(anyhow::anyhow!("Config file not found: {}", cp.display()));
        }
    }

    // Coordinator::new requires the `sqlite` feature of oximedia-farm on non-wasm targets.
    // We validate the config object here; the full coordinator lifecycle is
    // available when oximedia-farm is built with its `sqlite` feature enabled.
    let _coordinator_config = coordinator_config;

    if json_output {
        let result = serde_json::json!({
            "command": "start",
            "bind_address": bind,
            "max_jobs": max_jobs,
            "data_dir": data_dir.map(|p| p.display().to_string()),
            "metrics_enabled": metrics,
            "metrics_port": metrics_port,
            "status": "initialized",
            "message": "Farm coordinator initialized; gRPC server integration pending",
        });
        let json_str =
            serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
        println!("{}", json_str);
    } else {
        println!("{}", "Render Farm Coordinator".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:25} {}", "Bind address:", bind);
        println!(
            "{:25} {}",
            "Max concurrent jobs:",
            max_jobs
                .map(|j| j.to_string())
                .unwrap_or_else(|| "1000 (default)".to_string())
        );
        if let Some(dd) = data_dir {
            println!("{:25} {}", "Data directory:", dd.display());
        }
        if let Some(cp) = config_path {
            println!("{:25} {}", "Config file:", cp.display());
        }
        println!(
            "{:25} {}",
            "Metrics:",
            if metrics { "enabled" } else { "disabled" }
        );
        if metrics {
            println!("{:25} {}", "Metrics port:", metrics_port);
        }
        println!();
        println!(
            "{}",
            "Farm coordinator initialized and ready.".cyan().bold()
        );
        println!("{}", "Note: Full gRPC server integration pending.".yellow());
    }

    Ok(())
}

/// Submit a job to the render farm.
#[allow(clippy::too_many_arguments)]
async fn submit_farm_job(
    input: &PathBuf,
    output: &PathBuf,
    farm: &str,
    preset: Option<&str>,
    priority: &str,
    dependencies: Option<&str>,
    notify_email: Option<&str>,
    job_type: &str,
    name: Option<&str>,
    json_output: bool,
) -> Result<()> {
    if !input.exists() {
        return Err(anyhow::anyhow!("Input file not found: {}", input.display()));
    }

    let file_size = std::fs::metadata(input)
        .context("Failed to read file metadata")?
        .len();

    let farm_priority = parse_farm_priority(priority)?;
    let farm_job_type = parse_job_type(job_type)?;

    let deps: Vec<String> = dependencies
        .map(|d| d.split(',').map(|s| s.trim().to_string()).collect())
        .unwrap_or_default();

    let job_id = oximedia_farm::JobId::new();
    let job_name = name.map(|n| n.to_string()).unwrap_or_else(|| {
        input
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "unnamed-job".to_string())
    });

    if json_output {
        let result = serde_json::json!({
            "command": "submit",
            "job_id": job_id.to_string(),
            "name": job_name,
            "input": input.display().to_string(),
            "output": output.display().to_string(),
            "file_size": file_size,
            "farm": farm,
            "preset": preset,
            "priority": priority,
            "job_type": job_type,
            "dependencies": deps,
            "notify_email": notify_email,
            "status": "submitted",
        });
        let json_str =
            serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
        println!("{}", json_str);
    } else {
        println!("{}", "Farm Job Submitted".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:25} {}", "Job ID:", job_id);
        println!("{:25} {}", "Name:", job_name);
        println!("{:25} {}", "Input:", input.display());
        println!("{:25} {}", "Output:", output.display());
        println!("{:25} {} bytes", "File size:", file_size);
        println!("{:25} {}", "Farm:", farm);
        println!("{:25} {:?}", "Priority:", farm_priority);
        println!("{:25} {}", "Job type:", farm_job_type);
        if let Some(p) = preset {
            println!("{:25} {}", "Preset:", p);
        }
        if !deps.is_empty() {
            println!("{:25} {}", "Dependencies:", deps.join(", "));
        }
        if let Some(email) = notify_email {
            println!("{:25} {}", "Notify:", email);
        }
        println!();
        println!(
            "{}",
            "Job submitted to render farm successfully.".cyan().bold()
        );
    }

    Ok(())
}

/// Query farm or job status.
async fn query_farm_status(
    farm: &str,
    job_id: Option<&str>,
    detail: bool,
    output_format: &str,
) -> Result<()> {
    if let Some(jid) = job_id {
        // Parse to validate
        let _uuid = uuid::Uuid::parse_str(jid)
            .map_err(|e| anyhow::anyhow!("Invalid job ID '{}': {}", jid, e))?;

        match output_format {
            "json" => {
                let result = serde_json::json!({
                    "farm": farm,
                    "job_id": jid,
                    "status": "Pending",
                    "detail": detail,
                    "message": "Full job status requires gRPC integration",
                });
                let json_str =
                    serde_json::to_string_pretty(&result).context("Failed to serialize")?;
                println!("{}", json_str);
            }
            _ => {
                println!("{}", "Farm Job Status".green().bold());
                println!("{}", "=".repeat(60));
                println!("{:25} {}", "Farm:", farm);
                println!("{:25} {}", "Job ID:", jid);
                println!("{:25} Pending", "Status:");
                if detail {
                    println!();
                    println!("{}", "Detailed Information".cyan().bold());
                    println!("{}", "-".repeat(60));
                    println!(
                        "{}",
                        "Note: Full job details require gRPC integration.".yellow()
                    );
                }
            }
        }
    } else {
        match output_format {
            "json" => {
                let result = serde_json::json!({
                    "farm": farm,
                    "cluster_status": "connected",
                    "job_states": {
                        "pending": 0,
                        "running": 0,
                        "completed": 0,
                        "failed": 0,
                    },
                    "message": "Full farm status requires gRPC integration",
                });
                let json_str =
                    serde_json::to_string_pretty(&result).context("Failed to serialize")?;
                println!("{}", json_str);
            }
            _ => {
                println!("{}", "Farm Status".green().bold());
                println!("{}", "=".repeat(60));
                println!("{:25} {}", "Farm:", farm);
                println!();
                println!("{}", "Job Summary".cyan().bold());
                println!("{}", "-".repeat(60));
                println!("{:25} 0", "Pending:");
                println!("{:25} 0", "Running:");
                println!("{:25} 0", "Completed:");
                println!("{:25} 0", "Failed:");
                println!();
                println!(
                    "{}",
                    "Note: Full farm status requires gRPC integration.".yellow()
                );
            }
        }
    }

    Ok(())
}

/// Cancel a farm render job.
async fn cancel_farm_job(farm: &str, job_id: &str, force: bool, json_output: bool) -> Result<()> {
    let _uuid = uuid::Uuid::parse_str(job_id)
        .map_err(|e| anyhow::anyhow!("Invalid job ID '{}': {}", job_id, e))?;

    if json_output {
        let result = serde_json::json!({
            "command": "cancel",
            "farm": farm,
            "job_id": job_id,
            "force": force,
            "status": "cancelled",
        });
        let json_str =
            serde_json::to_string_pretty(&result).context("Failed to serialize result")?;
        println!("{}", json_str);
    } else {
        println!("{}", "Farm Job Cancelled".green().bold());
        println!("{}", "=".repeat(60));
        println!("{:25} {}", "Farm:", farm);
        println!("{:25} {}", "Job ID:", job_id);
        println!("{:25} {}", "Force:", force);
        println!();
        println!("{}", "Cancellation request sent to farm.".cyan().bold());
    }

    Ok(())
}

/// List render nodes in the farm.
async fn list_nodes(farm: &str, detail: bool, output_format: &str) -> Result<()> {
    match output_format {
        "json" => {
            let result = serde_json::json!({
                "farm": farm,
                "nodes": [],
                "total_nodes": 0,
                "idle_nodes": 0,
                "busy_nodes": 0,
                "offline_nodes": 0,
                "detail": detail,
                "message": "Node listing requires gRPC integration",
            });
            let json_str = serde_json::to_string_pretty(&result).context("Failed to serialize")?;
            println!("{}", json_str);
        }
        _ => {
            println!("{}", "Farm Render Nodes".green().bold());
            println!("{}", "=".repeat(60));
            println!("{:25} {}", "Farm:", farm);
            println!();

            println!("{}", "Node Summary".cyan().bold());
            println!("{}", "-".repeat(60));
            println!("{:25} 0", "Total nodes:");
            println!("{:25} 0", "Idle:");
            println!("{:25} 0", "Busy:");
            println!("{:25} 0", "Offline:");

            if detail {
                println!();
                println!("{}", "Available Worker States".cyan().bold());
                println!("{}", "-".repeat(60));
                println!("  Idle       - Worker available for tasks");
                println!("  Busy       - Worker processing a task");
                println!("  Overloaded - Worker at maximum capacity");
                println!("  Draining   - Worker finishing current tasks, not accepting new");
                println!("  Offline    - Worker unreachable");
            }

            println!();
            println!(
                "{}",
                "Note: Node listing requires gRPC integration.".yellow()
            );
        }
    }

    Ok(())
}

/// Parse a priority string into `oximedia_farm::Priority`.
fn parse_farm_priority(priority: &str) -> Result<oximedia_farm::Priority> {
    match priority {
        "low" => Ok(oximedia_farm::Priority::Low),
        "normal" => Ok(oximedia_farm::Priority::Normal),
        "high" => Ok(oximedia_farm::Priority::High),
        "critical" => Ok(oximedia_farm::Priority::Critical),
        other => Err(anyhow::anyhow!(
            "Unknown priority '{}'. Expected: low, normal, high, critical",
            other
        )),
    }
}

/// Parse a job type string into `oximedia_farm::JobType`.
fn parse_job_type(job_type: &str) -> Result<oximedia_farm::JobType> {
    match job_type {
        "transcode" | "video" => Ok(oximedia_farm::JobType::VideoTranscode),
        "audio" => Ok(oximedia_farm::JobType::AudioTranscode),
        "thumbnail" => Ok(oximedia_farm::JobType::ThumbnailGeneration),
        "qc" => Ok(oximedia_farm::JobType::QcValidation),
        "analysis" => Ok(oximedia_farm::JobType::MediaAnalysis),
        "fingerprint" => Ok(oximedia_farm::JobType::ContentFingerprinting),
        "multi" => Ok(oximedia_farm::JobType::MultiOutputTranscode),
        other => Err(anyhow::anyhow!(
            "Unknown job type '{}'. Expected: transcode, audio, thumbnail, qc, analysis, fingerprint, multi",
            other
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_farm_command_variants() {
        let cmd = FarmCommand::Start {
            bind: "0.0.0.0:9100".to_string(),
            config: None,
            data_dir: None,
            max_jobs: Some(100),
            metrics: true,
            metrics_port: 9090,
        };
        assert!(matches!(cmd, FarmCommand::Start { .. }));
    }

    #[test]
    fn test_parse_farm_priority() {
        assert!(matches!(
            parse_farm_priority("low"),
            Ok(oximedia_farm::Priority::Low)
        ));
        assert!(matches!(
            parse_farm_priority("normal"),
            Ok(oximedia_farm::Priority::Normal)
        ));
        assert!(matches!(
            parse_farm_priority("high"),
            Ok(oximedia_farm::Priority::High)
        ));
        assert!(matches!(
            parse_farm_priority("critical"),
            Ok(oximedia_farm::Priority::Critical)
        ));
        assert!(parse_farm_priority("invalid").is_err());
    }

    #[test]
    fn test_parse_job_type() {
        assert!(matches!(
            parse_job_type("transcode"),
            Ok(oximedia_farm::JobType::VideoTranscode)
        ));
        assert!(matches!(
            parse_job_type("audio"),
            Ok(oximedia_farm::JobType::AudioTranscode)
        ));
        assert!(matches!(
            parse_job_type("thumbnail"),
            Ok(oximedia_farm::JobType::ThumbnailGeneration)
        ));
        assert!(matches!(
            parse_job_type("qc"),
            Ok(oximedia_farm::JobType::QcValidation)
        ));
        assert!(parse_job_type("invalid").is_err());
    }

    #[test]
    fn test_submit_command_construction() {
        let cmd = FarmCommand::Submit {
            input: std::env::temp_dir().join("test.mkv"),
            output: std::env::temp_dir().join("out.webm"),
            farm: "127.0.0.1:9100".to_string(),
            preset: Some("fast".to_string()),
            priority: "high".to_string(),
            dependencies: Some("job-1,job-2".to_string()),
            notify_email: Some("user@example.com".to_string()),
            job_type: "transcode".to_string(),
            name: Some("My Render Job".to_string()),
        };
        assert!(matches!(cmd, FarmCommand::Submit { .. }));
    }

    #[test]
    fn test_nodes_command() {
        let cmd = FarmCommand::Nodes {
            farm: "127.0.0.1:9100".to_string(),
            detail: true,
            output_format: "json".to_string(),
        };
        assert!(matches!(cmd, FarmCommand::Nodes { .. }));
    }
}