ferro-rs 0.2.21

A Laravel-inspired web framework for Rust
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
//! Application builder for Ferro framework
//!
//! Provides a fluent builder API to configure and run a Ferro application.
//!
//! # Example
//!
//! ```rust,ignore
//! use ferro_rs::Application;
//!
//! #[tokio::main]
//! async fn main() {
//!     Application::new()
//!         .config(config::register_all)
//!         .bootstrap(bootstrap::register)
//!         .routes(routes::register)
//!         .migrations::<migrations::Migrator>()
//!         .run()
//!         .await;
//! }
//! ```

use crate::seeder::SeederRegistry;
use crate::{Config, Router, Server};
use clap::{Parser, Subcommand};
use sea_orm_migration::prelude::*;
use std::env;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;

/// Type alias for async bootstrap function
type BootstrapFn = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;

/// CLI structure for Ferro applications
#[derive(Parser)]
#[command(name = "app")]
#[command(about = "Ferro application server and utilities")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Run the web server (default command)
    Serve {
        /// Skip running migrations on startup
        #[arg(long)]
        no_migrate: bool,
    },
    /// Run pending database migrations
    #[command(name = "db:migrate")]
    DbMigrate,
    /// Show migration status
    #[command(name = "db:status")]
    DbStatus,
    /// Rollback the last migration(s)
    #[command(name = "db:rollback")]
    DbRollback {
        /// Number of migrations to rollback
        #[arg(default_value = "1")]
        steps: u32,
    },
    /// Drop all tables and re-run all migrations
    #[command(name = "db:fresh")]
    DbFresh,
    /// Run the scheduler daemon (checks every minute)
    #[command(name = "schedule:work")]
    ScheduleWork,
    /// Run all due scheduled tasks once
    #[command(name = "schedule:run")]
    ScheduleRun,
    /// List all registered scheduled tasks
    #[command(name = "schedule:list")]
    ScheduleList,
    /// Run database seeders
    #[command(name = "db:seed")]
    DbSeed {
        /// Run only a specific seeder
        #[arg(long)]
        class: Option<String>,
    },
}

/// Application builder for Ferro framework
///
/// Use this to configure and run your Ferro application with a fluent API.
pub struct Application<M = NoMigrator>
where
    M: MigratorTrait,
{
    config_fn: Option<Box<dyn FnOnce()>>,
    bootstrap_fn: Option<BootstrapFn>,
    routes_fn: Option<Box<dyn FnOnce() -> Router + Send>>,
    seeders_fn: Option<Box<dyn FnOnce() -> SeederRegistry + Send>>,
    _migrator: std::marker::PhantomData<M>,
}

/// Placeholder type for when no migrator is configured
pub struct NoMigrator;

impl MigratorTrait for NoMigrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![]
    }
}

impl Application<NoMigrator> {
    /// Create a new application builder
    pub fn new() -> Self {
        Application {
            config_fn: None,
            bootstrap_fn: None,
            routes_fn: None,
            seeders_fn: None,
            _migrator: std::marker::PhantomData,
        }
    }
}

impl Default for Application<NoMigrator> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M> Application<M>
where
    M: MigratorTrait,
{
    /// Register a configuration function
    ///
    /// This function is called early during startup to register
    /// application configuration.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// App::new()
    ///     .config(config::register_all)
    /// ```
    pub fn config<F>(mut self, f: F) -> Self
    where
        F: FnOnce() + 'static,
    {
        self.config_fn = Some(Box::new(f));
        self
    }

    /// Register a bootstrap function
    ///
    /// This async function is called to register services, middleware,
    /// and other application components.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// App::new()
    ///     .bootstrap(bootstrap::register)
    /// ```
    pub fn bootstrap<F, Fut>(mut self, f: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.bootstrap_fn = Some(Box::new(move || Box::pin(f())));
        self
    }

    /// Register a routes function
    ///
    /// This function returns the application's router configuration.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// App::new()
    ///     .routes(routes::register)
    /// ```
    pub fn routes<F>(mut self, f: F) -> Self
    where
        F: FnOnce() -> Router + Send + 'static,
    {
        self.routes_fn = Some(Box::new(f));
        self
    }

    /// Configure the migrator type for database migrations
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// Application::new()
    ///     .migrations::<migrations::Migrator>()
    /// ```
    pub fn migrations<NewM>(self) -> Application<NewM>
    where
        NewM: MigratorTrait,
    {
        Application {
            config_fn: self.config_fn,
            bootstrap_fn: self.bootstrap_fn,
            routes_fn: self.routes_fn,
            seeders_fn: self.seeders_fn,
            _migrator: std::marker::PhantomData,
        }
    }

    /// Register a seeders function
    ///
    /// This function returns the application's seeder registry for database seeding.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// Application::new()
    ///     .seeders(seeders::register)
    /// ```
    pub fn seeders<F>(mut self, f: F) -> Self
    where
        F: FnOnce() -> SeederRegistry + Send + 'static,
    {
        self.seeders_fn = Some(Box::new(f));
        self
    }

    /// Run the application
    ///
    /// This parses CLI arguments and executes the appropriate command:
    /// - `serve` (default): Run the web server
    /// - `db:migrate`: Run pending migrations
    /// - `db:status`: Show migration status
    /// - `db:rollback`: Rollback migrations
    /// - `db:fresh`: Drop and re-run all migrations
    /// - `schedule:*`: Scheduler commands
    pub async fn run(self) {
        let cli = Cli::parse();

        // Initialize framework configuration (loads .env files)
        Config::init(Path::new("."));

        // Destructure self to avoid partial move issues
        let Application {
            config_fn,
            bootstrap_fn,
            routes_fn,
            seeders_fn,
            _migrator,
        } = self;

        // Run user's config registration
        if let Some(config_fn) = config_fn {
            config_fn();
        }

        // Initialize translator (after config so user can override LangConfig)
        crate::lang::init::init();

        match cli.command {
            None | Some(Commands::Serve { no_migrate: false }) => {
                // Default: run server with auto-migrate
                Self::run_migrations_silent::<M>().await;
                Self::run_server_internal(bootstrap_fn, routes_fn).await;
            }
            Some(Commands::Serve { no_migrate: true }) => {
                // Run server without migrations
                Self::run_server_internal(bootstrap_fn, routes_fn).await;
            }
            Some(Commands::DbMigrate) => {
                Self::run_migrations::<M>().await;
            }
            Some(Commands::DbStatus) => {
                Self::show_migration_status::<M>().await;
            }
            Some(Commands::DbRollback { steps }) => {
                Self::rollback_migrations::<M>(steps).await;
            }
            Some(Commands::DbFresh) => {
                Self::fresh_migrations::<M>().await;
            }
            Some(Commands::ScheduleWork) => {
                Self::run_scheduler_daemon_internal(bootstrap_fn).await;
            }
            Some(Commands::ScheduleRun) => {
                Self::run_scheduled_tasks_internal(bootstrap_fn).await;
            }
            Some(Commands::ScheduleList) => {
                Self::list_scheduled_tasks().await;
            }
            Some(Commands::DbSeed { class }) => {
                Self::run_seeders(seeders_fn, class).await;
            }
        }
    }

    async fn run_seeders(
        seeders_fn: Option<Box<dyn FnOnce() -> SeederRegistry + Send>>,
        class: Option<String>,
    ) {
        let database_url = match std::env::var("DATABASE_URL") {
            Ok(u) => u,
            Err(_) => {
                eprintln!("DATABASE_URL must be set");
                std::process::exit(1);
            }
        };
        let db = match sea_orm::Database::connect(&database_url).await {
            Ok(c) => c,
            Err(e) => {
                eprintln!("Failed to connect to database: {e}");
                std::process::exit(1);
            }
        };

        let registry = match seeders_fn {
            Some(f) => f(),
            None => {
                eprintln!("No seeders registered.");
                eprintln!("Register seeders with .seeders(seeders::register) in main.rs");
                return;
            }
        };

        let result = match class {
            Some(name) => registry.run_one(&name, &db).await,
            None => registry.run_all(&db).await,
        };

        if let Err(e) = result {
            eprintln!("Seeding failed: {e}");
            std::process::exit(1);
        }
    }

    async fn run_server_internal(
        bootstrap_fn: Option<BootstrapFn>,
        routes_fn: Option<Box<dyn FnOnce() -> Router + Send>>,
    ) {
        // Run bootstrap
        if let Some(bootstrap_fn) = bootstrap_fn {
            bootstrap_fn().await;
        }

        // Get router
        let router = if let Some(routes_fn) = routes_fn {
            routes_fn()
        } else {
            Router::new()
        };

        // Create server with configuration from environment
        Server::from_config(router)
            .run()
            .await
            .expect("Failed to start server");
    }

    async fn get_database_connection() -> sea_orm::DatabaseConnection {
        let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");

        // For SQLite, ensure the database file can be created
        let database_url = if database_url.starts_with("sqlite://") {
            let path = database_url.trim_start_matches("sqlite://");
            let path = path.trim_start_matches("./");

            if let Some(parent) = Path::new(path).parent() {
                if !parent.as_os_str().is_empty() {
                    std::fs::create_dir_all(parent).ok();
                }
            }

            if !Path::new(path).exists() {
                std::fs::File::create(path).ok();
            }

            format!("sqlite:{path}?mode=rwc")
        } else {
            database_url
        };

        sea_orm::Database::connect(&database_url)
            .await
            .expect("Failed to connect to database")
    }

    async fn run_migrations_silent<Migrator: MigratorTrait>() {
        let db = Self::get_database_connection().await;
        if let Err(e) = Migrator::up(&db, None).await {
            eprintln!("Warning: Migration failed: {e}");
        }
    }

    async fn run_migrations<Migrator: MigratorTrait>() {
        println!("Running migrations...");
        let db = Self::get_database_connection().await;
        Migrator::up(&db, None)
            .await
            .expect("Failed to run migrations");
        println!("Migrations completed successfully!");
    }

    async fn show_migration_status<Migrator: MigratorTrait>() {
        println!("Migration status:");
        let db = Self::get_database_connection().await;
        Migrator::status(&db)
            .await
            .expect("Failed to get migration status");
    }

    async fn rollback_migrations<Migrator: MigratorTrait>(steps: u32) {
        println!("Rolling back {steps} migration(s)...");
        let db = Self::get_database_connection().await;
        Migrator::down(&db, Some(steps))
            .await
            .expect("Failed to rollback migrations");
        println!("Rollback completed successfully!");
    }

    async fn fresh_migrations<Migrator: MigratorTrait>() {
        println!("WARNING: Dropping all tables and re-running migrations...");
        let db = Self::get_database_connection().await;
        Migrator::fresh(&db)
            .await
            .expect("Failed to refresh database");
        println!("Database refreshed successfully!");
    }

    async fn run_scheduler_daemon_internal(bootstrap_fn: Option<BootstrapFn>) {
        // Run bootstrap for scheduler context
        if let Some(bootstrap_fn) = bootstrap_fn {
            bootstrap_fn().await;
        }

        println!("==============================================");
        println!("  Ferro Scheduler Daemon");
        println!("==============================================");
        println!();
        println!("  Note: Create tasks with `ferro make:task <name>`");
        println!("  Press Ctrl+C to stop");
        println!();
        println!("==============================================");

        eprintln!("Scheduler daemon is not yet configured.");
        eprintln!("Create a scheduled task with: ferro make:task <name>");
        eprintln!("Then register it in src/schedule.rs");
    }

    async fn run_scheduled_tasks_internal(bootstrap_fn: Option<BootstrapFn>) {
        // Run bootstrap for scheduler context
        if let Some(bootstrap_fn) = bootstrap_fn {
            bootstrap_fn().await;
        }

        println!("Running scheduled tasks...");
        eprintln!("Scheduler is not yet configured.");
        eprintln!("Create a scheduled task with: ferro make:task <name>");
    }

    async fn list_scheduled_tasks() {
        println!("Registered scheduled tasks:");
        println!();
        eprintln!("No scheduled tasks registered.");
        eprintln!("Create a scheduled task with: ferro make:task <name>");
    }
}