audb-cli 0.1.11

Command-line interface for AuDB database application framework
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
//! Deployment management module
//!
//! This module implements the `au deploy` command and its subcommands for
//! building and deploying AuDB applications.
//!
//! ## Commands
//!
//! - `au deploy` / `au deploy start` - Build and deploy
//! - `au deploy status` - Check deployment status
//! - `au deploy stop` - Stop deployment
//! - `au deploy logs` - View logs
//! - `au deploy restart` - Restart deployment

pub mod config;
pub mod docker;
pub mod launchd;
pub mod state;
pub mod templates;

pub use config::{DeploymentConfig, DeploymentTarget};
pub use state::DeploymentState;

use anyhow::{Context, Result};
use audb::model::Project;
use audb::parser::GoldParser;
use console::{Term, style};
use std::collections::HashMap;
use std::path::Path;
use walkdir::WalkDir;

/// Deploy options from CLI flags
#[derive(Debug)]
pub struct DeployOptions {
    pub target: Option<String>,
    pub port: Option<u16>,
    pub env: Vec<String>,
    pub volume: Vec<String>,
    pub force_rebuild: bool,
    pub compose: bool,
}

/// Deploy subcommands
#[derive(Debug)]
pub enum DeployCommand {
    /// Start/deploy the application
    Start,
    /// Check deployment status
    Status,
    /// Stop the deployment
    Stop,
    /// View deployment logs
    Logs,
    /// Restart the deployment
    Restart,
}

/// Run the deploy command
pub async fn run(command: DeployCommand, options: DeployOptions) -> Result<()> {
    match command {
        DeployCommand::Start => start_deployment(options).await,
        DeployCommand::Status => show_status().await,
        DeployCommand::Stop => stop_deployment().await,
        DeployCommand::Logs => show_logs(false, None).await,
        DeployCommand::Restart => restart_deployment().await,
    }
}

/// Start deployment
async fn start_deployment(options: DeployOptions) -> Result<()> {
    let term = Term::stdout();

    term.write_line("")?;
    term.write_line(&format!(
        "{} {}",
        style("Starting deployment").bold().cyan(),
        style("(this may take a few minutes)").dim()
    ))?;
    term.write_line("")?;

    let project_root = std::env::current_dir().context("Failed to get current directory")?;

    // Step 1: Validate gold files
    term.write_line(&format!("{} Validating gold files...", style("1/5").dim()))?;
    let gold_dir = project_root.join("gold");
    if gold_dir.exists() {
        if let Err(e) = crate::commands::check::run("./gold") {
            term.write_line(&format!("{} Validation failed: {}", style("").red(), e))?;
            term.write_line("")?;
            return Err(e.context("Gold file validation failed. Fix errors before deploying."));
        }
        term.write_line(&format!("  {} Gold files validated", style("").green()))?;
    } else {
        term.write_line(&format!(
            "  {} No gold directory found, skipping validation",
            style("").yellow()
        ))?;
    }

    // Step 2: Generate code
    term.write_line(&format!("{} Generating code...", style("2/5").dim()))?;
    if gold_dir.exists() {
        if let Err(e) = crate::commands::generate::run("./gold", "./src/generated") {
            term.write_line(&format!(
                "{} Code generation failed: {}",
                style("").red(),
                e
            ))?;
            term.write_line("")?;
            return Err(e.context("Code generation failed. Fix errors before deploying."));
        }
        term.write_line(&format!("  {} Code generated", style("").green()))?;
    } else {
        term.write_line(&format!(
            "  {} No gold directory found, skipping generation",
            style("").yellow()
        ))?;
    }

    // Step 3: Load or create deployment config
    term.write_line(&format!(
        "{} Loading deployment configuration...",
        style("3/5").dim()
    ))?;
    let mut config = load_deployment_config(&project_root)?;

    // Apply CLI flag overrides
    apply_cli_overrides(&mut config, &options)?;

    // Step 4: Deploy based on target
    term.write_line(&format!(
        "{} Deploying to {}...",
        style("4/5").dim(),
        match &config.target {
            DeploymentTarget::Docker => "Docker",
            DeploymentTarget::Systemd => "Systemd",
            DeploymentTarget::Daemon => "Daemon",
            DeploymentTarget::Local => "Local",
        }
    ))?;

    let _state = match &config.target {
        DeploymentTarget::Docker => {
            if options.compose {
                deploy_with_compose(&project_root, &config).await?
            } else {
                docker::deploy(&project_root, &config, options.force_rebuild).await?
            }
        }
        DeploymentTarget::Systemd => {
            term.write_line(&format!(
                "{} Systemd deployment not yet implemented",
                style("").yellow()
            ))?;
            return Ok(());
        }
        DeploymentTarget::Daemon => {
            // On macOS, use launchd; on Linux, use systemd; otherwise use daemon mode
            #[cfg(target_os = "macos")]
            {
                launchd::deploy(&project_root, &config, options.force_rebuild).await?
            }
            #[cfg(not(target_os = "macos"))]
            {
                term.write_line(&format!(
                    "{} Daemon deployment not yet implemented for this platform",
                    style("").yellow()
                ))?;
                return Ok(());
            }
        }
        DeploymentTarget::Local => deploy_local(&project_root, &config).await?,
    };

    term.write_line(&format!("{} Deployment complete!", style("5/5").dim()))?;
    term.write_line("")?;
    term.write_line(&format!(
        "{} Deployment successful!",
        style("").green().bold()
    ))?;
    term.write_line("")?;

    Ok(())
}

/// Load deployment configuration from gold files
fn load_deployment_config(project_root: &Path) -> Result<DeploymentConfig> {
    // Find and parse all gold files
    let gold_dir = project_root.join("gold");

    if !gold_dir.exists() {
        // No gold files - use defaults
        return Ok(default_deployment_config());
    }

    // Discover all .au files
    let mut gold_files = Vec::new();
    for entry in WalkDir::new(&gold_dir)
        .follow_links(true)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("au") {
            match GoldParser::parse_file(path) {
                Ok(file) => gold_files.push(file),
                Err(e) => {
                    eprintln!("Warning: Failed to parse {}: {}", path.display(), e);
                }
            }
        }
    }

    if gold_files.is_empty() {
        // No valid gold files - use defaults
        return Ok(default_deployment_config());
    }

    // Parse gold files into Project model
    let project = match Project::from_gold_files(gold_files) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Warning: Failed to build project model: {}", e);
            eprintln!("Using default deployment configuration");
            return Ok(default_deployment_config());
        }
    };

    // Extract deployment config from project
    if let Some(deployment) = project.deployment {
        // Convert from audb::model::DeploymentConfig to deploy::config::DeploymentConfig
        let target = match deployment.target.as_str() {
            "docker" => DeploymentTarget::Docker,
            "systemd" => DeploymentTarget::Systemd,
            "daemon" => DeploymentTarget::Daemon,
            "local" => DeploymentTarget::Local,
            _ => {
                eprintln!(
                    "Warning: Unknown deployment target '{}', using docker",
                    deployment.target
                );
                DeploymentTarget::Docker
            }
        };

        let healthcheck =
            deployment
                .healthcheck
                .map(|hc| crate::commands::deploy::config::HealthCheckConfig {
                    endpoint: hc.endpoint,
                    interval: hc.interval,
                    timeout: hc.timeout,
                    retries: hc.retries,
                });

        Ok(DeploymentConfig {
            target,
            persist: deployment.persist,
            port: deployment.port,
            environment: deployment.environment,
            volumes: deployment.volumes,
            healthcheck,
            restart: deployment.restart,
        })
    } else {
        // No deployment config in gold files - use defaults
        Ok(default_deployment_config())
    }
}

/// Default deployment configuration when none is specified
fn default_deployment_config() -> DeploymentConfig {
    DeploymentConfig {
        target: DeploymentTarget::Docker,
        persist: true,
        port: Some(8080),
        environment: HashMap::new(),
        volumes: HashMap::new(),
        healthcheck: Some(crate::commands::deploy::config::HealthCheckConfig {
            endpoint: "/health".to_string(),
            interval: "5s".to_string(),
            timeout: "60s".to_string(),
            retries: 3,
        }),
        restart: "unless-stopped".to_string(),
    }
}

/// Show deployment status
async fn show_status() -> Result<()> {
    let project_root = std::env::current_dir().context("Failed to get current directory")?;

    let state = DeploymentState::load(&project_root).context("No deployment state found")?;

    match state.target {
        DeploymentTarget::Docker => docker::status(&project_root).await,
        DeploymentTarget::Daemon => {
            #[cfg(target_os = "macos")]
            {
                launchd::status(&project_root).await
            }
            #[cfg(not(target_os = "macos"))]
            {
                Err(anyhow::anyhow!(
                    "Daemon deployment not supported on this platform"
                ))
            }
        }
        DeploymentTarget::Systemd => Err(anyhow::anyhow!("Systemd deployment not yet implemented")),
        DeploymentTarget::Local => {
            println!("Local deployment - check process manually");
            Ok(())
        }
    }
}

/// Stop deployment
async fn stop_deployment() -> Result<()> {
    let project_root = std::env::current_dir().context("Failed to get current directory")?;

    let state = DeploymentState::load(&project_root).context("No deployment state found")?;

    match state.target {
        DeploymentTarget::Docker => docker::stop(&project_root).await,
        DeploymentTarget::Daemon => {
            #[cfg(target_os = "macos")]
            {
                launchd::stop(&project_root).await
            }
            #[cfg(not(target_os = "macos"))]
            {
                Err(anyhow::anyhow!(
                    "Daemon deployment not supported on this platform"
                ))
            }
        }
        DeploymentTarget::Systemd => Err(anyhow::anyhow!("Systemd deployment not yet implemented")),
        DeploymentTarget::Local => Err(anyhow::anyhow!("Local deployment - stop process manually")),
    }
}

/// Show deployment logs
async fn show_logs(follow: bool, tail: Option<String>) -> Result<()> {
    let project_root = std::env::current_dir().context("Failed to get current directory")?;

    let state = DeploymentState::load(&project_root).context("No deployment state found")?;

    match state.target {
        DeploymentTarget::Docker => docker::logs(&project_root, follow, tail).await,
        DeploymentTarget::Daemon => {
            #[cfg(target_os = "macos")]
            {
                launchd::logs(&project_root, follow, tail).await
            }
            #[cfg(not(target_os = "macos"))]
            {
                Err(anyhow::anyhow!(
                    "Daemon deployment not supported on this platform"
                ))
            }
        }
        DeploymentTarget::Systemd => Err(anyhow::anyhow!("Systemd deployment not yet implemented")),
        DeploymentTarget::Local => Err(anyhow::anyhow!("Local deployment - check logs manually")),
    }
}

/// Restart deployment
async fn restart_deployment() -> Result<()> {
    let project_root = std::env::current_dir().context("Failed to get current directory")?;

    let state = DeploymentState::load(&project_root).context("No deployment state found")?;

    match state.target {
        DeploymentTarget::Docker => docker::restart(&project_root).await,
        DeploymentTarget::Daemon => {
            #[cfg(target_os = "macos")]
            {
                launchd::restart(&project_root).await
            }
            #[cfg(not(target_os = "macos"))]
            {
                Err(anyhow::anyhow!(
                    "Daemon deployment not supported on this platform"
                ))
            }
        }
        DeploymentTarget::Systemd => Err(anyhow::anyhow!("Systemd deployment not yet implemented")),
        DeploymentTarget::Local => Err(anyhow::anyhow!(
            "Local deployment - restart process manually"
        )),
    }
}

/// Apply CLI flag overrides to deployment config
fn apply_cli_overrides(config: &mut DeploymentConfig, options: &DeployOptions) -> Result<()> {
    // Override target if specified
    if let Some(ref target_str) = options.target {
        config.target = match target_str.as_str() {
            "docker" => DeploymentTarget::Docker,
            "systemd" => DeploymentTarget::Systemd,
            "daemon" => DeploymentTarget::Daemon,
            "local" => DeploymentTarget::Local,
            _ => return Err(anyhow::anyhow!("Unknown deployment target: {}", target_str)),
        };
    }

    // Override port if specified
    if let Some(port) = options.port {
        config.port = Some(port);
    }

    // Add environment variables from CLI
    for env_pair in &options.env {
        if let Some((key, value)) = env_pair.split_once('=') {
            config
                .environment
                .insert(key.to_string(), value.to_string());
        } else {
            return Err(anyhow::anyhow!(
                "Invalid environment variable format: '{}'. Use KEY=VALUE",
                env_pair
            ));
        }
    }

    // Add volumes from CLI
    for volume_pair in &options.volume {
        if let Some((host, container)) = volume_pair.split_once(':') {
            config
                .volumes
                .insert(host.to_string(), container.to_string());
        } else {
            return Err(anyhow::anyhow!(
                "Invalid volume format: '{}'. Use HOST:CONTAINER",
                volume_pair
            ));
        }
    }

    Ok(())
}

/// Deploy using docker-compose
async fn deploy_with_compose(
    project_root: &Path,
    config: &DeploymentConfig,
) -> Result<DeploymentState> {
    use console::{Term, style};
    use std::process::Command;

    let term = Term::stdout();

    // Generate docker-compose.yml
    term.write_line("Generating docker-compose.yml...")?;
    let compose_content = templates::generate_docker_compose(
        project_root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("audb-app"),
        config,
    );

    let compose_path = project_root.join("docker-compose.yml");
    std::fs::write(&compose_path, compose_content).context("Failed to write docker-compose.yml")?;

    term.write_line(&format!(
        "  {} docker-compose.yml created",
        style("").green()
    ))?;

    // Run docker-compose up
    term.write_line("Starting with docker-compose...")?;
    let status = Command::new("docker-compose")
        .arg("up")
        .arg("-d")
        .arg("--build")
        .current_dir(project_root)
        .status()
        .context("Failed to run docker-compose. Is it installed?")?;

    if !status.success() {
        return Err(anyhow::anyhow!("docker-compose up failed"));
    }

    term.write_line(&format!("  {} Services started", style("").green()))?;

    // Create deployment state
    let project_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("audb-app");

    let state = DeploymentState {
        target: config.target,
        deployed_at: chrono::Utc::now(),
        service_label: format!("{}_app_1", project_name),
        project_name: project_name.to_string(),
    };

    state.save(project_root)?;

    Ok(state)
}

/// Deploy locally (just run the binary)
async fn deploy_local(project_root: &Path, config: &DeploymentConfig) -> Result<DeploymentState> {
    use console::{Term, style};
    use std::process::Command;

    let term = Term::stdout();

    // Build the project
    term.write_line("Building project...")?;
    let status = Command::new("cargo")
        .arg("build")
        .arg("--release")
        .current_dir(project_root)
        .status()
        .context("Failed to run cargo build")?;

    if !status.success() {
        return Err(anyhow::anyhow!("cargo build failed"));
    }

    term.write_line(&format!("  {} Build successful", style("").green()))?;

    // Get the binary name from Cargo.toml
    let binary_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("app");

    // Binary is in workspace target dir, not project target dir
    let workspace_root = project_root
        .parent()
        .and_then(|p| p.parent())
        .unwrap_or(project_root);

    let binary_path = workspace_root
        .join("target")
        .join("release")
        .join(binary_name);

    if !binary_path.exists() {
        return Err(anyhow::anyhow!(
            "Binary not found at {}",
            binary_path.display()
        ));
    }

    // Start the server
    term.write_line("")?;
    term.write_line(&format!(
        "{} Starting server on port {}...",
        style("").green().bold(),
        config.port.unwrap_or(8080)
    ))?;
    term.write_line("")?;

    let mut child = Command::new(&binary_path)
        .current_dir(project_root)
        .spawn()
        .context("Failed to start server")?;

    // Wait a moment to see if it crashes immediately
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

    match child.try_wait() {
        Ok(Some(status)) => {
            return Err(anyhow::anyhow!(
                "Server exited immediately with status: {}",
                status
            ));
        }
        Ok(None) => {
            // Still running - success!
            term.write_line(&format!(
                "{} Server started successfully (PID: {})",
                style("").green(),
                child.id()
            ))?;
            term.write_line("")?;
            term.write_line(&format!(
                "Access your API at: http://localhost:{}",
                config.port.unwrap_or(8080)
            ))?;
            term.write_line("")?;
            term.write_line(&format!(
                "{}",
                style("Press Ctrl+C to stop the server").dim()
            ))?;
            term.write_line("")?;

            // Wait for the process
            let status = child.wait().context("Failed to wait for server process")?;

            if !status.success() {
                return Err(anyhow::anyhow!("Server exited with status: {}", status));
            }
        }
        Err(e) => {
            return Err(anyhow::anyhow!("Failed to check server status: {}", e));
        }
    }

    // Create deployment state
    let project_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("audb-app");

    let state = DeploymentState {
        target: config.target,
        deployed_at: chrono::Utc::now(),
        service_label: format!("local-{}", project_name),
        project_name: project_name.to_string(),
    };

    state.save(project_root)?;

    Ok(state)
}