razeri_plugin_api/lib.rs
1// Copyright (C) 2026 Gabriel Shea
2// Licensed under either of the Apache License, Version 2.0 or the MIT
3// license, at your option.
4
5#![warn(missing_docs)]
6
7//! # razeri-plugin-api
8//!
9//! Extension point traits and registries for the Razeri platform.
10//!
11//! This crate defines the **plugin API surface** — the traits that third-party
12//! developers implement to extend Razeri with new database dialects, storage
13//! backends, LLM providers, language renderers, and event sinks.
14//!
15//! ## Extension Points
16//!
17//! | Trait | Registry | Key Type |
18//! |-------|----------|----------|
19//! | [`PlatformDialect`] | [`PlatformRegistry`] | string (canonical name) |
20//! | [`StorageProviderFactory`] | [`StorageRegistry`] | `StoragePlatform` enum + string |
21//! | [`LlmClientFactory`] / [`LlmClient`] | [`LlmRegistry`] | string |
22//! | [`LlmModelAdapter`] | [`ModelRegistry`] | (provider, model) pair |
23//! | [`LanguageRendererFactory`] | [`LanguageRegistry`] | string |
24//! | [`EventSink`] | [`EventRegistry`] | fan-out (all sinks) |
25//!
26//! ## Beside the extension points
27//!
28//! | Module | What it holds |
29//! |--------|---------------|
30//! | [`conformance`] | the report that grades a dialect against everything it owes, run from the dialect's own tests |
31//! | [`resolve`] | a platform name, an alias or `name@version`, turned into the dialect that renders it |
32//! | [`process`] | the one dialect registry a process resolves names against, and the plugin directory that feeds it |
33//! | [`dynamic`] | loading a plugin built as a shared library, and refusing one built differently from the razeri that loads it |
34//! | [`alerting`] | alert rules and health summaries evaluated over the event stream |
35//! | [`sinks`] | the event sinks razeri ships, written against the same [`EventSink`] trait a plugin implements |
36//!
37//! ## Composition Root
38//!
39//! Use [`PluginRegistryBuilder`] to wire everything together at application
40//! startup, then pass the resulting [`PluginRegistry`] to subsystems. The
41//! builder's own page shows it in use.
42
43pub mod alerting;
44pub mod builder;
45pub mod conformance;
46pub mod dialect;
47pub mod dynamic;
48pub mod error;
49pub mod event;
50pub mod language;
51pub mod llm;
52pub mod model;
53pub mod process;
54pub mod registry;
55pub mod resolve;
56pub mod sinks;
57pub mod storage;
58
59// ── Convenience re-exports ────────────────────────────────────────────
60
61pub use builder::PluginRegistryBuilder;
62pub use dialect::{
63 BlockTerminator, DeployClient, DeployScript, DialectHandle, DialectInfo, PlatformDialect,
64 PlatformRegistry, UnsupportedVersion,
65};
66pub use razeri_plugin_contract::{EngineVersion, EngineVersionError};
67
68// The contract a plugin's types and traits are written against, re-exported so
69// a dialect crate can depend on this one crate and reach everything it needs.
70pub use dynamic::{
71 BuildDeclaration, BuildDeclarationFn, BuildPart, PLUGIN_BUILD_SYMBOL, PLUGIN_REGISTER_SYMBOL,
72 PluginLoadResult, PluginRefusal, RegisterPluginFn,
73};
74pub use razeri_plugin_contract;
75
76/// **The named routine grammars, spelled.**
77///
78/// A dialect whose engine has a routine in a grammar Razeri does not carry
79/// renders the whole `CREATE` itself. These three functions write out the
80/// grammars Razeri does carry, from the same
81/// [`RoutineSpec`](razeri_plugin_contract::RoutineSpec) a dialect receives, so a
82/// grammar that is *"PL/pgSQL with one tweak"* starts from PL/pgSQL and says
83/// what differs rather than being written from nothing.
84pub use razeri_plugin_contract::routine_render;
85pub use razeri_plugin_contract::routine_render::{
86 render_procedure_as, render_scalar_function_as, render_table_function_as,
87};
88
89#[cfg(all(feature = "dynamic", not(target_arch = "wasm32")))]
90pub use dynamic::load_plugins_from_dir;
91pub use error::{EventSinkError, LanguageError, LlmError, StorageError};
92pub use event::{
93 EventCategory, EventEmitter, EventFilterKeys, EventPayload, EventQuery, EventRegistry,
94 EventSeverity, EventSink, EventSubject, EventSubjectKind, EventSummary, EventValidationError,
95 RazeriEvent, WorkflowContext,
96};
97pub use language::{LanguageRegistry, LanguageRenderer, LanguageRendererFactory};
98pub use llm::{
99 ChatResponse, LlmClient, LlmClientFactory, LlmRegistry, Message, ModelInfo, TokenUsage,
100};
101pub use model::{LlmModelAdapter, ModelCapabilities, ModelRegistry};
102pub use process::{
103 InstallError, PLUGIN_DIR_ENV, PluginDirReport, install_plugin_dir, plugin_dir_from_environment,
104 plugin_dir_report, process_event_sinks, process_registry,
105};
106pub use registry::PluginRegistry;
107pub use resolve::ResolveError;
108pub use storage::{
109 StorageListEntry, StorageMetadata, StorageOps, StorageProviderFactory, StorageRegistry,
110};
111
112// Re-export built-in sink types and factory. The JSONL sink is native-only
113// (filesystem via `tokio::fs`), so its re-export is absent on wasm.
114#[cfg(not(target_arch = "wasm32"))]
115pub use sinks::jsonl::JsonlSink;
116pub use sinks::stdout::StdoutSink;
117pub use sinks::webhook::WebhookSink;
118pub use sinks::{EventSinkConfig, create_sink};
119
120// Re-export alerting and health model
121pub use alerting::{
122 AlertCondition, AlertMetric, AlertResult, AlertRule, AlertScope, ComparisonOp, HealthDomain,
123 HealthStatus, HealthSummary, SinkStatus, discover_health, evaluate_rules, health_for_domain,
124};
125
126// Re-export inventory registration types
127pub use builder::{
128 DialectRegistration, EventSinkRegistration, LanguageRegistration, LlmRegistration,
129 ModelRegistration, PluginRegistration, StorageRegistration,
130};
131
132/// **Make a crate a razeri plugin, in one line.**
133///
134/// Name a function that registers what the crate provides:
135///
136/// ```ignore
137/// use razeri_plugin_api::PluginRegistryBuilder;
138/// use std::sync::Arc;
139///
140/// fn register(builder: &mut PluginRegistryBuilder) {
141/// builder.register_dialect(Arc::new(MyDb));
142/// }
143///
144/// razeri_plugin_api::export_plugin!(register);
145/// ```
146///
147/// The crate can then reach razeri two ways, and the same line serves both:
148///
149/// - **Loaded from a plugin directory**, built as a `cdylib`. The line exports
150/// how the library was built and the function razeri calls to register it.
151/// Razeri reads the first before it calls the second, and refuses a library
152/// built with another compiler or against other plugin crates.
153/// - **Linked into a razeri you build**, as an ordinary dependency. The line
154/// records `register` so the registry finds it at start-up, the same way it
155/// finds razeri's own dialects.
156///
157/// Use it once per crate, at the top level of `lib.rs`.
158#[macro_export]
159macro_rules! export_plugin {
160 ($register:path) => {
161 /// How this plugin was built. Razeri reads it before it calls
162 /// anything else in this library.
163 #[unsafe(no_mangle)]
164 pub extern "C" fn razeri_plugin_build()
165 -> *const $crate::dynamic::export::ExportedBuildDeclaration {
166 &$crate::dynamic::export::THIS_BUILD
167 }
168
169 /// Registers this plugin with the razeri that loaded it.
170 ///
171 /// # Safety
172 ///
173 /// Called by razeri only after this library's build declaration
174 /// matched its own; `builder` is razeri's and outlives the call.
175 #[unsafe(no_mangle)]
176 pub unsafe extern "Rust" fn razeri_plugin_register_v1(
177 builder: &mut $crate::PluginRegistryBuilder,
178 ) {
179 $register(builder);
180 }
181
182 $crate::dynamic::export::inventory::submit! {
183 $crate::PluginRegistration::new($register)
184 }
185 };
186}
187
188// ── Convenience helpers ───────────────────────────────────────────────
189
190use std::sync::Arc;
191
192/// Resolve a platform name to the dialect that renders it.
193///
194/// This is the **one resolver** — all service crates call it instead of
195/// matching on names themselves. Each dialect declares the spellings it answers
196/// to, so `"pg"` reaches `PostgreSQL` and `"mssql"` reaches SQL Server because
197/// those dialects say so. Matching ignores case and surrounding whitespace, and
198/// an unknown name comes back with near-miss suggestions.
199///
200/// A dialect the host loaded at run time resolves the same way as one linked
201/// in: both are read off the registry.
202///
203/// # Errors
204///
205/// [`ResolveError::UnknownDialect`], with suggestions, if no loaded dialect
206/// answers to the name; [`ResolveError::AmbiguousName`] if two do.
207///
208/// # Examples
209///
210/// ```no_run
211/// use razeri_plugin_api::{ResolveError, resolve_dialect_by_name};
212///
213/// # fn main() -> Result<(), ResolveError> {
214/// // Aliases, canonical names and casing all resolve to the same dialect.
215/// let dialect = resolve_dialect_by_name("pg")?;
216/// println!("{}", dialect.info().name);
217///
218/// let dialect = resolve_dialect_by_name("SNOWFLAKE")?;
219/// let dialect = resolve_dialect_by_name("sqlite")?;
220/// # Ok(())
221/// # }
222/// ```
223pub fn resolve_dialect_by_name(name: &str) -> Result<Arc<dyn PlatformDialect>, ResolveError> {
224 resolve::resolve_dialect_by_name(name)
225}
226
227/// Resolve a dialect by string name, returning `None` on failure.
228///
229/// Convenience wrapper around [`resolve_dialect_by_name`] for callers that
230/// prefer `Option` over `Result`.
231#[must_use]
232pub fn try_resolve_dialect_by_name(name: &str) -> Option<Arc<dyn PlatformDialect>> {
233 resolve_dialect_by_name(name).ok()
234}