Skip to main content

folk_api/
server_plugin.rs

1//! `ServerPlugin` helper trait for the common case: a plugin that runs one
2//! long-lived background task (HTTP server, queue consumer, etc.) and shuts
3//! down when the server signals shutdown.
4//!
5//! Most plugins should implement [`ServerPlugin`] rather than [`Plugin`]
6//! directly, then wrap with [`ServerPluginWrapper`].
7
8use std::sync::{Arc, Mutex};
9
10use anyhow::Result;
11use async_trait::async_trait;
12use tokio::task::JoinHandle;
13use tracing::{error, info, warn};
14
15use crate::context::PluginContext;
16use crate::plugin::Plugin;
17use crate::role::Placement;
18use crate::rpc::RpcMethodDef;
19
20/// Trait for plugins that run a single long-lived background task.
21/// The `run` future should observe `ctx.shutdown` and return when signaled.
22#[async_trait]
23pub trait ServerPlugin: Send + Sync + 'static {
24    /// Stable plugin name (same semantics as [`Plugin::name`]).
25    fn name(&self) -> &'static str;
26
27    /// Run the plugin's main loop. Return `Ok(())` on shutdown.
28    ///
29    /// Observe `ctx.shutdown` to detect the server shutdown signal.
30    /// Do **not** discard `watch::RecvError` with `.ok()` — treat it as an
31    /// unexpected condition (the sender was dropped without signaling shutdown)
32    /// and log an error:
33    ///
34    /// ```ignore
35    /// if let Err(e) = ctx.shutdown.changed().await {
36    ///     tracing::error!(error = %e, "shutdown sender dropped unexpectedly");
37    /// }
38    /// ```
39    async fn run(&self, ctx: PluginContext) -> Result<()>;
40
41    /// Optional RPC method advertisements (default empty).
42    fn rpc_methods(&self) -> Vec<RpcMethodDef> {
43        Vec::new()
44    }
45
46    /// Where this plugin runs in the fork-after-warm model (phase 79).
47    /// Default [`Placement::WorkerOnly`]; see [`Plugin::placement`].
48    ///
49    /// [`Plugin::placement`]: crate::Plugin::placement
50    fn placement(&self) -> Placement {
51        Placement::WorkerOnly
52    }
53}
54
55/// Wraps a [`ServerPlugin`] so it can be used as a [`Plugin`].
56/// Spawns `run` at boot, awaits the task during shutdown.
57pub struct ServerPluginWrapper<S: ServerPlugin> {
58    inner: Arc<S>,
59    handle: Mutex<Option<JoinHandle<Result<()>>>>,
60}
61
62impl<S: ServerPlugin> ServerPluginWrapper<S> {
63    pub fn new(inner: S) -> Self {
64        Self {
65            inner: Arc::new(inner),
66            handle: Mutex::new(None),
67        }
68    }
69}
70
71#[async_trait]
72impl<S: ServerPlugin> Plugin for ServerPluginWrapper<S> {
73    fn name(&self) -> &'static str {
74        self.inner.name()
75    }
76
77    async fn boot(&mut self, ctx: PluginContext) -> Result<()> {
78        let mut slot = self.handle.lock().expect("mutex");
79        if slot.is_some() {
80            return Err(anyhow::anyhow!(
81                "plugin '{}' is already running; boot() called twice",
82                self.inner.name()
83            ));
84        }
85        let inner = self.inner.clone();
86        let handle = tokio::spawn(async move { inner.run(ctx).await });
87        *slot = Some(handle);
88        info!(plugin = self.inner.name(), "server plugin booted");
89        Ok(())
90    }
91
92    async fn shutdown(&self) -> Result<()> {
93        let handle = {
94            let mut slot = self
95                .handle
96                .lock()
97                .map_err(|_| anyhow::anyhow!("ServerPluginWrapper handle mutex poisoned"))?;
98            slot.take()
99        };
100
101        let Some(handle) = handle else {
102            warn!(
103                plugin = self.inner.name(),
104                "shutdown called but no handle present"
105            );
106            return Ok(());
107        };
108
109        // Abort ensures the task stops even if it is not observing ctx.shutdown.
110        // The shutdown signal was already broadcast before shutdown() is called,
111        // so cooperative tasks have had a chance to react; abort() is the fallback.
112        // Without this, a stuck task causes handle.await to deadlock forever.
113        handle.abort();
114
115        match handle.await {
116            Ok(Ok(())) => {
117                info!(plugin = self.inner.name(), "run loop completed cleanly");
118                Ok(())
119            }
120            Ok(Err(err)) => {
121                error!(plugin = self.inner.name(), error = ?err, "run loop returned error (shutdown continues)");
122                Ok(())
123            }
124            Err(join_err) if join_err.is_cancelled() => {
125                info!(
126                    plugin = self.inner.name(),
127                    "run loop cancelled during shutdown"
128                );
129                Ok(())
130            }
131            Err(join_err) => {
132                error!(plugin = self.inner.name(), error = %join_err, "run loop panicked (shutdown continues)");
133                Ok(())
134            }
135        }
136    }
137
138    fn rpc_methods(&self) -> Vec<RpcMethodDef> {
139        self.inner.rpc_methods()
140    }
141
142    fn placement(&self) -> Placement {
143        self.inner.placement()
144    }
145}