Skip to main content

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