acton-cli 0.25.0

CLI tool for scaffolding and managing acton-service backend services
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
use anyhow::Result;
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, Select};
use indicatif::{ProgressBar, ProgressStyle};
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::template_engine::TemplateEngine;
use crate::templates::{self, ServiceTemplate};
use crate::utils::{self, format};

#[allow(clippy::too_many_arguments)]
pub async fn execute(
    name: String,
    http: bool,
    grpc: bool,
    full: bool,
    database: Option<String>,
    cache: Option<String>,
    events: Option<String>,
    auth: Option<String>,
    observability: bool,
    resilience: bool,
    rate_limit: bool,
    openapi: bool,
    graphql: bool,
    _template: Option<String>,
    path: Option<String>,
    no_git: bool,
    interactive: bool,
    yes: bool,
    dry_run: bool,
) -> Result<()> {
    // Validate service name
    utils::validate_service_name(&name)?;

    // Determine if we should use interactive mode
    let use_interactive = interactive
        || (!yes && database.is_none() && cache.is_none() && events.is_none() && !grpc && !full);

    // Collect configuration
    let config = if use_interactive && !yes {
        collect_interactive_config(&name)?
    } else {
        ServiceConfig {
            name: name.clone(),
            http: if full { true } else { http },
            grpc: grpc || full,
            database,
            cache,
            events,
            auth,
            observability,
            resilience,
            rate_limit,
            openapi,
            graphql: graphql || full,
        }
    };

    // Determine project path
    let project_path = if let Some(p) = path {
        PathBuf::from(p).join(&name)
    } else {
        PathBuf::from(&name)
    };

    // Check if directory exists
    if project_path.exists() {
        anyhow::bail!(
            "Directory '{}' already exists\n\n\
            Suggestions:\n\
            • Use a different name: acton service new {}-v2\n\
            • Remove existing: rm -rf {}\n\
            • Update existing: cd {} && acton service add <feature>",
            project_path.display(),
            name,
            name,
            name
        );
    }

    // Show what will be generated
    if dry_run {
        show_dry_run(&config, &project_path);
        return Ok(());
    }

    // Create the project
    create_project(&config, &project_path, no_git).await?;

    // Show success message and next steps
    show_success(&config, &project_path);

    Ok(())
}

struct ServiceConfig {
    name: String,
    http: bool,
    grpc: bool,
    database: Option<String>,
    cache: Option<String>,
    events: Option<String>,
    auth: Option<String>,
    observability: bool,
    resilience: bool,
    rate_limit: bool,
    openapi: bool,
    graphql: bool,
}

fn collect_interactive_config(name: &str) -> Result<ServiceConfig> {
    println!("\n{}", "Welcome to acton-service!".bold().cyan());
    println!("Let's create your microservice.\n");

    let theme = ColorfulTheme::default();

    // Service type
    let service_types = vec![
        "HTTP REST API (simple, recommended for beginners)",
        "gRPC Service (internal services, high performance)",
        "HTTP + gRPC (dual protocol, maximum flexibility)",
    ];

    let service_type = Select::with_theme(&theme)
        .with_prompt("Service type")
        .items(&service_types)
        .default(0)
        .interact()?;

    let (http, grpc) = match service_type {
        0 => (true, false),
        1 => (false, true),
        2 => (true, true),
        _ => (true, false),
    };

    // Database
    let enable_database = Confirm::with_theme(&theme)
        .with_prompt("Enable database?")
        .default(false)
        .interact()?;

    let database = if enable_database {
        let db_types = vec!["PostgreSQL"];
        let db_idx = Select::with_theme(&theme)
            .with_prompt("Database type")
            .items(&db_types)
            .default(0)
            .interact()?;

        Some(
            match db_idx {
                0 => "postgres",
                _ => "postgres",
            }
            .to_string(),
        )
    } else {
        None
    };

    // Cache
    let enable_cache = Confirm::with_theme(&theme)
        .with_prompt("Enable caching?")
        .default(false)
        .interact()?;

    let cache = if enable_cache {
        Some("redis".to_string())
    } else {
        None
    };

    // Events
    let enable_events = Confirm::with_theme(&theme)
        .with_prompt("Enable event streaming?")
        .default(false)
        .interact()?;

    let events = if enable_events {
        Some("nats".to_string())
    } else {
        None
    };

    // Observability
    let observability = Confirm::with_theme(&theme)
        .with_prompt("Enable observability (OpenTelemetry)?")
        .default(true)
        .interact()?;

    let graphql = Confirm::with_theme(&theme)
        .with_prompt("Add GraphQL transport?")
        .default(false)
        .interact()?;

    Ok(ServiceConfig {
        name: name.to_string(),
        http,
        grpc,
        database,
        cache,
        events,
        auth: None,
        observability,
        resilience: false,
        rate_limit: false,
        openapi: false,
        graphql,
    })
}

async fn create_project(config: &ServiceConfig, project_path: &Path, no_git: bool) -> Result<()> {
    let pb = ProgressBar::new(10);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] {msg}")
            .unwrap()
            .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ "),
    );
    pb.enable_steady_tick(Duration::from_millis(100));

    // Create template data
    let template = ServiceTemplate {
        name: config.name.clone(),
        pascal_name: format::to_pascal_case(&config.name),
        snake_name: format::to_snake_case(&config.name),
        http: config.http,
        grpc: config.grpc,
        database: config.database.clone(),
        cache: config.cache.clone(),
        events: config.events.clone(),
        auth: config.auth.clone(),
        observability: config.observability,
        resilience: config.resilience,
        rate_limit: config.rate_limit,
        openapi: config.openapi,
        audit: false,
        graphql: config.graphql,
    };

    // Initialize template engine
    pb.set_message("Initializing template engine...");
    let engine = TemplateEngine::new()?;

    // Prepare template context
    let mut context = template.to_json();
    let context_obj = context.as_object_mut().unwrap();
    context_obj.insert(
        "acton_service_path".to_string(),
        serde_json::Value::String(template.acton_service_path().unwrap_or_default()),
    );
    context_obj.insert(
        "features".to_string(),
        serde_json::Value::Array(
            template
                .features()
                .iter()
                .map(|f| serde_json::Value::String(f.clone()))
                .collect(),
        ),
    );

    pb.set_message("Creating project structure...");
    utils::create_dir_all(project_path)?;

    // Create src directory
    let src_dir = project_path.join("src");
    utils::create_dir_all(&src_dir)?;

    pb.set_message("Generating Cargo.toml...");
    utils::write_file(
        &project_path.join("Cargo.toml"),
        &engine.render("service/Cargo.toml.jinja", &context)?,
    )?;

    pb.set_message("Generating configuration...");
    utils::write_file(
        &project_path.join("config.toml"),
        &templates::config::generate(&template),
    )?;

    pb.set_message("Generating main.rs...");
    utils::write_file(
        &src_dir.join("main.rs"),
        &engine.render("service/main.rs.jinja", &context)?,
    )?;

    // Generate handlers if HTTP enabled
    if config.http {
        pb.set_message("Generating handlers...");
        utils::write_file(
            &src_dir.join("handlers.rs"),
            &engine.render("handlers/mod.rs.jinja", &context)?,
        )?;
    }

    // Generate build.rs if gRPC enabled
    if config.grpc {
        pb.set_message("Generating build.rs...");
        utils::write_file(
            &project_path.join("build.rs"),
            &engine.render("service/build.rs.jinja", &context)?,
        )?;

        // Create proto directory
        let proto_dir = project_path.join("proto");
        utils::create_dir_all(&proto_dir)?;
    }

    // Generate graphql module if GraphQL enabled
    if config.graphql {
        pb.set_message("Generating GraphQL schema...");
        utils::write_file(
            &src_dir.join("graphql.rs"),
            &templates::graphql::generate_module(),
        )?;
    }

    pb.set_message("Generating .gitignore...");
    utils::write_file(
        &project_path.join(".gitignore"),
        &engine.render("service/.gitignore.jinja", &context)?,
    )?;

    pb.set_message("Generating README.md...");
    utils::write_file(
        &project_path.join("README.md"),
        &engine.render("service/README.md.jinja", &context)?,
    )?;

    pb.set_message("Generating Dockerfile...");
    utils::write_file(
        &project_path.join("Dockerfile"),
        &templates::deployment::generate_dockerfile(&config.name),
    )?;

    utils::write_file(
        &project_path.join(".dockerignore"),
        &templates::deployment::generate_dockerignore(),
    )?;

    // Initialize git
    if !no_git && utils::git::is_available() {
        pb.set_message("Initializing git repository...");
        utils::git::init(project_path)?;
    }

    // Format generated code
    if utils::cargo::is_available() {
        pb.set_message("Formatting code...");
        let _ = utils::cargo::fmt(project_path); // Ignore errors
    }

    pb.finish_and_clear();

    Ok(())
}

fn show_dry_run(config: &ServiceConfig, project_path: &Path) {
    println!("\n{}", "Dry run - would generate:".bold());
    println!(
        "\n{}",
        format!("Project: {}", project_path.display()).cyan()
    );

    println!("\n{}:", "Files".bold());
    println!("  • Cargo.toml");
    println!("  • config.toml");
    println!("  • src/main.rs");
    if config.http {
        println!("  • src/handlers.rs");
    }
    if config.grpc {
        println!("  • build.rs");
        println!("  • proto/ (directory)");
    }
    if config.graphql {
        println!("  • src/graphql.rs");
    }
    println!("  • .gitignore");
    println!("  • README.md");
    println!("  • Dockerfile");
    println!("  • .dockerignore");

    println!("\n{}:", "Features".bold());
    if config.http {
        println!("  ✓ HTTP REST API");
    }
    if config.grpc {
        println!("  ✓ gRPC Service");
    }
    if let Some(database) = config.database.as_ref() {
        println!("  ✓ Database ({database})");
    }
    if let Some(cache) = config.cache.as_ref() {
        println!("  ✓ Cache ({cache})");
    }
    if let Some(events) = config.events.as_ref() {
        println!("  ✓ Events ({events})");
    }
    if config.observability {
        println!("  ✓ Observability");
    }
    if config.resilience {
        println!("  ✓ Resilience patterns");
    }
    if config.rate_limit {
        println!("  ✓ Rate limiting");
    }
    if config.graphql {
        println!("  ✓ GraphQL transport");
    }
}

fn show_success(config: &ServiceConfig, project_path: &Path) {
    println!(
        "\n{} {}",
        "".green().bold(),
        format!("Created {} service", config.name).bold()
    );

    if config.http || config.grpc || config.database.is_some() || config.graphql {
        println!("\n{}:", "Features enabled".bold());
        if config.http {
            println!("  {} HTTP REST API with versioning", "".green());
        }
        if config.grpc {
            println!("  {} gRPC service", "".green());
        }
        if config.graphql {
            println!(
                "  {} GraphQL transport at /api/v1/graphql",
                "".green()
            );
        }
        if let Some(db) = &config.database {
            println!("  {} {} database with connection pooling", "".green(), db);
        }
        if let Some(cache) = &config.cache {
            println!("  {} {} caching", "".green(), cache);
        }
        if let Some(events) = &config.events {
            println!("  {} {} event streaming", "".green(), events);
        }
        if config.observability {
            println!("  {} OpenTelemetry observability", "".green());
        }
    }

    // Add gRPC port configuration info
    if config.grpc {
        println!("\n{}:", "Port Configuration".bold());
        if config.http {
            println!(
                "  {} HTTP and gRPC share port 8080 (single-port mode)",
                "".cyan()
            );
            println!("  {} To use separate ports, edit config.toml:", "".cyan());
            println!("    Set use_separate_port = true (HTTP: 8080, gRPC: 9090)");
        } else {
            println!("  {} gRPC listening on port 9090", "".cyan());
        }
    }

    println!("\n{}:", "Next steps".bold());
    println!("  cd {}", project_path.display());

    if config.http {
        println!("  acton service add endpoint GET /users");
    }

    println!("  cargo run");

    println!(
        "\n{} Learn more: https://docs.acton-service.dev/getting-started",
        "📚".cyan()
    );
}