flare-core-runtime 1.0.4

Service runtime, task orchestration, health, shutdown, plugin, and state tracking primitives.
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! ServiceRuntime 核心实现
//!
//! 提供统一的服务生命周期管理,支持:
//! - 多种服务类型 (HTTP, gRPC, MQ 消费者, 自定义任务)
//! - 优雅停机
//! - 服务注册/注销
//! - 健康检查
//! - 状态监控

use crate::config::RuntimeConfig;
use crate::error::HealthError;
use crate::health::{HealthCheck, HealthChecker};
use crate::registry::ServiceRegistry;
use crate::signal::{CompositeSignal, CtrlCSignal, ShutdownSignal, UnixSignal, UnixSignalKind};
use crate::state::StateTracker;
use crate::task::{SpawnTask, Task, TaskManager};
use anyhow::Result;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::{error, info, warn};

/// 默认健康检查:监控任务失败状态
struct TaskFailureHealthCheck {
    tracker: Arc<StateTracker>,
}

impl TaskFailureHealthCheck {
    fn new(tracker: Arc<StateTracker>) -> Self {
        Self { tracker }
    }
}

impl HealthCheck for TaskFailureHealthCheck {
    fn check(
        &self,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = std::result::Result<(), HealthError>> + Send + '_>,
    > {
        Box::pin(async move {
            if self.tracker.has_failures().await {
                let failed = self.tracker.get_failed_tasks().await;
                return Err(HealthError::CheckFailed {
                    name: self.name().to_string(),
                    reason: format!("failed tasks detected: {:?}", failed),
                });
            }
            Ok(())
        })
    }

    fn name(&self) -> &str {
        "task-failure-monitor"
    }
}

/// 健康检查失败后的运行时行为
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HealthFailureAction {
    /// 仅记录告警,不主动停机
    LogOnly,
    /// 触发优雅停机
    GracefulShutdown,
}

struct HealthMonitorHandle {
    stop_tx: oneshot::Sender<()>,
    join_handle: JoinHandle<()>,
    failure_rx: Option<mpsc::UnboundedReceiver<String>>,
}

/// 服务运行时
///
/// 统一管理服务的生命周期,包括:
/// - 任务启动和管理(HTTP, gRPC, MQ 消费者等)
/// - 服务注册和注销
/// - 优雅停机
/// - 状态监控
///
/// # 示例
///
/// ## 简单模式(不注册服务)
///
/// ```rust,no_run
/// use flare_core_runtime::ServiceRuntime;
/// use flare_core_runtime::task::SpawnTask;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
///     let runtime = ServiceRuntime::new("my-service")
///         .add_spawn("my-task", async { Ok(()) });
///
///     runtime.run().await?;
///     Ok(())
/// }
/// ```
///
/// ## 完整模式(带服务注册)
///
/// ```rust,no_run
/// use flare_core_runtime::ServiceRuntime;
/// use std::net::SocketAddr;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
///     let runtime = ServiceRuntime::new("my-service")
///         .with_address("0.0.0.0:8080".parse().unwrap())
///         .add_spawn("grpc", async { Ok(()) });
///
///     runtime.run_with_registration(|addr| {
///         Box::pin(async move {
///             // 注册服务
///             Ok(None)
///         })
///     }).await?;
///     Ok(())
/// }
/// ```
pub struct ServiceRuntime {
    /// 服务名称
    service_name: String,
    /// 服务地址(用于服务注册)
    service_address: Option<SocketAddr>,
    /// 任务管理器
    task_manager: TaskManager,
    /// 服务注册器
    registry: Option<Box<dyn ServiceRegistry>>,
    /// 配置
    config: RuntimeConfig,
    /// 健康检查器(可选)
    health_checker: Option<HealthChecker>,
    /// 健康检查失败动作
    health_failure_action: HealthFailureAction,
}

impl ServiceRuntime {
    /// 创建新的服务运行时
    ///
    /// # 参数
    ///
    /// * `service_name` - 服务名称(用于日志和服务注册)
    ///
    /// # 示例
    ///
    /// ```rust
    /// use flare_core_runtime::ServiceRuntime;
    ///
    /// let runtime = ServiceRuntime::new("my-service");
    /// ```
    pub fn new(service_name: impl Into<String>) -> Self {
        Self {
            service_name: service_name.into(),
            service_address: None,
            task_manager: TaskManager::new(),
            registry: None,
            config: RuntimeConfig::default(),
            health_checker: None,
            health_failure_action: HealthFailureAction::LogOnly,
        }
    }

    /// 创建简单的任务运行器(无需服务名和地址)
    ///
    /// 用于运行 MQ 消费者、自定义任务等简单场景
    ///
    /// # 示例
    ///
    /// ```rust
    /// use flare_core_runtime::ServiceRuntime;
    ///
    /// // 仅运行 MQ 消费者
    /// let runtime = ServiceRuntime::simple()
    ///     .add_spawn("kafka-consumer", async { Ok(()) });
    /// ```
    pub fn simple() -> Self {
        Self {
            service_name: "simple-runtime".to_string(),
            service_address: None,
            task_manager: TaskManager::new(),
            registry: None,
            config: RuntimeConfig::default(),
            health_checker: None,
            health_failure_action: HealthFailureAction::LogOnly,
        }
    }

    /// 创建 MQ 消费者运行器
    ///
    /// 专门用于运行 MQ 消费者的便捷方法
    ///
    /// # 示例
    ///
    /// ```rust
    /// use flare_core_runtime::ServiceRuntime;
    ///
    /// let runtime = ServiceRuntime::mq_consumer()
    ///     .add_spawn("kafka-consumer", async { Ok(()) })
    ///     .add_spawn("nats-consumer", async { Ok(()) });
    /// ```
    pub fn mq_consumer() -> Self {
        Self::simple()
    }

    /// 创建自定义任务运行器
    ///
    /// 专门用于运行自定义任务的便捷方法
    ///
    /// # 示例
    ///
    /// ```rust
    /// use flare_core_runtime::ServiceRuntime;
    ///
    /// let runtime = ServiceRuntime::tasks()
    ///     .add_spawn("task-1", async { Ok(()) })
    ///     .add_spawn("task-2", async { Ok(()) });
    /// ```
    pub fn tasks() -> Self {
        Self::simple()
    }

    /// 设置服务地址
    ///
    /// # 参数
    ///
    /// * `address` - 服务地址(用于服务注册)
    pub fn with_address(mut self, address: SocketAddr) -> Self {
        self.service_address = Some(address);
        self
    }

    /// 设置运行时配置
    pub fn with_config(mut self, config: RuntimeConfig) -> Self {
        self.task_manager.set_config(config.clone());
        self.config = config;
        self
    }

    /// 设置服务注册器
    pub fn with_registry(mut self, registry: Box<dyn ServiceRegistry>) -> Self {
        self.registry = Some(registry);
        self
    }

    /// 设置健康检查器
    pub fn with_health_checker(mut self, checker: HealthChecker) -> Self {
        self.health_checker = Some(checker);
        self
    }

    /// 添加健康检查项
    pub fn add_health_check(mut self, check: Arc<dyn HealthCheck>) -> Self {
        if let Some(checker) = &mut self.health_checker {
            checker.add_check(check);
        } else {
            let mut checker = HealthChecker::new()
                .with_failure_threshold(self.config.health_check.failure_threshold);
            checker.add_check(check);
            self.health_checker = Some(checker);
        }
        self
    }

    /// 设置健康检查失败时的行为
    pub fn with_health_failure_action(mut self, action: HealthFailureAction) -> Self {
        self.health_failure_action = action;
        self
    }

    /// 添加任务
    ///
    /// # 参数
    ///
    /// * `task` - 要添加的任务(实现了 `Task` trait)
    pub fn add_task(mut self, task: Box<dyn Task>) -> Self {
        self.task_manager.add_task(task);
        self
    }

    /// 添加 spawn 任务(直接添加 Future)
    ///
    /// # 参数
    ///
    /// * `name` - 任务名称
    /// * `future` - 要运行的 Future
    ///
    /// # 示例
    ///
    /// ```rust
    /// use flare_core_runtime::ServiceRuntime;
    ///
    /// let runtime = ServiceRuntime::new("my-service")
    ///     .add_spawn("my-task", async { Ok(()) });
    /// ```
    pub fn add_spawn<Fut>(mut self, name: impl Into<String>, future: Fut) -> Self
    where
        Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>>
            + Send
            + 'static,
    {
        self.task_manager
            .add_task(Box::new(SpawnTask::new(name, future)));
        self
    }

    /// 添加 spawn 任务(带依赖)
    pub fn add_spawn_with_deps<Fut>(
        mut self,
        name: impl Into<String>,
        future: Fut,
        dependencies: Vec<String>,
    ) -> Self
    where
        Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>>
            + Send
            + 'static,
    {
        self.task_manager.add_task(Box::new(
            SpawnTask::new(name, future).with_dependencies(dependencies),
        ));
        self
    }

    /// 添加 spawn 任务(需要 shutdown)
    pub fn add_spawn_with_shutdown<F, Fut>(mut self, name: impl Into<String>, future_fn: F) -> Self
    where
        F: FnOnce(oneshot::Receiver<()>) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>>
            + Send
            + 'static,
    {
        self.task_manager
            .add_task(Box::new(SpawnTask::with_shutdown(name, future_fn)));
        self
    }

    /// 获取状态追踪器
    pub fn state_tracker(&self) -> Arc<StateTracker> {
        self.task_manager.state_tracker()
    }

    /// 启动健康检查监控任务
    fn start_health_monitor(&mut self) -> Option<HealthMonitorHandle> {
        if !self.config.health_check.enabled {
            return None;
        }

        let mut checker = self.health_checker.take().unwrap_or_else(|| {
            let mut default_checker = HealthChecker::new()
                .with_failure_threshold(self.config.health_check.failure_threshold);
            default_checker.add_check(Arc::new(TaskFailureHealthCheck::new(
                self.task_manager.state_tracker(),
            )));
            default_checker
        });

        if checker.check_count() == 0 {
            checker.add_check(Arc::new(TaskFailureHealthCheck::new(
                self.task_manager.state_tracker(),
            )));
        }

        let mut failure_rx = None;
        if self.health_failure_action == HealthFailureAction::GracefulShutdown {
            let (failure_tx, rx) = mpsc::unbounded_channel::<String>();
            checker = checker.with_on_failure(Arc::new(move |check_name: &str| {
                let _ = failure_tx.send(check_name.to_string());
            }));
            failure_rx = Some(rx);
        }

        let service_name = self.service_name.clone();
        let interval = self.config.health_check.interval;
        let timeout = self.config.health_check.timeout;
        let (stop_tx, mut stop_rx) = oneshot::channel::<()>();

        let handle = tokio::spawn(async move {
            let mut ticker = tokio::time::interval(interval);
            ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

            info!(
                service_name = %service_name,
                interval_ms = interval.as_millis() as u64,
                timeout_ms = timeout.as_millis() as u64,
                check_count = checker.check_count(),
                "Health monitor started"
            );

            loop {
                tokio::select! {
                    _ = &mut stop_rx => {
                        info!(service_name = %service_name, "Health monitor stopped");
                        break;
                    }
                    _ = ticker.tick() => {
                        match tokio::time::timeout(timeout, checker.check_all()).await {
                            Ok(results) => {
                                let unhealthy: Vec<_> = results.into_iter().filter(|r| !r.healthy).collect();
                                if !unhealthy.is_empty() {
                                    let names: Vec<_> = unhealthy.into_iter().map(|r| r.name).collect();
                                    warn!(
                                        service_name = %service_name,
                                        unhealthy_checks = ?names,
                                        "Health monitor detected unhealthy checks"
                                    );
                                }
                            }
                            Err(_) => {
                                warn!(
                                    service_name = %service_name,
                                    timeout_ms = timeout.as_millis() as u64,
                                    "Health monitor round timed out"
                                );
                            }
                        }
                    }
                }
            }
        });

        Some(HealthMonitorHandle {
            stop_tx,
            join_handle: handle,
            failure_rx,
        })
    }

    /// 运行服务(简单模式,不注册服务)
    ///
    /// 执行以下步骤:
    /// 1. 启动所有任务
    /// 2. 等待所有任务就绪
    /// 3. 等待关闭信号(Ctrl+C)
    /// 4. 优雅关闭所有任务
    pub async fn run(self) -> Result<()> {
        self.run_with_signals(vec![]).await
    }

    /// 运行服务(带自定义信号)
    ///
    /// # 参数
    ///
    /// * `signals` - 自定义停机信号列表
    pub async fn run_with_signals(
        mut self,
        mut signals: Vec<Box<dyn ShutdownSignal>>,
    ) -> Result<()> {
        info!(
            service_name = %self.service_name,
            task_count = self.task_manager.task_count(),
            "🚀 Starting service runtime"
        );

        // 1. 构建停机信号
        if signals.is_empty() {
            // 默认信号:Ctrl+C + SIGTERM (Unix)
            signals.push(Box::new(CtrlCSignal::new()));

            #[cfg(target_family = "unix")]
            signals.push(Box::new(UnixSignal::new(UnixSignalKind::Terminate)));
        }

        let mut shutdown_signal = CompositeSignal::from_signals(signals);

        // 2. 启动所有任务
        let (join_set, shutdown_txs) = self
            .task_manager
            .start_all()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to start tasks: {}", e))?;

        // 3. 等待所有任务就绪
        self.task_manager
            .wait_for_ready()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to wait for tasks ready: {}", e))?;

        // 4.1 启动健康检查监控(可选)
        let mut health_monitor = self.start_health_monitor();

        // 5. 等待停机信号或健康检查触发停机
        info!("Waiting for shutdown signal...");
        if let Some(monitor) = health_monitor.as_mut() {
            if let Some(failure_rx) = monitor.failure_rx.as_mut() {
                tokio::select! {
                    _ = shutdown_signal.wait() => {
                        info!("Shutdown signal received");
                    }
                    failed = failure_rx.recv() => {
                        warn!(failed_check = ?failed, "Health check threshold exceeded, triggering graceful shutdown");
                    }
                }
            } else {
                shutdown_signal.wait().await;
                info!("Shutdown signal received");
            }
        } else {
            shutdown_signal.wait().await;
            info!("Shutdown signal received");
        }

        // 6. 停止健康检查监控
        if let Some(monitor) = health_monitor {
            let _ = monitor.stop_tx.send(());
            let _ = monitor.join_handle.await;
        }

        // 7. 停止所有任务
        self.task_manager.stop_all(join_set, shutdown_txs).await;

        info!(service_name = %self.service_name, "Service runtime stopped");
        Ok(())
    }

    /// 运行服务(带服务注册)
    ///
    /// 执行以下步骤:
    /// 1. 启动所有任务
    /// 2. 等待所有任务就绪
    /// 3. 注册服务
    /// 4. 等待关闭信号
    /// 5. 注销服务
    /// 6. 优雅关闭所有任务
    pub async fn run_with_registration<F, Fut>(self, register_fn: F) -> Result<()>
    where
        F: FnOnce(SocketAddr) -> Fut,
        Fut: std::future::Future<
                Output = Result<
                    Option<Box<dyn ServiceRegistry>>,
                    Box<dyn std::error::Error + Send + Sync>,
                >,
            > + Send,
    {
        self.run_with_registration_and_signals(register_fn, vec![])
            .await
    }

    /// 运行服务(带服务注册 + 自定义停机信号)
    ///
    /// 聚合部署进程可注入 [`ChannelSignal`](crate::signal::ChannelSignal),
    /// 让多个注册型服务共享同一个外部生命周期控制。
    pub async fn run_with_registration_and_signals<F, Fut>(
        mut self,
        register_fn: F,
        mut signals: Vec<Box<dyn ShutdownSignal>>,
    ) -> Result<()>
    where
        F: FnOnce(SocketAddr) -> Fut,
        Fut: std::future::Future<
                Output = Result<
                    Option<Box<dyn ServiceRegistry>>,
                    Box<dyn std::error::Error + Send + Sync>,
                >,
            > + Send,
    {
        let service_name = self.service_name.clone();
        let service_address = self.service_address.ok_or_else(|| {
            anyhow::anyhow!(
                "Service address is required for service registration. \
                 Use `with_address()` to set the address."
            )
        })?;

        info!(
            service_name = %service_name,
            address = %service_address,
            task_count = self.task_manager.task_count(),
            "🚀 Starting service runtime with registration"
        );

        // 1. 构建停机信号
        if signals.is_empty() {
            signals.push(Box::new(CtrlCSignal::new()));

            #[cfg(target_family = "unix")]
            signals.push(Box::new(UnixSignal::new(UnixSignalKind::Terminate)));
        }
        let mut shutdown_signal = CompositeSignal::from_signals(signals);

        // 2. 启动所有任务
        let (join_set, shutdown_txs) = self
            .task_manager
            .start_all()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to start tasks: {}", e))?;

        // 3. 等待所有任务就绪
        self.task_manager
            .wait_for_ready()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to wait for tasks ready: {}", e))?;

        // 4. 注册服务
        info!("Registering service...");
        let registry = match register_fn(service_address).await {
            Ok(Some(reg)) => {
                info!("✅ Service registered: {}", service_name);
                Some(reg)
            }
            Ok(None) => {
                info!("Service registration skipped");
                None
            }
            Err(e) => {
                error!(error = %e, "❌ Service registration failed");

                // 停止所有任务
                self.task_manager.stop_all(join_set, shutdown_txs).await;

                return Err(anyhow::anyhow!("Service registration failed: {}", e));
            }
        };

        // 4.1 启动健康检查监控(可选)
        let mut health_monitor = self.start_health_monitor();

        // 5. 等待停机信号或健康检查触发停机
        info!("Waiting for shutdown signal...");
        if let Some(monitor) = health_monitor.as_mut() {
            if let Some(failure_rx) = monitor.failure_rx.as_mut() {
                tokio::select! {
                    _ = shutdown_signal.wait() => {
                        info!("Shutdown signal received");
                    }
                    failed = failure_rx.recv() => {
                        warn!(failed_check = ?failed, "Health check threshold exceeded, triggering graceful shutdown");
                    }
                }
            } else {
                shutdown_signal.wait().await;
                info!("Shutdown signal received");
            }
        } else {
            shutdown_signal.wait().await;
            info!("Shutdown signal received");
        }

        // 5.1 停止健康检查监控
        if let Some(monitor) = health_monitor {
            let _ = monitor.stop_tx.send(());
            let _ = monitor.join_handle.await;
        }

        // 6. 注销服务
        if let Some(mut reg) = registry {
            info!("Deregistering service...");
            if let Err(e) = reg.shutdown().await {
                warn!(error = %e, "⚠️ Failed to deregister service gracefully");
            } else {
                info!("✅ Service deregistered");
            }
        }

        // 7. 停止所有任务
        self.task_manager.stop_all(join_set, shutdown_txs).await;

        info!(service_name = %self.service_name, "Service runtime stopped");
        Ok(())
    }
}

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

    #[test]
    fn test_service_runtime_new() {
        let runtime = ServiceRuntime::new("test-service");
        assert_eq!(runtime.service_name, "test-service");
    }

    #[test]
    fn test_service_runtime_simple() {
        let runtime = ServiceRuntime::simple();
        assert_eq!(runtime.service_name, "simple-runtime");
        assert!(runtime.service_address.is_none());
    }

    #[test]
    fn test_service_runtime_mq_consumer() {
        let runtime = ServiceRuntime::mq_consumer().add_spawn("kafka-consumer", async { Ok(()) });

        assert_eq!(runtime.task_manager.task_count(), 1);
    }

    #[test]
    fn test_service_runtime_tasks() {
        let runtime = ServiceRuntime::tasks()
            .add_spawn("task-1", async { Ok(()) })
            .add_spawn("task-2", async { Ok(()) });

        assert_eq!(runtime.task_manager.task_count(), 2);
    }

    #[test]
    fn test_service_runtime_with_address() {
        let addr: SocketAddr = "0.0.0.0:8080".parse().unwrap();
        let runtime = ServiceRuntime::new("test-service").with_address(addr);

        assert_eq!(runtime.service_address, Some(addr));
    }

    #[test]
    fn test_service_runtime_with_config_updates_task_manager() {
        let config = RuntimeConfig::new().with_shutdown_timeout(Duration::from_millis(25));
        let runtime = ServiceRuntime::new("test-service")
            .add_spawn("task-1", async { Ok(()) })
            .with_config(config);

        assert_eq!(runtime.task_manager.task_count(), 1);
        assert_eq!(
            runtime.task_manager.shutdown_timeout(),
            Duration::from_millis(25)
        );
    }

    #[test]
    fn test_service_runtime_add_spawn() {
        let runtime = ServiceRuntime::new("test-service").add_spawn("task-1", async { Ok(()) });

        assert_eq!(runtime.task_manager.task_count(), 1);
    }

    #[tokio::test]
    async fn run_with_registration_accepts_custom_shutdown_signal() {
        use crate::signal::ChannelSignal;
        use tokio::sync::oneshot;

        let service_address: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let (shutdown_tx, shutdown_rx) = oneshot::channel();
        let runtime = ServiceRuntime::new("test-service")
            .with_address(service_address)
            .add_spawn_with_shutdown("wait-for-shutdown", |shutdown_rx| async move {
                let _ = shutdown_rx.await;
                Ok(())
            });

        let run = runtime.run_with_registration_and_signals(
            |addr| async move {
                assert_eq!(addr, service_address);
                Ok(None)
            },
            vec![Box::new(ChannelSignal::new("test-shutdown", shutdown_rx))],
        );
        let stop = async move {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            shutdown_tx.send(()).unwrap();
        };

        let (result, _) = tokio::join!(run, stop);
        result.unwrap();
    }
}