#graceful-shutdown #process #signal #runnable #fault #async-trait #async-stream

processmanager

管理进程生命周期、优雅关闭和进程故障

1 个不稳定版本

0.1.0 2024年3月27日

#1271Rust 模式

MIT 许可证

15KB
260

ProcessManager

管理多个运行中的服务。ProcessManager 收集 Runnable 的实现,并接管运行时管理,如启动、停止(优雅或失败)服务。

如果一个服务失败,管理器将为其他所有服务启动优雅关闭。

示例

use processmanager::*;

#[tokio::main]
async fn main() {

    #[derive(Default)]
    struct ExampleController {
        runtime_guard: RuntimeGuard,
    }

    #[async_trait::async_trait]
    impl Runnable for ExampleController {
        async fn process_start(&self) -> Result<(), RuntimeError> {
            // This can be any type of future like an async streams
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));

            loop {
                match self.runtime_guard.tick(interval.tick()).await {
                    ProcessOperation::Next(_) => println!("work"),
                    ProcessOperation::Control(RuntimeControlMessage::Shutdown) => {
                        println!("shutdown"); 
                        break
                    },
                    ProcessOperation::Control(RuntimeControlMessage::Reload) => println!("trigger relead"),
                }
            }

            Ok(())
        }

        fn process_handle(&self) -> Box<dyn ProcessControlHandler> {
            Box::new(self.runtime_guard.handle())
         }
    }

    let mut manager = ProcessManager::new();
    manager.insert(SignalReceiver::default());
    manager.insert(ExampleController::default());

    let handle = manager.process_handle();

    // start all processes
    let _ = tokio::spawn(async move {
        manager.process_start().await.expect("service start failed");
    });

    // Shutdown waits for all services to shutdown gracefully.
    handle.shutdown().await;
}

依赖项

~4–13MB
~135K SLoC