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    /// Whether this plugin must be booted in every worker pool (phase 85).
55    /// Default `false`; see [`Plugin::runs_in_every_pool`].
56    ///
57    /// [`Plugin::runs_in_every_pool`]: crate::Plugin::runs_in_every_pool
58    fn runs_in_every_pool(&self) -> bool {
59        false
60    }
61}
62
63/// Wraps a [`ServerPlugin`] so it can be used as a [`Plugin`].
64/// Spawns `run` at boot, awaits the task during shutdown.
65pub struct ServerPluginWrapper<S: ServerPlugin> {
66    inner: Arc<S>,
67    handle: Mutex<Option<JoinHandle<Result<()>>>>,
68}
69
70impl<S: ServerPlugin> ServerPluginWrapper<S> {
71    pub fn new(inner: S) -> Self {
72        Self {
73            inner: Arc::new(inner),
74            handle: Mutex::new(None),
75        }
76    }
77}
78
79#[async_trait]
80impl<S: ServerPlugin> Plugin for ServerPluginWrapper<S> {
81    fn name(&self) -> &'static str {
82        self.inner.name()
83    }
84
85    async fn boot(&mut self, ctx: PluginContext) -> Result<()> {
86        let mut slot = self.handle.lock().expect("mutex");
87        if slot.is_some() {
88            return Err(anyhow::anyhow!(
89                "plugin '{}' is already running; boot() called twice",
90                self.inner.name()
91            ));
92        }
93        let inner = self.inner.clone();
94        let handle = tokio::spawn(async move { inner.run(ctx).await });
95        *slot = Some(handle);
96        info!(plugin = self.inner.name(), "server plugin booted");
97        Ok(())
98    }
99
100    async fn shutdown(&self) -> Result<()> {
101        let handle = {
102            let mut slot = self
103                .handle
104                .lock()
105                .map_err(|_| anyhow::anyhow!("ServerPluginWrapper handle mutex poisoned"))?;
106            slot.take()
107        };
108
109        let Some(handle) = handle else {
110            warn!(
111                plugin = self.inner.name(),
112                "shutdown called but no handle present"
113            );
114            return Ok(());
115        };
116
117        // Abort ensures the task stops even if it is not observing ctx.shutdown.
118        // The shutdown signal was already broadcast before shutdown() is called,
119        // so cooperative tasks have had a chance to react; abort() is the fallback.
120        // Without this, a stuck task causes handle.await to deadlock forever.
121        handle.abort();
122
123        match handle.await {
124            Ok(Ok(())) => {
125                info!(plugin = self.inner.name(), "run loop completed cleanly");
126                Ok(())
127            }
128            Ok(Err(err)) => {
129                error!(plugin = self.inner.name(), error = ?err, "run loop returned error (shutdown continues)");
130                Ok(())
131            }
132            Err(join_err) if join_err.is_cancelled() => {
133                info!(
134                    plugin = self.inner.name(),
135                    "run loop cancelled during shutdown"
136                );
137                Ok(())
138            }
139            Err(join_err) => {
140                error!(plugin = self.inner.name(), error = %join_err, "run loop panicked (shutdown continues)");
141                Ok(())
142            }
143        }
144    }
145
146    fn rpc_methods(&self) -> Vec<RpcMethodDef> {
147        self.inner.rpc_methods()
148    }
149
150    fn placement(&self) -> Placement {
151        self.inner.placement()
152    }
153
154    fn runs_in_every_pool(&self) -> bool {
155        self.inner.runs_in_every_pool()
156    }
157}