umbral_core/plugin.rs
1//! The Plugin trait — umbral's only extension mechanism.
2//!
3//! Auth, sessions, admin, tasks, REST, and OpenAPI are all plugins; so
4//! is every third-party crate that ships models, routes, or commands.
5//! This module defines the contract, the `AppContext` plugins receive,
6//! and the `BuildError` variants topological-sort issues surface as.
7//!
8//! See `docs/specs/02-plugin-contract.md` for the eventual target
9//! shape; this file ships the M7 v1 subset (no middleware, no commands,
10//! no inventory auto-registration).
11//!
12//! ## The trait
13//!
14//! ```ignore
15//! use umbral::prelude::*;
16//!
17//! pub struct BlogPlugin;
18//!
19//! impl Plugin for BlogPlugin {
20//! fn name(&self) -> &'static str { "blog" }
21//!
22//! fn dependencies(&self) -> &'static [&'static str] { &["auth"] }
23//!
24//! fn models(&self) -> Vec<umbral::migrate::ModelMeta> {
25//! vec![umbral::migrate::ModelMeta::for_::<Post>()]
26//! }
27//!
28//! fn routes(&self) -> Router {
29//! Router::new().route("/posts", get(list))
30//! }
31//! }
32//! ```
33//!
34//! `AppBuilder::plugin(BlogPlugin)` registers it; `App::build()`
35//! topologically sorts the registered plugins, walks every plugin's
36//! routes / models / system_checks, and fires `on_ready` in dependency
37//! order.
38
39use std::path::PathBuf;
40
41use crate::db::DbPool;
42use axum::Router;
43
44use crate::check::SystemCheck;
45use crate::migrate::ModelMeta;
46use crate::settings::Settings;
47
48/// Run an async future to completion from inside a synchronous
49/// `Plugin::on_ready` implementation.
50///
51/// `Plugin::on_ready` is a sync trait method (the trait has to be
52/// object-safe for `Vec<Box<dyn Plugin>>`), but most real-world async
53/// work — schema DDL via sqlx, policy setup, initial seeding — needs
54/// to await. This helper bridges that gap safely under every runtime
55/// configuration that umbral encounters in practice:
56///
57/// | Caller context | Bridge used |
58/// |---|---|
59/// | Multi-thread tokio runtime (`#[tokio::main]`, prod binaries) | `tokio::task::block_in_place` + `Handle::block_on` — parks the OS thread, doesn't block the executor |
60/// | Current-thread tokio runtime (`#[tokio::test]` default) | Spawns a dedicated OS thread with its own `Runtime`; `block_in_place` would panic here |
61/// | No ambient runtime (bare `main`, exotic callers) | Creates a temporary `Runtime` and `block_on`s |
62///
63/// ## Why not just `Handle::current().block_on(fut)`?
64///
65/// `block_on` on a `Handle` panics when called from within a
66/// current-thread runtime (which is the default for `#[tokio::test]`).
67/// The multi-thread path requires `block_in_place` to hand control
68/// back to the executor; the current-thread path requires moving to a
69/// different OS thread entirely.
70///
71/// ## Usage
72///
73/// ```rust,ignore
74/// fn on_ready(&self, ctx: &AppContext) -> Result<(), PluginError> {
75/// umbral::plugin::block_on_ready(self.do_async_setup(&ctx.pool))?;
76/// Ok(())
77/// }
78/// ```
79pub fn block_on_ready<F>(fut: F) -> F::Output
80where
81 F: std::future::Future + Send,
82 F::Output: Send,
83{
84 match tokio::runtime::Handle::try_current() {
85 Ok(handle) => {
86 // We are inside a tokio runtime. The safe bridging path
87 // depends on the runtime flavor:
88 //
89 // - Multi-thread: `block_in_place` parks the current OS
90 // thread and yields it to the executor so other tasks
91 // keep running. The `Handle::block_on` call inside then
92 // drives the future to completion on that parked thread.
93 //
94 // - Current-thread: `block_in_place` panics because a
95 // single-threaded executor can't lend the thread to sync
96 // work while simultaneously needing it to drive the
97 // reactor. The only safe path is to escape to a new OS
98 // thread. We use `std::thread::scope` (stable since
99 // Rust 1.63, our MSRV is 1.85) so non-`'static`
100 // borrows from the call frame can cross the thread
101 // boundary safely — the scope join guarantees the
102 // spawned thread exits before the frame does.
103 if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread {
104 tokio::task::block_in_place(|| handle.block_on(fut))
105 } else {
106 // Current-thread (or unknown flavor): escape to a
107 // scoped thread with its own single-thread runtime.
108 std::thread::scope(|s| {
109 s.spawn(|| {
110 tokio::runtime::Builder::new_current_thread()
111 .enable_all()
112 .build()
113 .expect("block_on_ready: failed to build current-thread runtime")
114 .block_on(fut)
115 })
116 .join()
117 .expect("block_on_ready: scoped thread panicked")
118 })
119 }
120 }
121 Err(_) => {
122 // No ambient runtime. Build a temporary one for this call.
123 tokio::runtime::Builder::new_current_thread()
124 .enable_all()
125 .build()
126 .expect("block_on_ready: failed to build runtime")
127 .block_on(fut)
128 }
129 }
130}
131
132/// The contract every umbral extension implements.
133///
134/// Every method except `name()` has a default that returns the empty
135/// contribution. A plugin opts in only to what it contributes: a
136/// pure-route plugin overrides `routes()`; a pure-data plugin
137/// overrides `models()`; the auth plugin overrides almost all of them.
138///
139/// The trait is `Send + Sync + 'static` so `App::builder()` can store a
140/// homogeneous `Vec<Box<dyn Plugin>>` and the runtime can hand the
141/// plugin reference to threads (e.g. for background tasks spawned in
142/// `on_ready`). The bounds are deliberately permissive: any
143/// reasonable Rust struct meets them by default.
144pub trait Plugin: Send + Sync + 'static {
145 /// A stable identifier. Used as the key in the migration tracking
146 /// table, in dependency lists, and as the directory name under
147 /// `migrations/`. Plugin names live in the same namespace as
148 /// `migrate::APP_PLUGIN_NAME` (`"app"`), so user crates must not
149 /// pick the name `"app"`.
150 fn name(&self) -> &'static str;
151
152 /// Names of plugins that must load before this one. The
153 /// `App::builder()` topological sort uses this; cycles surface as
154 /// `BuildError::PluginCycle`. The default is no dependencies.
155 fn dependencies(&self) -> &'static [&'static str] {
156 &[]
157 }
158
159 /// The plugin's models, in declaration order. The M7 migration
160 /// engine collects these across every registered plugin and uses
161 /// them as the diff target for `makemigrations`.
162 ///
163 /// Default: no models. A pure-route or pure-middleware plugin
164 /// leaves this alone.
165 fn models(&self) -> Vec<ModelMeta> {
166 Vec::new()
167 }
168
169 /// The plugin's HTTP routes. Merged into the app router after the
170 /// hand-written one passed to `AppBuilder::routes()`. Plugins
171 /// choose their own path prefixes (spec 02 §"What a plugin can
172 /// contribute": routes are flat, not auto-prefixed).
173 fn routes(&self) -> Router {
174 Router::new()
175 }
176
177 /// Declared URL routes this plugin contributes — a companion to
178 /// [`routes`] used for surfacing route lists outside the request
179 /// flow (currently: the dev-mode default 404 page). axum doesn't
180 /// expose its internal route table, so plugins report what they
181 /// declare here; the framework treats this as informational only
182 /// — not a source of truth for routing.
183 ///
184 /// Each entry carries a path pattern and the HTTP methods it
185 /// accepts; the dev-mode 404 page renders method badges so a
186 /// developer can tell at a glance which verb to use. Conversions
187 /// (see [`RouteSpec`]'s `From` impls) cover the ergonomic shapes:
188 /// `"/admin/login".into()`, `("GET", "/articles").into()`,
189 /// `(&["GET", "POST"][..], "/api/post").into()`.
190 ///
191 /// Default empty. Mismatch with the real `routes()` is a stale-
192 /// list bug, not a correctness bug.
193 ///
194 /// [`routes`]: Plugin::routes
195 /// [`RouteSpec`]: crate::routes::RouteSpec
196 fn route_paths(&self) -> Vec<crate::routes::RouteSpec> {
197 Vec::new()
198 }
199
200 /// OpenAPI path items the plugin contributes. Returned as a
201 /// `Vec<(path, value)>` where `path` is the URL template
202 /// (`/api/auth/login`, `/api/foo/{id}`) and `value` is the
203 /// matching OpenAPI 3.0 [Path Item Object][1] serialised as
204 /// a `serde_json::Value`.
205 ///
206 /// [`umbral-openapi`] walks every registered plugin's
207 /// contribution at spec-build time and merges them into the
208 /// emitted document's `paths` object. Closes BUG-20 from
209 /// `bugs/tests/testBugs.md` — auto-generated CRUD routes were
210 /// the only thing the spec described before; plugin-
211 /// contributed routes (auth, custom actions) were invisible
212 /// to Swagger UI.
213 ///
214 /// Plugins that don't ship OpenAPI documentation leave this
215 /// alone. The umbral-openapi plugin's own routes (the
216 /// `/openapi.json` and Swagger UI mount) are not in the
217 /// generated spec — they're delivery, not API.
218 ///
219 /// [1]: https://spec.openapis.org/oas/v3.0.3#path-item-object
220 /// [`umbral-openapi`]: https://docs.rs/umbral-openapi
221 fn openapi_paths(&self) -> Vec<(String, serde_json::Value)> {
222 Vec::new()
223 }
224
225 /// Boot-time checks the plugin needs to pass. Run in phase 4 of
226 /// `App::build()` alongside the framework's built-in checks.
227 /// `Severity::Error` blocks boot; `Severity::Warning` logs and
228 /// continues.
229 fn system_checks(&self) -> Vec<SystemCheck> {
230 Vec::new()
231 }
232
233 /// `true` if this plugin registers a [`Storage`](crate::storage::Storage)
234 /// backend (e.g. `StoragePlugin`, which calls
235 /// [`crate::storage::set_storage`] in [`Plugin::on_ready`]).
236 ///
237 /// The boot system check `field.storage_backend` reads this flag to
238 /// decide whether a model that declares a `FileField` / `ImageField`
239 /// has somewhere to resolve its uploads. It checks the *capability
240 /// flag* rather than the ambient `storage_opt()` because storage is
241 /// registered in `on_ready`, which runs *after* the system-check
242 /// phase — at check time the ambient backend isn't published yet, but
243 /// the declared capability is knowable from the plugin list. Override
244 /// this (return `true`) in any plugin whose `on_ready` registers a
245 /// backend.
246 fn provides_storage(&self) -> bool {
247 false
248 }
249
250 /// The database alias every model this plugin contributes should
251 /// be read from and written to. Returns `None` to use the
252 /// `"default"` pool (the same one `umbral::db::pool()` returns).
253 ///
254 /// This is umbral's per-plugin database routing hook. The
255 /// builder reads it during phase 3 and the QuerySet's
256 /// `resolve_pool` defers to it when no `.on(&pool)` override is
257 /// set on the chain. Per-plugin granularity (every model the
258 /// plugin owns goes to one database) is the v1 shape; per-model
259 /// overrides via attribute lands when a real workload needs it.
260 ///
261 /// The named alias must have been registered via
262 /// `AppBuilder::database(alias, pool)` before `App::build()`. A
263 /// reference to an unregistered alias surfaces as
264 /// `BuildError::PluginDatabaseAlias` at boot.
265 ///
266 /// Note: `Settings.databases[alias]` does **not** register a pool on
267 /// its own today — it is parsed config, but nothing opens a pool from
268 /// it (audit_2 core-app-config #4). Open the pool yourself
269 /// (`umbral::db::connect(&url).await?`) and pass it to
270 /// `AppBuilder::database(alias, pool)`.
271 fn database(&self) -> Option<&'static str> {
272 None
273 }
274
275 /// Template directories this plugin contributes.
276 ///
277 /// Each path is added to the global template search list in plugin
278 /// registration order. The app-level `templates_dir` (set via
279 /// `AppBuilder::templates_dir`) is always searched first; plugin
280 /// directories follow in topological dependency order so a plugin
281 /// with no dependencies appears before its dependents.
282 ///
283 /// When two plugins (or the app directory and a plugin) ship a
284 /// template with the same name, the first directory in the list wins
285 /// and a tracing warning is emitted at boot so the collision is
286 /// visible. First-match-wins across all template directories.
287 ///
288 /// Default: no directories. A plugin that renders no HTML leaves
289 /// this alone.
290 fn templates_dirs(&self) -> Vec<PathBuf> {
291 Vec::new()
292 }
293
294 /// Custom template tags / filters this plugin contributes
295 /// (feature #67 - a loadable template tag/filter library).
296 ///
297 /// Each returned [`TemplateRegistrar`] is a closure that mutates the
298 /// minijinja [`Environment`](minijinja::Environment) at engine-build
299 /// time — `env.add_filter(...)`, `env.add_function(...)`,
300 /// `env.add_global(...)`. They are collected across all plugins in
301 /// topological order and applied *after* the framework built-ins
302 /// (`static`, `media_url`, `markdown`, `now`, `currency`, …), so a
303 /// plugin may deliberately override a built-in by re-registering the
304 /// same name.
305 ///
306 /// The closures must be owned and `'static` (no borrow of `self`) so
307 /// the framework can stash them and re-run them on every dev-mode
308 /// hot-reload rebuild. Capture any per-plugin config by value.
309 ///
310 /// ```ignore
311 /// fn template_registrars(&self) -> Vec<TemplateRegistrar> {
312 /// vec![Box::new(|env| {
313 /// env.add_filter("shout", |s: String| s.to_uppercase());
314 /// })]
315 /// }
316 /// ```
317 ///
318 /// Default: no custom tags. A plugin that ships none leaves this alone.
319 fn template_registrars(&self) -> Vec<crate::templates::TemplateRegistrar> {
320 Vec::new()
321 }
322
323 /// Wrap the app router with the plugin's middleware layers.
324 ///
325 /// Called once per plugin during `App::build`'s phase 5, in
326 /// topological dependency order. The plugin receives the router
327 /// after its routes have already been merged in, applies any
328 /// `.layer(...)` calls it needs (tower layers, axum's middleware
329 /// fn helpers, etc.), and returns the wrapped router.
330 ///
331 /// Returning the router shape (instead of a `Vec<Layer>` like
332 /// the spec sketched) sidesteps the trait-object lifetime
333 /// problem Layer's generics produce. Plugins keep full access
334 /// to the axum / tower API at the call site.
335 ///
336 /// Default: return the router unchanged. A pure-data plugin
337 /// (models only) inherits this and never touches the router.
338 fn wrap_router(&self, router: Router) -> Router {
339 router
340 }
341
342 /// Framework-level request/response middleware this plugin contributes
343 /// (feature #68).
344 ///
345 /// Where [`wrap_router`](Plugin::wrap_router) hands you the raw axum
346 /// `Router` for arbitrary tower `Layer`s, this is the ergonomic
347 /// surface: each [`Middleware`](crate::middleware::Middleware) gets a
348 /// `before_request` / `after_response` hook and nothing else to wire.
349 /// All plugins' middleware (plus the app's) are collected into one
350 /// stack and installed as a single layer at `App::build`, in plugin
351 /// topological order — a plugin's `before_request` runs after those of
352 /// the plugins it depends on, and its `after_response` runs before
353 /// them (onion order).
354 ///
355 /// Reach for `wrap_router` when you need a real tower `Layer` (timeouts,
356 /// tracing spans, body-limit); reach for this when you just want to
357 /// look at the request or response.
358 ///
359 /// Default: no middleware.
360 fn middleware(&self) -> Vec<std::sync::Arc<dyn crate::middleware::Middleware>> {
361 Vec::new()
362 }
363
364 /// Static files the plugin ships baked into its binary.
365 ///
366 /// Each entry produces one `GET <url_path>` route that returns the
367 /// file body with the supplied `Content-Type` and `Cache-Control`.
368 /// Bodies are `&'static [u8]` — typically `include_bytes!` —
369 /// because the canonical use is "the binary ships its own CSS / JS
370 /// / fonts."
371 ///
372 /// Use cases:
373 /// - `umbral-admin` ships its precompiled Tailwind CSS this way.
374 /// - A plugin that adds an HTMX page can ship an icon or font.
375 /// - User code can register arbitrary embedded assets.
376 ///
377 /// Conflicts across plugins (two plugins claiming the same
378 /// `url_path`) are **not** silently resolved — axum's
379 /// `Router::route` panics at `App::build` time with an "overlapping
380 /// method route" error naming the path. The build fails loudly; fix
381 /// the collision by giving each plugin a distinct `url_path`
382 /// (namespacing under the plugin name is the convention).
383 ///
384 /// Default: no files. Plugins that ship no embedded assets leave
385 /// this alone.
386 fn static_files(&self) -> Vec<StaticFile> {
387 Vec::new()
388 }
389
390 /// On-disk source directories this plugin contributes to the
391 /// unified static pipeline.
392 ///
393 /// Where [`static_files`] bakes assets into the binary (zero-config,
394 /// always available), `static_dirs` declares a *filesystem* source
395 /// the framework's static handler serves live. Each entry pairs a
396 /// `namespace` (the per-plugin URL/disk segment that prevents
397 /// collisions — `"admin"`, `"playground"`) with the absolute
398 /// `source_dir` holding that plugin's source assets (plugins
399 /// typically compute it from `env!("CARGO_MANIFEST_DIR")`).
400 ///
401 /// At `App::build()` the framework walks every plugin's
402 /// `static_dirs()` into a `namespace -> source_dir` registry and
403 /// mounts one handler at the configured `static_url` (default
404 /// `/static/`). A request `/static/<namespace>/<rest>` resolves:
405 ///
406 /// - **Dev** — `<source_dir>/<rest>` first (live source serving: drop
407 /// a rebuilt file and it's served on the next request), falling
408 /// back to `<static_root>/<namespace>/<rest>` when the namespace
409 /// isn't registered or the file is missing.
410 /// - **Prod / Test** — `<static_root>/<namespace>/<rest>` only.
411 ///
412 /// Two plugins declaring the same `namespace` is a boot-time error
413 /// ([`BuildError::DuplicateStaticNamespace`]) — collisions fail
414 /// loudly, never silently shadow.
415 ///
416 /// Default: no directories. A plugin that ships no filesystem assets
417 /// leaves this alone.
418 ///
419 /// [`static_files`]: Plugin::static_files
420 /// [`BuildError::DuplicateStaticNamespace`]: crate::app::BuildError::DuplicateStaticNamespace
421 fn static_dirs(&self) -> Vec<StaticDir> {
422 Vec::new()
423 }
424
425 /// On-disk directories served at the **root** of `static_url` — with
426 /// no namespace segment.
427 ///
428 /// Where [`static_dirs`] serves a plugin's assets under a namespaced
429 /// path (`/static/<namespace>/<file>`), these directories back the
430 /// bare `/static/<file>` space for app/site-level static (a project's
431 /// own CSS, images, favicon). The framework's single static handler
432 /// resolves a request by trying registered namespaces first, then
433 /// these root directories with the full request path.
434 ///
435 /// This is the seam that lets the framework own `static_url` as a
436 /// single mount: a `StoragePlugin`'s static side pointed at the configured
437 /// `static_url` contributes its directory here instead of nesting its
438 /// own (conflicting) catch-all route. A plugin serving its directory
439 /// at a *different* mount returns nothing here and nests as usual.
440 ///
441 /// Default: none.
442 ///
443 /// [`static_dirs`]: Plugin::static_dirs
444 fn static_root_dirs(&self) -> Vec<std::path::PathBuf> {
445 Vec::new()
446 }
447
448 /// CLI subcommands the plugin contributes.
449 ///
450 /// Each command implements [`crate::cli::PluginCommand`] and ships
451 /// a `clap::Command` plus an async `run` handler. The framework's
452 /// binary (or any user-written one) calls
453 /// [`crate::cli::dispatch`] with the App's plugin list to wire
454 /// these into a single CLI tree.
455 ///
456 /// Default: no commands. Plugins that only contribute models,
457 /// routes, or middleware leave this alone.
458 fn commands(&self) -> Vec<Box<dyn crate::cli::PluginCommand>> {
459 Vec::new()
460 }
461
462 /// Callable HTTP endpoints this plugin wants advertised in a
463 /// machine-readable index (e.g. a REST API root, or a client's
464 /// service-discovery fetch).
465 ///
466 /// This is *not* how a plugin mounts routes — that's [`routes`].
467 /// It's a declaration of which of those routes are worth surfacing
468 /// to an API client, with a human label and a grouping key. The
469 /// framework collects every plugin's list at `App::build()` into a
470 /// global readable via [`crate::migrate::registered_api_endpoints`];
471 /// a plugin like `umbral-rest` reads that global to render an API
472 /// root without ever naming the plugins that contributed.
473 ///
474 /// Paths are relative (`/oauth/google/login`) — the core type stays
475 /// origin-agnostic; a consumer joins its own origin when it needs an
476 /// absolute URL.
477 ///
478 /// Default: nothing advertised. Plugins that don't expose a
479 /// client-facing API leave this alone.
480 ///
481 /// [`routes`]: Plugin::routes
482 fn api_endpoints(&self) -> Vec<ApiEndpoint> {
483 Vec::new()
484 }
485
486 /// Wire signals, start background work, seal admin registrations.
487 /// Called after phase 4 (system checks) passes, in topological
488 /// dependency order. Sync, on purpose; spawn async work via
489 /// `ctx.runtime()` when the runtime handle lands.
490 fn on_ready(&self, _ctx: &AppContext) -> Result<(), PluginError> {
491 Ok(())
492 }
493}
494
495/// One static file a plugin ships baked into its binary. Returned
496/// from [`Plugin::static_files`].
497///
498/// The body is a `&'static [u8]` (usually from `include_bytes!`) so
499/// the file ships with the binary; no on-disk asset directory needs
500/// to exist at runtime. `cache_control` defaults to one day if left
501/// `None`.
502#[derive(Debug, Clone)]
503pub struct StaticFile {
504 /// URL path the asset is served at, e.g. `/admin/static/admin.css`.
505 pub url_path: &'static str,
506 /// `Content-Type` header value, e.g. `text/css; charset=utf-8`.
507 pub content_type: &'static str,
508 /// File body. Usually `include_bytes!("relative/path")`.
509 pub body: &'static [u8],
510 /// Optional `Cache-Control` header. `None` → `public, max-age=86400`.
511 pub cache_control: Option<&'static str>,
512}
513
514/// One on-disk source directory a plugin contributes to the unified
515/// static pipeline. Returned from [`Plugin::static_dirs`].
516///
517/// `namespace` is the URL/disk segment that isolates this plugin's
518/// assets from every other plugin's — a request `/static/<namespace>/…`
519/// and the collected output dir `<static_root>/<namespace>/…` both key
520/// off it. It is a `&'static str` because plugins declare it as a
521/// literal.
522///
523/// `source_dir` is the absolute on-disk directory holding the plugin's
524/// source assets, served live in dev. It is a `PathBuf` (not a
525/// `&'static str`) because plugins compute it at runtime — typically
526/// `PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("static")`.
527#[derive(Debug, Clone)]
528pub struct StaticDir {
529 /// Per-plugin URL/disk segment, e.g. `"admin"` or `"playground"`.
530 pub namespace: &'static str,
531 /// Absolute on-disk directory holding the plugin's source assets.
532 pub source_dir: PathBuf,
533}
534
535impl StaticDir {
536 /// Build a [`StaticDir`] from a namespace literal and any
537 /// `Into<PathBuf>` source (a `PathBuf`, `&Path`, or `String`/`&str`
538 /// computed from `env!("CARGO_MANIFEST_DIR")`).
539 pub fn new(namespace: &'static str, source_dir: impl Into<PathBuf>) -> Self {
540 Self {
541 namespace,
542 source_dir: source_dir.into(),
543 }
544 }
545}
546
547/// One callable endpoint a plugin advertises for service discovery.
548/// Returned from [`Plugin::api_endpoints`] and collected at
549/// `App::build()` into [`crate::migrate::registered_api_endpoints`].
550///
551/// The shape is deliberately minimal and origin-agnostic: `path` is
552/// relative, so the type carries no assumption about the public host.
553/// A consumer (a REST API root, a SPA) joins its own origin to build an
554/// absolute URL. `group` lets a consumer bucket endpoints by source
555/// (`"oauth"`, `"tasks"`); `name` is a stable machine key within the
556/// group (`"google.login"`); `label` is the human string a UI renders.
557#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
558pub struct ApiEndpoint {
559 /// Grouping key, e.g. `"oauth"`. Lets a consumer bucket endpoints
560 /// by the plugin/area that contributed them.
561 pub group: String,
562 /// Stable machine name within the group, e.g. `"google.login"`.
563 pub name: String,
564 /// HTTP method, uppercase: `"GET"`, `"POST"`, …
565 pub method: String,
566 /// Relative path, e.g. `"/oauth/google/login"`. No origin.
567 pub path: String,
568 /// Human label a UI renders, e.g. `"Sign in with Google"`.
569 pub label: String,
570}
571
572/// The handle plugins receive in `on_ready`.
573///
574/// Carries clones of the ambient state so a plugin can spawn background
575/// work or seal late registrations without touching globals. M7 v1
576/// surfaces the default pool and a settings snapshot; the runtime
577/// handle lands when the first plugin needs it (likely `umbral-tasks`
578/// at M9).
579#[derive(Debug, Clone)]
580pub struct AppContext {
581 /// The default connection pool, typed by backend. Same value as
582 /// `umbral::db::pool_dispatched().clone()` returns. Plugin code
583 /// that needs the pool typically goes through the ORM instead
584 /// (`Model::objects()…`); this field is the escape hatch for
585 /// schema-DDL bootstrap (the documented exception in CLAUDE.md)
586 /// and backend-specific features like Postgres RLS.
587 pub pool: DbPool,
588 /// A clone of the active settings.
589 pub settings: Settings,
590}
591
592/// Errors a plugin's `on_ready` can return. Boxed under
593/// `BuildError::PluginOnReady` so the build phase surfaces them with
594/// the plugin name attached.
595pub type PluginError = Box<dyn std::error::Error + Send + Sync>;