1use std::sync::Arc;
6
7use anyhow::{Context, Result};
8use folk_api::{Plugin, PluginContext, RpcRegistrar};
9use tokio::sync::watch;
10use tracing::{info, warn};
11
12use crate::config::FolkConfig;
13use crate::health_registry::HealthRegistryImpl;
14use crate::logging;
15use crate::metrics_registry::MetricsRegistryImpl;
16use crate::plugin_registry::PluginRegistry;
17use crate::runtime::Runtime;
18use crate::worker_pool::WorkerPool;
19
20pub struct FolkServer {
22 config: FolkConfig,
23 runtime: Arc<dyn Runtime>,
24 plugins: PluginRegistry,
25 rpc_registrar: Option<Arc<dyn RpcRegistrar>>,
26}
27
28impl FolkServer {
29 pub fn new(config: FolkConfig, runtime: Arc<dyn Runtime>) -> Self {
31 Self {
32 config,
33 runtime,
34 plugins: PluginRegistry::new(),
35 rpc_registrar: None,
36 }
37 }
38
39 pub fn set_rpc_registrar(&mut self, registrar: Arc<dyn RpcRegistrar>) {
42 self.rpc_registrar = Some(registrar);
43 }
44
45 pub fn register_plugin(&mut self, plugin: Box<dyn Plugin>) {
47 self.plugins.register(plugin);
48 }
49
50 pub async fn run(mut self) -> Result<()> {
52 let _ = logging::init(&self.config.log);
53
54 info!(
55 version = folk_api::FOLK_API_VERSION,
56 workers = self.config.workers.count,
57 "folk server starting"
58 );
59
60 let (shutdown_tx, shutdown_rx) = watch::channel(false);
61
62 let health_registry = HealthRegistryImpl::new();
63 let metrics_registry = MetricsRegistryImpl::new();
64
65 if self.config.workers.warmup {
66 match self.runtime.warmup().await {
67 Ok(()) => {},
68 Err(e) => warn!(error = %e, "opcache warmup failed, skipping"),
69 }
70 }
71
72 let pool = WorkerPool::new(self.runtime.clone(), self.config.workers.clone())
73 .context("failed to start worker pool")?;
74
75 info!("worker pool started");
76
77 let ctx = PluginContext {
78 executor: pool.clone(),
79 shutdown: shutdown_rx.clone(),
80 rpc_registrar: self.rpc_registrar.clone(),
81 health_registry: Some(health_registry.clone()),
82 metrics_registry: Some(metrics_registry.clone()),
83 };
84
85 self.plugins
86 .boot_all(&ctx)
87 .await
88 .context("plugin boot failed")?;
89
90 info!(plugins = ?self.plugins.names(), "all plugins booted");
91
92 wait_for_signal().await;
94 info!("shutdown signal received; draining");
95
96 let _ = shutdown_tx.send(true);
97
98 let timeout = self.config.server.shutdown_timeout;
99 let shutdown_result =
100 tokio::time::timeout(timeout, async { self.plugins.shutdown_all().await }).await;
101
102 if shutdown_result.is_err() {
103 warn!(?timeout, "graceful shutdown timed out; forcing");
104 }
105
106 info!("folk server stopped");
107 Ok(())
108 }
109}
110
111#[cfg(not(target_os = "windows"))]
112async fn wait_for_signal() {
113 use tokio::signal::unix::{SignalKind, signal};
114 let mut sigterm = signal(SignalKind::terminate()).expect("SIGTERM handler");
115 let mut sigint = signal(SignalKind::interrupt()).expect("SIGINT handler");
116 tokio::select! {
117 _ = sigterm.recv() => { info!("received SIGTERM"); },
118 _ = sigint.recv() => { info!("received SIGINT"); },
119 }
120}
121
122#[cfg(target_os = "windows")]
123async fn wait_for_signal() {
124 tokio::signal::ctrl_c().await.expect("ctrl-c");
125}