Skip to main content

arcly_http/core/
plugins.rs

1//! Third-party plugin ecosystem.
2//!
3//! A plugin owns a corner of the framework's behaviour without forking the
4//! core crate: register global routes, mutate the OpenAPI spec, attach
5//! global interceptors, spawn background tasks under graceful shutdown.
6//!
7//! ## Object safety
8//!
9//! `ArclyPlugin` uses the *erased-type* pattern: each lifecycle hook returns
10//! a `BoxFuture` instead of `async fn`, so the trait stays object-safe and
11//! we can hold `Vec<Box<dyn ArclyPlugin>>`.
12//!
13//! ## Opaque context
14//!
15//! `ArclyPluginContext` exposes a small, framework-typed API for the things
16//! plugins legitimately need to do. Axum / Tower types are private; the
17//! public methods all speak in arcly types (`RequestContext`, `Response`).
18//!
19//! ## Deferred construction
20//!
21//! Plugins register *handler factories* rather than routes directly. At
22//! launch time, once the frozen DI container exists, `App::launch` invokes
23//! each factory with the real `&'static FrozenDiContainer` and mounts the
24//! resulting axum route. This sidesteps any unsoundness from materialising
25//! the container before it's built.
26
27use std::fmt;
28
29use futures::future::BoxFuture;
30
31use crate::http::Response;
32
33use crate::core::engine::{FrozenDiContainer, HttpMethod};
34use crate::web::context::RequestContext;
35
36// ─── Errors ─────────────────────────────────────────────────────────────
37
38#[derive(Debug)]
39pub struct PluginError {
40    pub plugin: &'static str,
41    pub stage: PluginStage,
42    pub source: Box<dyn std::error::Error + Send + Sync>,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum PluginStage {
47    Init,
48    Start,
49    Shutdown,
50}
51
52impl PluginError {
53    pub fn new<E: Into<Box<dyn std::error::Error + Send + Sync>>>(
54        plugin: &'static str,
55        stage: PluginStage,
56        source: E,
57    ) -> Self {
58        Self {
59            plugin,
60            stage,
61            source: source.into(),
62        }
63    }
64}
65
66impl fmt::Display for PluginError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        write!(
69            f,
70            "plugin `{}` failed at {:?}: {}",
71            self.plugin, self.stage, self.source
72        )
73    }
74}
75impl std::error::Error for PluginError {}
76
77// ─── The trait ──────────────────────────────────────────────────────────
78
79/// Plugin lifecycle.
80///
81/// All three hooks receive the framework's frozen DI container as a
82/// `&'static` ref (after init completes), so background tasks and shutdown
83/// drain routines can resolve injected services with zero locks. The init
84/// hook receives the *mutable* `ArclyPluginContext`, through which the
85/// plugin can `provide<T>` new singletons into the container before it
86/// freezes.
87pub trait ArclyPlugin: Send + Sync + 'static {
88    fn name(&self) -> &'static str;
89
90    /// **Pre-bind.** Register providers, routes, interceptors, openapi mutators.
91    /// The container is built AFTER every plugin's `on_init` returns.
92    fn on_init<'a>(
93        &'a mut self,
94        ctx: &'a mut ArclyPluginContext,
95    ) -> BoxFuture<'a, Result<(), PluginError>> {
96        let _ = ctx;
97        Box::pin(async { Ok(()) })
98    }
99
100    /// **Drain started.** Fired as soon as a shutdown signal is received,
101    /// *concurrently* with the HTTP in-flight drain (it does not delay the
102    /// listener closing). Stop accepting new work here — pause message-queue
103    /// consumers, schedulers, pollers — so plugin workloads quiesce while
104    /// HTTP connections drain. Cleanup itself belongs in `on_shutdown`.
105    fn on_draining<'a>(
106        &'a self,
107        container: &'static FrozenDiContainer,
108    ) -> BoxFuture<'a, Result<(), PluginError>> {
109        let _ = container;
110        Box::pin(async { Ok(()) })
111    }
112
113    /// **Post-bind.** Listener is live and accepting. Background tasks spawn
114    /// here. `container` resolves any provider — including ones the plugin
115    /// itself registered in `on_init`.
116    fn on_start<'a>(
117        &'a self,
118        container: &'static FrozenDiContainer,
119    ) -> BoxFuture<'a, Result<(), PluginError>> {
120        let _ = container;
121        Box::pin(async { Ok(()) })
122    }
123
124    /// **Graceful shutdown.** Invoked **after** the HTTP server has stopped
125    /// accepting new connections and all in-flight requests have drained.
126    /// Wrapped by `App` in a per-plugin timeout (default 5s, configurable
127    /// via `LaunchConfig::drain_budget`) so a hung plugin can never wedge
128    /// the process or starve other plugins' shutdown.
129    ///
130    /// **Do not block.** The timeout can only cancel the future at an
131    /// `.await` point — a synchronous spin or blocking syscall here pins a
132    /// runtime worker thread until it returns. Use `spawn_blocking` for
133    /// unavoidable blocking cleanup.
134    fn on_shutdown<'a>(
135        &'a self,
136        container: &'static FrozenDiContainer,
137    ) -> BoxFuture<'a, Result<(), PluginError>> {
138        let _ = container;
139        Box::pin(async { Ok(()) })
140    }
141}
142
143// ─── Handler factory + context ─────────────────────────────────────────
144
145/// A typed handler usable from plugin-registered routes. Takes a
146/// `RequestContext`, returns a `Response`.
147pub type PluginHandler =
148    std::sync::Arc<dyn Fn(RequestContext) -> BoxFuture<'static, Response> + Send + Sync>;
149
150#[doc(hidden)]
151pub struct PluginRoute {
152    pub method: HttpMethod,
153    pub path: &'static str,
154    pub handler: PluginHandler,
155    /// Name of the plugin that registered this route. Filled in by the
156    /// launch path after each `on_init` returns; used in collision errors.
157    pub plugin: &'static str,
158}
159
160/// Mutable handle plugins receive during `on_init`.
161///
162/// `provide<T>` queues a singleton for the DI container, applied just before
163/// the container freezes. Once frozen the container is `&'static` and
164/// reads are lock-free for the lifetime of the process.
165pub(crate) type OpenApiMutator = Box<dyn FnOnce(&mut serde_json::Value) + Send + Sync>;
166pub(crate) type PendingProvider =
167    Box<dyn FnOnce(&mut crate::core::engine::DiContainerBuilder) + Send>;
168
169pub struct ArclyPluginContext {
170    pub(crate) extra_routes: Vec<PluginRoute>,
171    pub(crate) openapi_mutators: Vec<OpenApiMutator>,
172    pub(crate) global_interceptors: Vec<&'static dyn crate::web::interceptors::Interceptor>,
173    pub(crate) boundary_filters: Vec<&'static dyn crate::web::boundary::BoundaryFilter>,
174    pub(crate) pending_providers: Vec<PendingProvider>,
175    /// Name of the plugin whose `on_init` is currently running. Set by the
176    /// launch loop so errors raised through the context name the right plugin.
177    pub(crate) current_plugin: &'static str,
178}
179
180impl ArclyPluginContext {
181    #[doc(hidden)]
182    pub fn new() -> Self {
183        Self {
184            extra_routes: Vec::new(),
185            openapi_mutators: Vec::new(),
186            global_interceptors: Vec::new(),
187            boundary_filters: Vec::new(),
188            pending_providers: Vec::new(),
189            current_plugin: "ArclyPluginContext",
190        }
191    }
192
193    /// Inject a singleton of type `T` into the DI container. Resolves later
194    /// via `Inject<T>` in any controller / service / interceptor.
195    ///
196    /// Order: every plugin's `on_init` runs first, then all `provide<T>`
197    /// closures are applied in declaration order, *then* the container
198    /// freezes. So one plugin can read another's provision in `on_start`
199    /// but not in `on_init`.
200    ///
201    /// If `T` already has an `#[Injectable]` provider, launch fails loudly —
202    /// use [`override_provider`](Self::override_provider) to replace it
203    /// intentionally.
204    pub fn provide<T: Send + Sync + 'static>(&mut self, value: T) {
205        self.pending_providers.push(Box::new(move |b| {
206            b.register(value);
207        }));
208    }
209
210    /// Replace a core `#[Injectable]` provider with this instance. The
211    /// descriptor is discarded; every `Inject<T>` in the app resolves to the
212    /// plugin's value. Happens before the container freezes, so the swap is
213    /// race-free and the hot path stays lock-free.
214    pub fn override_provider<T: Send + Sync + 'static>(&mut self, value: T) {
215        self.pending_providers.push(Box::new(move |b| {
216            b.register_override(value);
217        }));
218    }
219
220    /// Attach a boundary filter that runs on **every** request *before the
221    /// body is read* — the cheap early-reject point for signature checks,
222    /// IP allowlists, and rate limits. Returning `Break(resp)` short-circuits
223    /// without paying for body buffering or context assembly.
224    /// Ergonomic twin of [`Self::register_global_interceptor`]: takes ownership
225    /// and leaks internally (interceptors are process-lifetime objects) —
226    /// no `Box::leak` ceremony in plugin code.
227    pub fn add_interceptor(&mut self, ic: impl crate::web::interceptors::Interceptor) {
228        self.global_interceptors.push(Box::leak(Box::new(ic)));
229    }
230
231    /// Ergonomic twin of [`Self::register_boundary_filter`]: takes ownership and
232    /// leaks internally.
233    pub fn add_boundary_filter(&mut self, f: impl crate::web::boundary::BoundaryFilter) {
234        self.boundary_filters.push(Box::leak(Box::new(f)));
235    }
236
237    pub fn register_boundary_filter(
238        &mut self,
239        f: &'static dyn crate::web::boundary::BoundaryFilter,
240    ) {
241        self.boundary_filters.push(f);
242    }
243
244    /// Register a route. The handler receives a fully-built `RequestContext`
245    /// — including DI access via `ctx.inject::<T>()` — and returns a
246    /// `Response`. The path is mounted verbatim under the application root.
247    ///
248    /// The path may be built at runtime (e.g. a config-driven prefix); it is
249    /// leaked to `&'static str`, which is fine because routes live for the
250    /// whole process anyway.
251    pub fn add_route<F, Fut>(&mut self, method: HttpMethod, path: impl Into<String>, handler: F)
252    where
253        F: Fn(RequestContext) -> Fut + Send + Sync + 'static,
254        Fut: std::future::Future<Output = Response> + Send + 'static,
255    {
256        let arc: PluginHandler = std::sync::Arc::new(move |ctx| Box::pin(handler(ctx)));
257        self.extra_routes.push(PluginRoute {
258            method,
259            path: Box::leak(path.into().into_boxed_str()),
260            handler: arc,
261            plugin: self.current_plugin,
262        });
263    }
264
265    /// Shortcut: register a GET.
266    pub fn add_get<F, Fut>(&mut self, path: impl Into<String>, handler: F)
267    where
268        F: Fn(RequestContext) -> Fut + Send + Sync + 'static,
269        Fut: std::future::Future<Output = Response> + Send + 'static,
270    {
271        self.add_route(HttpMethod::GET, path, handler);
272    }
273
274    /// Mutate the assembled OpenAPI document at launch time.
275    pub fn modify_openapi<F>(&mut self, f: F)
276    where
277        F: FnOnce(&mut serde_json::Value) + Send + Sync + 'static,
278    {
279        self.openapi_mutators.push(Box::new(f));
280    }
281
282    /// Read a required environment variable.
283    ///
284    /// Returns `Err(PluginError)` with stage `Init` if the variable is absent
285    /// or contains non-UTF-8 bytes, so callers can propagate it cleanly with `?`.
286    pub fn require_env(&self, key: &str) -> Result<String, PluginError> {
287        std::env::var(key).map_err(|_| {
288            PluginError::new(
289                self.current_plugin,
290                PluginStage::Init,
291                format!("required env var `{key}` is missing or not valid UTF-8"),
292            )
293        })
294    }
295
296    /// Read an environment variable with a fallback default.
297    pub fn env_or(&self, key: &str, default: impl Into<String>) -> String {
298        std::env::var(key).unwrap_or_else(|_| default.into())
299    }
300
301    /// Attach an interceptor that fires on **every** mounted route — macro
302    /// routes and plugin-registered routes alike. Global interceptors compose
303    /// as the outermost layers, in registration order (first registered =
304    /// outermost), around any per-route `#[UseInterceptors]` chain.
305    pub fn register_global_interceptor(
306        &mut self,
307        ic: &'static dyn crate::web::interceptors::Interceptor,
308    ) {
309        self.global_interceptors.push(ic);
310    }
311}
312
313impl Default for ArclyPluginContext {
314    fn default() -> Self {
315        Self::new()
316    }
317}
318
319// Route mounting moved to `crate::web::plugin_routes` so this module stays
320// HTTP-agnostic. Re-exported here to keep the existing import path working.
321pub use crate::web::plugin_routes::build_plugin_route;