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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! FORGE - The Rust Full-Stack Framework
//!
//! Single binary runtime that provides:
//! - HTTP Gateway with RPC endpoints
//! - WebSocket server for real-time subscriptions
//! - Background job workers
//! - Cron scheduler
//! - Workflow engine
//! - Observability dashboard
//! - Cluster coordination

use std::future::Future;
use std::net::IpAddr;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use axum::body::Body;
use axum::http::Request;
use axum::response::Response;
use tokio::sync::broadcast;

use forge_core::cluster::{LeaderRole, NodeId, NodeInfo, NodeRole, NodeStatus};
use forge_core::config::{ForgeConfig, NodeRole as ConfigNodeRole};
use forge_core::error::{ForgeError, Result};
use forge_runtime::migrations::{load_migrations_from_dir, Migration, MigrationRunner};

use forge_runtime::cluster::{
    GracefulShutdown, HeartbeatConfig, HeartbeatLoop, LeaderConfig, LeaderElection, NodeRegistry,
    ShutdownConfig,
};
use forge_runtime::cron::{CronRegistry, CronRunner, CronRunnerConfig};
use forge_runtime::dashboard::{
    create_api_router, create_dashboard_router, DashboardConfig, DashboardState,
};
use forge_runtime::db::Database;
use forge_runtime::function::FunctionRegistry;
use forge_runtime::gateway::{AuthConfig, GatewayConfig as RuntimeGatewayConfig, GatewayServer};
use forge_runtime::jobs::{JobDispatcher, JobQueue, JobRegistry, Worker, WorkerConfig};
use forge_runtime::observability::{ObservabilityConfig, ObservabilityState};
use forge_runtime::realtime::{WebSocketConfig, WebSocketServer};
use forge_runtime::workflow::{
    EventStore, WorkflowExecutor, WorkflowRegistry, WorkflowScheduler, WorkflowSchedulerConfig,
};
use tokio_util::sync::CancellationToken;

/// Type alias for frontend handler function.
pub type FrontendHandler = fn(Request<Body>) -> Pin<Box<dyn Future<Output = Response> + Send>>;

/// Prelude module for common imports.
pub mod prelude {
    // Common types
    pub use chrono::{DateTime, Utc};
    pub use uuid::Uuid;

    // Serde re-exports for user code
    pub use serde::{Deserialize, Serialize};
    pub use serde_json;

    /// Timestamp type alias for convenience.
    pub type Timestamp = DateTime<Utc>;

    // Core types
    pub use forge_core::cluster::NodeRole;
    pub use forge_core::config::ForgeConfig;
    pub use forge_core::cron::{CronContext, ForgeCron};
    pub use forge_core::error::{ForgeError, Result};
    pub use forge_core::function::{
        ActionContext, AuthContext, ForgeMutation, ForgeQuery, MutationContext, QueryContext,
    };
    pub use forge_core::job::{ForgeJob, JobContext, JobPriority};
    pub use forge_core::realtime::Delta;
    pub use forge_core::schema::{FieldDef, ModelMeta, SchemaRegistry, TableDef};
    pub use forge_core::workflow::{ForgeWorkflow, WorkflowContext};

    pub use crate::{Forge, ForgeBuilder};

    // Testing utilities - re-export when testing feature is enabled
    // Note: Uses feature = "testing" only (not cfg(test)) because cfg(test) in this
    // crate doesn't enable the testing module in forge-core dependency.
    #[cfg(feature = "testing")]
    pub use forge_core::testing::{
        assert_json_matches,
        error_contains,
        validation_error_for_field,
        // Mocks
        DispatchedJob,
        // Database
        IsolatedTestDb,
        MockHttp,
        MockHttpBuilder,
        MockJobDispatch,
        MockRequest,
        MockResponse,
        MockWorkflowDispatch,
        StartedWorkflow,
        // Test contexts
        TestActionContext,
        TestActionContextBuilder,
        TestCronContext,
        TestCronContextBuilder,
        TestDatabase,
        TestJobContext,
        TestJobContextBuilder,
        TestMutationContext,
        TestMutationContextBuilder,
        TestQueryContext,
        TestQueryContextBuilder,
        TestWorkflowContext,
        TestWorkflowContextBuilder,
    };

    // Re-export assertion macros in prelude (macros are at crate root via #[macro_export])
    #[cfg(feature = "testing")]
    pub use forge_core::{
        assert_err, assert_err_variant, assert_http_called, assert_http_not_called,
        assert_job_dispatched, assert_job_not_dispatched, assert_ok, assert_workflow_not_started,
        assert_workflow_started,
    };
}

/// The main FORGE runtime.
pub struct Forge {
    config: ForgeConfig,
    db: Option<Database>,
    node_id: NodeId,
    function_registry: FunctionRegistry,
    job_registry: JobRegistry,
    cron_registry: Arc<CronRegistry>,
    workflow_registry: WorkflowRegistry,
    shutdown_tx: broadcast::Sender<()>,
    /// Path to user migrations directory (default: ./migrations).
    migrations_dir: PathBuf,
    /// Additional migrations provided programmatically.
    extra_migrations: Vec<Migration>,
    /// Observability state (created during run()).
    observability: Option<ObservabilityState>,
    /// Optional frontend handler for embedded SPA.
    frontend_handler: Option<FrontendHandler>,
}

impl Forge {
    /// Create a new builder for configuring FORGE.
    pub fn builder() -> ForgeBuilder {
        ForgeBuilder::new()
    }

    /// Get the node ID.
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// Get the configuration.
    pub fn config(&self) -> &ForgeConfig {
        &self.config
    }

    /// Get the function registry.
    pub fn function_registry(&self) -> &FunctionRegistry {
        &self.function_registry
    }

    /// Get the function registry mutably.
    pub fn function_registry_mut(&mut self) -> &mut FunctionRegistry {
        &mut self.function_registry
    }

    /// Get the job registry.
    pub fn job_registry(&self) -> &JobRegistry {
        &self.job_registry
    }

    /// Get the job registry mutably.
    pub fn job_registry_mut(&mut self) -> &mut JobRegistry {
        &mut self.job_registry
    }

    /// Get the cron registry.
    pub fn cron_registry(&self) -> Arc<CronRegistry> {
        self.cron_registry.clone()
    }

    /// Get the workflow registry.
    pub fn workflow_registry(&self) -> &WorkflowRegistry {
        &self.workflow_registry
    }

    /// Get the workflow registry mutably.
    pub fn workflow_registry_mut(&mut self) -> &mut WorkflowRegistry {
        &mut self.workflow_registry
    }

    /// Get the observability state (available after run() starts).
    pub fn observability(&self) -> Option<&ObservabilityState> {
        self.observability.as_ref()
    }

    /// Run the FORGE server.
    pub async fn run(mut self) -> Result<()> {
        tracing::info!("FORGE runtime starting");

        // Connect to database
        let db = Database::from_config(&self.config.database).await?;
        let pool = db.primary().clone();
        self.db = Some(db);

        tracing::info!("Connected to database");

        // Run migrations with mesh-safe locking
        // This acquires an advisory lock, so only one node runs migrations at a time
        let runner = MigrationRunner::new(pool.clone());

        // Load user migrations from directory + any programmatic ones
        let mut user_migrations = load_migrations_from_dir(&self.migrations_dir)?;
        user_migrations.extend(self.extra_migrations.clone());

        runner.run(user_migrations).await?;
        tracing::info!("Migrations completed");

        // Create observability state
        let obs_config = ObservabilityConfig::default();
        let observability = ObservabilityState::new(obs_config, pool.clone());
        self.observability = Some(observability.clone());

        // Start observability background tasks
        let obs_handles = observability.start_background_tasks();
        tracing::info!(
            "Observability collectors started ({} background tasks)",
            obs_handles.len()
        );

        // Get local node info
        let hostname = hostname::get()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_else(|_| "unknown".to_string());

        let ip_address: IpAddr = "127.0.0.1".parse().unwrap();
        let roles: Vec<NodeRole> = self
            .config
            .node
            .roles
            .iter()
            .map(config_role_to_node_role)
            .collect();

        let node_info = NodeInfo::new_local(
            hostname,
            ip_address,
            self.config.gateway.port,
            self.config.gateway.grpc_port,
            roles.clone(),
            self.config.node.worker_capabilities.clone(),
            env!("CARGO_PKG_VERSION").to_string(),
        );

        let node_id = node_info.id;
        self.node_id = node_id;

        // Create node registry
        let node_registry = Arc::new(NodeRegistry::new(pool.clone(), node_info));

        // Register node in cluster
        if let Err(e) = node_registry.register().await {
            tracing::warn!("Failed to register node (tables may not exist): {}", e);
        }

        // Set node status to active
        if let Err(e) = node_registry.set_status(NodeStatus::Active).await {
            tracing::warn!("Failed to set node status: {}", e);
        }

        // Create leader election for scheduler role
        let leader_election = if roles.contains(&NodeRole::Scheduler) {
            let election = Arc::new(LeaderElection::new(
                pool.clone(),
                node_id,
                LeaderRole::Scheduler,
                LeaderConfig::default(),
            ));

            // Try to become leader
            if let Err(e) = election.try_become_leader().await {
                tracing::warn!("Failed to acquire leadership: {}", e);
            }

            Some(election)
        } else {
            None
        };

        // Create graceful shutdown coordinator
        let shutdown = Arc::new(GracefulShutdown::new(
            node_registry.clone(),
            leader_election.clone(),
            ShutdownConfig::default(),
        ));

        // Create HTTP client for actions and crons
        let http_client = reqwest::Client::new();

        // Start background tasks based on roles
        let mut handles = Vec::new();

        // Start heartbeat loop
        {
            let heartbeat_pool = pool.clone();
            let heartbeat_node_id = node_id;
            let config = HeartbeatConfig::default();
            handles.push(tokio::spawn(async move {
                let heartbeat = HeartbeatLoop::new(heartbeat_pool, heartbeat_node_id, config);
                heartbeat.run().await;
            }));
        }

        // Start leader election loop if scheduler role
        if let Some(ref election) = leader_election {
            let election = election.clone();
            handles.push(tokio::spawn(async move {
                election.run().await;
            }));
        }

        // Start job worker if worker role
        if roles.contains(&NodeRole::Worker) {
            let job_queue = JobQueue::new(pool.clone());
            let worker_config = WorkerConfig {
                id: Some(node_id.as_uuid()),
                capabilities: self.config.node.worker_capabilities.clone(),
                max_concurrent: self.config.worker.max_concurrent_jobs,
                poll_interval: Duration::from_millis(self.config.worker.poll_interval_ms),
                ..Default::default()
            };

            let mut worker = Worker::with_observability(
                worker_config,
                job_queue,
                self.job_registry.clone(),
                pool.clone(),
                observability.clone(),
            );

            handles.push(tokio::spawn(async move {
                if let Err(e) = worker.run().await {
                    tracing::error!("Worker error: {}", e);
                }
            }));

            tracing::info!("Job worker started");
        }

        // Start cron runner if scheduler role and is leader
        if roles.contains(&NodeRole::Scheduler) {
            let cron_registry = self.cron_registry.clone();
            let cron_pool = pool.clone();
            let cron_http = http_client.clone();
            let is_leader = leader_election
                .as_ref()
                .map(|e| e.is_leader())
                .unwrap_or(false);

            let cron_config = CronRunnerConfig {
                poll_interval: Duration::from_secs(1),
                node_id: node_id.as_uuid(),
                is_leader,
            };

            let cron_runner = CronRunner::with_observability(
                cron_registry,
                cron_pool,
                cron_http,
                cron_config,
                observability.clone(),
            );

            handles.push(tokio::spawn(async move {
                if let Err(e) = cron_runner.run().await {
                    tracing::error!("Cron runner error: {}", e);
                }
            }));

            tracing::info!("Cron scheduler started");
        }

        // Start workflow scheduler if scheduler role
        let workflow_shutdown_token = CancellationToken::new();
        if roles.contains(&NodeRole::Scheduler) {
            let scheduler_executor = Arc::new(WorkflowExecutor::new(
                Arc::new(self.workflow_registry.clone()),
                pool.clone(),
                http_client.clone(),
            ));
            let event_store = Arc::new(EventStore::new(pool.clone()));
            let scheduler = WorkflowScheduler::new(
                pool.clone(),
                scheduler_executor,
                event_store,
                WorkflowSchedulerConfig::default(),
            );

            let shutdown_token = workflow_shutdown_token.clone();
            handles.push(tokio::spawn(async move {
                scheduler.run(shutdown_token).await;
            }));

            tracing::info!("Workflow scheduler started");
        }

        // Reactor handle for shutdown
        let mut reactor_handle = None;

        // Create job dispatcher and workflow executor for dispatch capabilities
        let job_queue = JobQueue::new(pool.clone());
        let job_dispatcher = Arc::new(JobDispatcher::new(job_queue, self.job_registry.clone()));
        let workflow_executor = Arc::new(WorkflowExecutor::new(
            Arc::new(self.workflow_registry.clone()),
            pool.clone(),
            http_client.clone(),
        ));

        // Start HTTP gateway if gateway role
        if roles.contains(&NodeRole::Gateway) {
            let gateway_config = RuntimeGatewayConfig {
                port: self.config.gateway.port,
                max_connections: self.config.gateway.max_connections,
                request_timeout_secs: self.config.gateway.request_timeout_secs,
                cors_enabled: true,
                cors_origins: vec!["*".to_string()],
                auth: AuthConfig::default(),
            };

            // Create dashboard state with registries and dispatchers
            let dashboard_state = DashboardState {
                pool: pool.clone(),
                config: DashboardConfig::default(),
                job_registry: self.job_registry.clone(),
                cron_registry: self.cron_registry.clone(),
                workflow_registry: self.workflow_registry.clone(),
                job_dispatcher: Some(job_dispatcher.clone()),
                workflow_executor: Some(workflow_executor.clone()),
            };

            // Build gateway router with dashboard and observability
            let gateway = GatewayServer::with_observability(
                gateway_config,
                self.function_registry.clone(),
                pool.clone(),
                observability.clone(),
            )
            .with_job_dispatcher(job_dispatcher.clone())
            .with_workflow_dispatcher(workflow_executor.clone());

            // Start the reactor for real-time updates
            let reactor = gateway.reactor();
            if let Err(e) = reactor.start().await {
                tracing::error!("Failed to start reactor: {}", e);
            } else {
                tracing::info!("Reactor started for real-time updates");
                reactor_handle = Some(reactor);
            }

            let mut router = gateway.router();

            // Mount dashboard at /_dashboard and API at /_api
            router = router
                .nest(
                    "/_dashboard",
                    create_dashboard_router(dashboard_state.clone()),
                )
                .nest("/_api", create_api_router(dashboard_state));

            // Add frontend handler as fallback if configured
            if let Some(handler) = self.frontend_handler {
                use axum::routing::get;
                router = router.fallback(get(handler));
                tracing::info!("Frontend handler enabled - serving embedded assets");
            }

            let addr = gateway.addr();

            handles.push(tokio::spawn(async move {
                tracing::info!("Gateway server listening on {}", addr);
                let listener = tokio::net::TcpListener::bind(addr)
                    .await
                    .expect("Failed to bind");
                if let Err(e) = axum::serve(listener, router).await {
                    tracing::error!("Gateway server error: {}", e);
                }
            }));

            tracing::info!("HTTP gateway started on port {}", self.config.gateway.port);
        }

        // Start WebSocket server if gateway role
        if roles.contains(&NodeRole::Gateway) {
            let ws_config = WebSocketConfig::default();
            let _ws_server = WebSocketServer::new(node_id, ws_config);

            // WebSocket upgrade handling would be added to the gateway router
            // For now, we just hold the server state
            tracing::info!("WebSocket server initialized");
        }

        tracing::info!("FORGE runtime started successfully");
        tracing::info!("  Node ID: {}", node_id);
        tracing::info!("  Roles: {:?}", roles);

        // Wait for shutdown signal
        let mut shutdown_rx = self.shutdown_tx.subscribe();

        tokio::select! {
            _ = tokio::signal::ctrl_c() => {
                tracing::info!("Received shutdown signal");
            }
            _ = shutdown_rx.recv() => {
                tracing::info!("Received shutdown notification");
            }
        }

        // Graceful shutdown
        tracing::info!("Starting graceful shutdown...");

        // Stop workflow scheduler
        workflow_shutdown_token.cancel();
        tracing::info!("Workflow scheduler stopped");

        if let Err(e) = shutdown.shutdown().await {
            tracing::warn!("Shutdown error: {}", e);
        }

        // Stop leader election
        if let Some(ref election) = leader_election {
            election.stop();
        }

        // Stop reactor before closing database
        if let Some(ref reactor) = reactor_handle {
            reactor.stop();
            tracing::info!("Reactor stopped");
        }

        // Shutdown observability (final flush)
        observability.shutdown().await;
        tracing::info!("Observability shutdown complete");

        // Close database connections
        if let Some(ref db) = self.db {
            db.close().await;
        }

        tracing::info!("FORGE runtime stopped");
        Ok(())
    }

    /// Request shutdown.
    pub fn shutdown(&self) {
        let _ = self.shutdown_tx.send(());
    }
}

/// Builder for configuring the FORGE runtime.
pub struct ForgeBuilder {
    config: Option<ForgeConfig>,
    function_registry: FunctionRegistry,
    job_registry: JobRegistry,
    cron_registry: CronRegistry,
    workflow_registry: WorkflowRegistry,
    migrations_dir: PathBuf,
    extra_migrations: Vec<Migration>,
    frontend_handler: Option<FrontendHandler>,
}

impl ForgeBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            config: None,
            function_registry: FunctionRegistry::new(),
            job_registry: JobRegistry::new(),
            cron_registry: CronRegistry::new(),
            workflow_registry: WorkflowRegistry::new(),
            migrations_dir: PathBuf::from("migrations"),
            extra_migrations: Vec::new(),
            frontend_handler: None,
        }
    }

    /// Set the directory to load migrations from.
    ///
    /// Defaults to `./migrations`. Migration files should be named like:
    /// - `0001_create_users.sql`
    /// - `0002_add_posts.sql`
    pub fn migrations_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.migrations_dir = path.into();
        self
    }

    /// Add a migration programmatically.
    ///
    /// Use this for migrations that need to be generated at runtime,
    /// or for testing. For most cases, use migration files instead.
    pub fn migration(mut self, name: impl Into<String>, sql: impl Into<String>) -> Self {
        self.extra_migrations.push(Migration::new(name, sql));
        self
    }

    /// Set a frontend handler for serving embedded SPA assets.
    ///
    /// Use with the `embedded-frontend` feature to build a single binary
    /// that includes both backend and frontend.
    pub fn frontend_handler(&mut self, handler: FrontendHandler) {
        self.frontend_handler = Some(handler);
    }

    /// Set the configuration.
    pub fn config(mut self, config: ForgeConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Get mutable access to the function registry.
    pub fn function_registry_mut(&mut self) -> &mut FunctionRegistry {
        &mut self.function_registry
    }

    /// Get mutable access to the job registry.
    pub fn job_registry_mut(&mut self) -> &mut JobRegistry {
        &mut self.job_registry
    }

    /// Get mutable access to the cron registry.
    pub fn cron_registry_mut(&mut self) -> &mut CronRegistry {
        &mut self.cron_registry
    }

    /// Get mutable access to the workflow registry.
    pub fn workflow_registry_mut(&mut self) -> &mut WorkflowRegistry {
        &mut self.workflow_registry
    }

    /// Build the FORGE runtime.
    pub fn build(self) -> Result<Forge> {
        let config = self
            .config
            .ok_or_else(|| ForgeError::Config("Configuration is required".to_string()))?;

        let (shutdown_tx, _) = broadcast::channel(1);

        Ok(Forge {
            config,
            db: None,
            node_id: NodeId::new(),
            function_registry: self.function_registry,
            job_registry: self.job_registry,
            cron_registry: Arc::new(self.cron_registry),
            workflow_registry: self.workflow_registry,
            shutdown_tx,
            migrations_dir: self.migrations_dir,
            extra_migrations: self.extra_migrations,
            observability: None,
            frontend_handler: self.frontend_handler,
        })
    }
}

impl Default for ForgeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert config NodeRole to cluster NodeRole.
fn config_role_to_node_role(role: &ConfigNodeRole) -> NodeRole {
    match role {
        ConfigNodeRole::Gateway => NodeRole::Gateway,
        ConfigNodeRole::Function => NodeRole::Function,
        ConfigNodeRole::Worker => NodeRole::Worker,
        ConfigNodeRole::Scheduler => NodeRole::Scheduler,
    }
}

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

    #[test]
    fn test_forge_builder_new() {
        let builder = ForgeBuilder::new();
        assert!(builder.config.is_none());
    }

    #[test]
    fn test_forge_builder_requires_config() {
        let builder = ForgeBuilder::new();
        let result = builder.build();
        assert!(result.is_err());
    }

    #[test]
    fn test_forge_builder_with_config() {
        let config = ForgeConfig::default_with_database_url("postgres://localhost/test");
        let result = ForgeBuilder::new().config(config).build();
        assert!(result.is_ok());
    }

    #[test]
    fn test_config_role_conversion() {
        assert_eq!(
            config_role_to_node_role(&ConfigNodeRole::Gateway),
            NodeRole::Gateway
        );
        assert_eq!(
            config_role_to_node_role(&ConfigNodeRole::Worker),
            NodeRole::Worker
        );
        assert_eq!(
            config_role_to_node_role(&ConfigNodeRole::Scheduler),
            NodeRole::Scheduler
        );
        assert_eq!(
            config_role_to_node_role(&ConfigNodeRole::Function),
            NodeRole::Function
        );
    }
}