forgex 0.0.1-alpha

CLI and runtime for the Forge full-stack framework
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
use anyhow::Result;
use clap::{Parser, Subcommand};
use console::style;
use std::fs;
use std::path::Path;

/// Add a new component.
#[derive(Parser)]
pub struct AddCommand {
    #[command(subcommand)]
    pub component: AddType,
}

/// Component types that can be added.
#[derive(Subcommand)]
pub enum AddType {
    /// Add a new model.
    Model {
        /// Model name (PascalCase).
        name: String,
    },
    /// Add a new query function.
    Query {
        /// Function name (snake_case).
        name: String,
    },
    /// Add a new mutation function.
    Mutation {
        /// Function name (snake_case).
        name: String,
    },
    /// Add a new action function.
    Action {
        /// Function name (snake_case).
        name: String,
    },
    /// Add a new background job.
    Job {
        /// Job name (snake_case).
        name: String,
    },
    /// Add a new cron task.
    Cron {
        /// Cron name (snake_case).
        name: String,
    },
    /// Add a new workflow.
    Workflow {
        /// Workflow name (snake_case).
        name: String,
    },
}

impl AddCommand {
    /// Execute the add command.
    pub async fn execute(self) -> Result<()> {
        match self.component {
            AddType::Model { name } => add_model(&name),
            AddType::Query { name } => add_function(&name, FunctionType::Query),
            AddType::Mutation { name } => add_function(&name, FunctionType::Mutation),
            AddType::Action { name } => add_function(&name, FunctionType::Action),
            AddType::Job { name } => add_job(&name),
            AddType::Cron { name } => add_cron(&name),
            AddType::Workflow { name } => add_workflow(&name),
        }
    }
}

/// Function types.
enum FunctionType {
    Query,
    Mutation,
    Action,
}

/// Add a new model.
fn add_model(name: &str) -> Result<()> {
    let pascal_name = to_pascal_case(name);
    let snake_name = to_snake_case(&pascal_name);

    let schema_dir = Path::new("src/schema");
    if !schema_dir.exists() {
        anyhow::bail!("Not in a FORGE project (src/schema not found)");
    }

    let file_path = schema_dir.join(format!("{}.rs", snake_name));
    if file_path.exists() {
        anyhow::bail!("Model already exists: {}", file_path.display());
    }

    let content = format!(
        r#"use forgex::prelude::*;

/// {pascal_name} model.
#[forgex::model]
pub struct {pascal_name} {{
    #[id]
    pub id: Uuid,

    // Add your fields here
    // pub name: String,

    #[default = "now()"]
    pub created_at: Timestamp,

    #[updated_at]
    pub updated_at: Timestamp,
}}
"#
    );

    fs::write(&file_path, content)?;
    update_schema_mod(&snake_name, &pascal_name)?;

    println!(
        "{} Created model: {}",
        style("").green(),
        style(&file_path.display()).cyan()
    );
    println!("   Don't forget to add your fields!");

    Ok(())
}

/// Add a new function.
fn add_function(name: &str, fn_type: FunctionType) -> Result<()> {
    let snake_name = to_snake_case(name);

    let functions_dir = Path::new("src/functions");
    if !functions_dir.exists() {
        anyhow::bail!("Not in a FORGE project (src/functions not found)");
    }

    let file_path = functions_dir.join(format!("{}.rs", snake_name));
    if file_path.exists() {
        anyhow::bail!("Function file already exists: {}", file_path.display());
    }

    let content = match fn_type {
        FunctionType::Query => format!(
            r#"//! Query: {snake_name}
//!
//! Queries are read-only database operations. They support:
//! - Real-time subscriptions (auto-refresh on data changes)
//! - Caching and deduplication
//! - Pagination helpers

use forgex::prelude::*;

/// {snake_name} query.
#[forgex::query]
pub async fn {snake_name}(ctx: &QueryContext) -> Result<Vec<()>> {{
    // Example: Fetch data from database
    // let items = sqlx::query_as!(
    //     Item,
    //     "SELECT * FROM items WHERE deleted_at IS NULL ORDER BY created_at DESC"
    // )
    // .fetch_all(ctx.db())
    // .await?;

    Ok(vec![])
}}
"#
        ),
        FunctionType::Mutation => format!(
            r#"//! Mutation: {snake_name}
//!
//! Mutations are write operations that modify data. They:
//! - Automatically invalidate affected subscriptions
//! - Support optimistic updates on the frontend
//! - Are wrapped in database transactions

use forgex::prelude::*;

/// {snake_name} mutation.
#[forgex::mutation]
pub async fn {snake_name}(ctx: &MutationContext) -> Result<()> {{
    // Example: Insert or update data
    // let id = Uuid::new_v4();
    // sqlx::query!(
    //     "INSERT INTO items (id, name) VALUES ($1, $2)",
    //     id,
    //     input.name
    // )
    // .execute(ctx.db())
    // .await?;

    Ok(())
}}
"#
        ),
        FunctionType::Action => format!(
            r#"//! Action: {snake_name}
//!
//! Actions are for external API calls and side effects. They:
//! - Are NOT wrapped in database transactions
//! - Should be idempotent when possible
//! - Can call external services (Stripe, SendGrid, etc.)
//!
//! Common use cases:
//! - Payment processing
//! - Email/SMS sending
//! - Third-party API calls
//! - File uploads to cloud storage

use forgex::prelude::*;

/// Result from {snake_name} action.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {pascal_name}Result {{
    pub success: bool,
    // Add your result fields here
}}

/// {snake_name} action.
#[forgex::action]
pub async fn {snake_name}(ctx: &ActionContext) -> Result<{pascal_name}Result> {{
    tracing::info!("Executing {snake_name} action");

    // Example: Call external API
    // let response = ctx.http_client()
    //     .post("https://api.example.com/endpoint")
    //     .json(&payload)
    //     .send()
    //     .await?;

    Ok({pascal_name}Result {{ success: true }})
}}
"#,
            pascal_name = to_pascal_case(&snake_name)
        ),
    };

    fs::write(&file_path, content)?;
    update_functions_mod(&snake_name)?;

    let description = match fn_type {
        FunctionType::Query => "query",
        FunctionType::Mutation => "mutation",
        FunctionType::Action => "action",
    };

    println!(
        "{} Created {}: {}",
        style("").green(),
        description,
        style(&file_path.display()).cyan()
    );

    Ok(())
}

/// Add a new job.
fn add_job(name: &str) -> Result<()> {
    let snake_name = to_snake_case(name);
    let pascal_name = to_pascal_case(name);

    let functions_dir = Path::new("src/functions");
    if !functions_dir.exists() {
        anyhow::bail!("Not in a FORGE project (src/functions not found)");
    }

    let file_path = functions_dir.join(format!("{}_job.rs", snake_name));
    if file_path.exists() {
        anyhow::bail!("Job file already exists: {}", file_path.display());
    }

    let content = format!(
        r#"//! Background job: {snake_name}
//!
//! Jobs are used for async processing with automatic retry logic.
//! They are ideal for tasks that:
//! - May take a long time to complete
//! - May fail and need retry
//! - Should run in the background
//!
//! ## Dispatching this job
//!
//! ```rust
//! ctx.dispatch_job({snake_name}, {pascal_name}Input {{
//!     // your arguments
//! }}).await?;
//! ```

use forgex::prelude::*;

/// Input for the {snake_name} job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {pascal_name}Input {{
    // Add your input fields here
    // pub user_id: Uuid,
    // pub data: String,
}}

/// Output from the {snake_name} job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {pascal_name}Output {{
    // Add your output fields here
    pub success: bool,
}}

/// {pascal_name} background job.
///
/// Configuration options:
/// - `timeout`: Maximum execution time (default: "5m")
/// - `max_attempts`: Number of retry attempts (default: 3)
/// - `backoff`: Retry backoff strategy: "exponential" or "linear" (default: "exponential")
#[forgex::job]
#[timeout = "5m"]
#[retry(max_attempts = 3, backoff = "exponential")]
pub async fn {snake_name}(ctx: &JobContext, _input: {pascal_name}Input) -> Result<{pascal_name}Output> {{
    tracing::info!(job_id = %ctx.job_id, "Starting {snake_name} job");

    // Add your job logic here
    // Example: Process data, call external APIs, etc.

    // Report progress (visible in dashboard)
    let _ = ctx.progress(50, "Processing...");

    // Simulate work
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;

    let _ = ctx.progress(100, "Complete");
    tracing::info!(job_id = %ctx.job_id, "Completed {snake_name} job");

    Ok({pascal_name}Output {{ success: true }})
}}
"#
    );

    fs::write(&file_path, content)?;
    update_functions_mod(&format!("{}_job", snake_name))?;

    println!(
        "{} Created job: {}",
        style("").green(),
        style(&file_path.display()).cyan()
    );
    println!("   Job features: timeout, retry, progress tracking");

    Ok(())
}

/// Add a new cron task.
fn add_cron(name: &str) -> Result<()> {
    let snake_name = to_snake_case(name);

    let functions_dir = Path::new("src/functions");
    if !functions_dir.exists() {
        anyhow::bail!("Not in a FORGE project (src/functions not found)");
    }

    let file_path = functions_dir.join(format!("{}_cron.rs", snake_name));
    if file_path.exists() {
        anyhow::bail!("Cron file already exists: {}", file_path.display());
    }

    let content = format!(
        r#"//! Scheduled task: {snake_name}
//!
//! Cron tasks run on a schedule defined by a cron expression.
//!
//! ## Common cron schedules
//!
//! - `* * * * *`     - Every minute
//! - `0 * * * *`     - Every hour
//! - `0 0 * * *`     - Daily at midnight
//! - `0 9 * * *`     - Daily at 9 AM
//! - `0 0 * * 0`     - Weekly on Sunday
//! - `0 0 1 * *`     - Monthly on the 1st
//! - `0 0 * * 1-5`   - Weekdays at midnight
//!
//! Format: `second minute hour day-of-month month day-of-week`

use forgex::prelude::*;

/// {snake_name} scheduled task.
///
/// Configuration options:
/// - First argument: Cron expression (required)
/// - `timezone`: Timezone for schedule (default: "UTC")
/// - `catch_up`: Run missed executions on startup (default: false)
#[forgex::cron("0 0 * * *")]  // Daily at midnight UTC
#[timezone = "UTC"]
pub async fn {snake_name}(ctx: &CronContext) -> Result<()> {{
    tracing::info!(run_id = %ctx.run_id, "Running {snake_name}");

    // Get database pool for queries
    let _pool = ctx.db();

    // Example: Query data and dispatch jobs
    // let items = sqlx::query!("SELECT * FROM items WHERE status = 'pending'")
    //     .fetch_all(ctx.db())
    //     .await?;

    tracing::info!(run_id = %ctx.run_id, "Completed {snake_name}");

    Ok(())
}}
"#
    );

    fs::write(&file_path, content)?;
    update_functions_mod(&format!("{}_cron", snake_name))?;

    println!(
        "{} Created cron: {}",
        style("").green(),
        style(&file_path.display()).cyan()
    );
    println!("   Schedule: 0 0 * * * (daily at midnight)");
    println!("   Edit the schedule in the #[forgex::cron] attribute");

    Ok(())
}

/// Add a new workflow.
fn add_workflow(name: &str) -> Result<()> {
    let snake_name = to_snake_case(name);
    let pascal_name = to_pascal_case(name);

    let functions_dir = Path::new("src/functions");
    if !functions_dir.exists() {
        anyhow::bail!("Not in a FORGE project (src/functions not found)");
    }

    let file_path = functions_dir.join(format!("{}_workflow.rs", snake_name));
    if file_path.exists() {
        anyhow::bail!("Workflow file already exists: {}", file_path.display());
    }

    let content = format!(
        r#"//! Workflow: {snake_name}
//!
//! Workflows are multi-step processes with automatic state persistence.
//! Each step is durable - if the workflow fails, it resumes from the last
//! completed step. Steps can also define compensation (rollback) logic.
//!
//! ## Starting this workflow
//!
//! ```rust
//! let result = ctx.start_workflow({snake_name}, {pascal_name}Input {{
//!     // your input
//! }}).await?;
//! ```
//!
//! ## Key concepts
//!
//! - Steps are idempotent and re-executable
//! - Compensation runs in reverse order on failure
//! - Workflow state persists across restarts

use forgex::prelude::*;

/// Input for the {snake_name} workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {pascal_name}Input {{
    // Add your input fields here
    // pub user_id: Uuid,
    // pub order_id: Uuid,
}}

/// Output from the {snake_name} workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {pascal_name}Output {{
    pub success: bool,
    // Add your output fields here
    // pub confirmation_id: String,
}}

/// {pascal_name} workflow.
///
/// Configuration options:
/// - `version`: Workflow version for migrations (default: 1)
/// - `timeout`: Maximum workflow duration (default: "1h")
#[forgex::workflow]
#[version = 1]
#[timeout = "1h"]
pub async fn {snake_name}(ctx: &WorkflowContext, _input: {pascal_name}Input) -> Result<{pascal_name}Output> {{
    tracing::info!(workflow_id = %ctx.run_id, "Starting {snake_name} workflow");

    // Step 1: Validate
    if !ctx.is_step_completed("validate") {{
        ctx.record_step_start("validate");
        tracing::info!("Step 1: Validating input");
        // Add validation logic here
        ctx.record_step_complete("validate", serde_json::json!({{"status": "validated"}}));
    }}

    // Step 2: Process
    if !ctx.is_step_completed("process") {{
        ctx.record_step_start("process");
        tracing::info!("Step 2: Processing");
        // Add main processing logic here
        ctx.record_step_complete("process", serde_json::json!({{"status": "processed"}}));
    }}

    // Step 3: Notify
    if !ctx.is_step_completed("notify") {{
        ctx.record_step_start("notify");
        tracing::info!("Step 3: Sending notification");
        // Add notification logic here
        ctx.record_step_complete("notify", serde_json::json!({{"status": "notified"}}));
    }}

    tracing::info!(workflow_id = %ctx.run_id, "Completed {snake_name} workflow");

    Ok({pascal_name}Output {{ success: true }})
}}
"#
    );

    fs::write(&file_path, content)?;
    update_functions_mod(&format!("{}_workflow", snake_name))?;

    println!(
        "{} Created workflow: {}",
        style("").green(),
        style(&file_path.display()).cyan()
    );
    println!("   Features: durable steps, compensation, automatic retry");

    Ok(())
}

/// Update src/schema/mod.rs to include the new model.
fn update_schema_mod(snake_name: &str, pascal_name: &str) -> Result<()> {
    let mod_path = Path::new("src/schema/mod.rs");
    let content = fs::read_to_string(mod_path).unwrap_or_default();

    let mod_decl = format!("pub mod {};", snake_name);

    // Check if already declared
    if content.contains(&mod_decl) {
        println!(
            "  {} {} already declared in mod.rs",
            style("").blue(),
            snake_name
        );
        return Ok(());
    }

    // Build new content without extra blank lines
    let mut new_content = content.trim_end().to_string();
    if !new_content.is_empty() {
        new_content.push('\n');
    }
    new_content.push_str(&mod_decl);
    new_content.push('\n');
    new_content.push_str(&format!("pub use {}::{};\n", snake_name, pascal_name));

    fs::write(mod_path, new_content)?;
    Ok(())
}

/// Update src/functions/mod.rs to include the new function.
fn update_functions_mod(snake_name: &str) -> Result<()> {
    let mod_path = Path::new("src/functions/mod.rs");
    let content = fs::read_to_string(mod_path).unwrap_or_default();

    let mod_decl = format!("pub mod {};", snake_name);

    // Check if already declared
    if content.contains(&mod_decl) {
        println!(
            "  {} {} already declared in mod.rs",
            style("").blue(),
            snake_name
        );
        return Ok(());
    }

    // Build new content without extra blank lines
    let mut new_content = content.trim_end().to_string();
    if !new_content.is_empty() {
        new_content.push('\n');
    }
    new_content.push_str(&mod_decl);
    new_content.push('\n');
    new_content.push_str(&format!("pub use {}::*;\n", snake_name));

    fs::write(mod_path, new_content)?;
    Ok(())
}

/// Convert to PascalCase.
fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' || c == '-' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_uppercase().next().unwrap());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

/// Convert to snake_case.
fn to_snake_case(s: &str) -> String {
    let mut result = String::new();

    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap());
        } else if c == '-' {
            result.push('_');
        } else {
            result.push(c);
        }
    }

    result
}

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

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("user"), "User");
        assert_eq!(to_pascal_case("order_item"), "OrderItem");
        assert_eq!(to_pascal_case("my-component"), "MyComponent");
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("User"), "user");
        assert_eq!(to_snake_case("OrderItem"), "order_item");
        assert_eq!(to_snake_case("MyComponent"), "my_component");
    }
}