Skip to main content

dre_protocol/
lib.rs

1//! The DRE plugin protocol, version 1.
2//!
3//! Plugins ship in packages: one executable, `dre-plugin-<package>`, serving every plugin the
4//! package provides (a single plugin may also be named `dre-<kind>-<name>`). It talks to DRE core
5//! over stdin/stdout in length-prefixed frames. Each frame is a JSON control message or an Arrow IPC stream; plugins
6//! log through `log` messages, and stderr carries what can't (panics, native drivers). See `docs/protocol.md` in the repository for the public contract.
7//!
8//! - [`frame`]: the wire format.
9//! - [`msg`]: every control message.
10//! - [`host`]: the core side: spawning a plugin, the handshake, requests.
11//! - [`plugin`]: the SDK plugin authors use to serve requests.
12//! - [`options`]: the options a plugin declares, and how they're checked.
13//! - [`conformance`]: checks any plugin binary against the protocol, from the language-neutral
14//!   fixture cases in `conformance/`.
15//! - [`schema`]: the JSON Schema of every message, published as `conformance/schema.json`.
16//! - [`sessions`]: OAuth sessions plugins keep in `~/.dre/oauth_sessions.json`.
17//! - [`markdown`]: the portable Markdown subset of messages, and its translations.
18//! - [`delivery`]: the delivery and network rules every file destination shares.
19
20// A public function that can panic says when in a `# Panics` section (CI denies warnings).
21#![warn(clippy::missing_panics_doc)]
22
23/// The `log` crate, re-exported: plugins log with `dre_protocol::log::info!` and friends, which
24/// the SDK sends to core as `log` messages.
25pub use log;
26
27pub mod conformance;
28pub mod connection;
29pub mod delivery;
30pub mod frame;
31#[cfg(target_os = "linux")]
32mod fuse_fds;
33pub mod host;
34pub mod markdown;
35pub mod msg;
36pub mod options;
37pub mod plugin;
38pub mod schema;
39pub mod sessions;
40pub mod style;
41pub mod util;
42
43/// This crate's version (its own, not DRE's); the fixture plugins report it.
44pub const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
45
46/// Protocol versions the plugin SDK speaks: a plugin built on it also works with an older core.
47pub const MIN_VERSION: u32 = 0;
48pub const MAX_VERSION: u32 = 1;
49/// The oldest protocol version core accepts from a plugin.
50pub const CORE_MIN_VERSION: u32 = 1;
51
52/// Capability: can hold one session (and its temp objects) across requests.
53pub const CAP_SESSIONS: &str = "sessions";
54/// Capability: can open a connection read-only.
55pub const CAP_READ_ONLY: &str = "read_only";
56/// Capability: can verify a statement without executing it.
57pub const CAP_CHECK: &str = "check";
58/// Capability (destinations): takes every file of one output in a single `deliver`.
59pub const CAP_MULTI_FILE: &str = "multi_file";
60/// Capability (destinations): takes a message (`deliver` with `message`), not only files.
61pub const CAP_MESSAGE: &str = "message";
62/// Capability (destinations): takes only messages; core never sends it a file output.
63pub const CAP_MESSAGE_ONLY: &str = "message_only";
64/// Source: loads rows into a temporary table on the session (`load`), for large lookups.
65pub const CAP_LOAD: &str = "load";
66/// Answers `validate` (checks a config block of options). The Rust SDK always advertises it.
67pub const CAP_VALIDATE: &str = "validate";
68
69/// Every capability a plugin may advertise, as the published schema lists them.
70pub const CAPABILITIES: &[&str] = &[
71    CAP_SESSIONS,
72    CAP_READ_ONLY,
73    CAP_CHECK,
74    CAP_MULTI_FILE,
75    CAP_MESSAGE,
76    CAP_MESSAGE_ONLY,
77    CAP_LOAD,
78    CAP_VALIDATE,
79];
80
81#[derive(
82    Debug,
83    Clone,
84    Copy,
85    PartialEq,
86    Eq,
87    PartialOrd,
88    Ord,
89    Hash,
90    serde::Serialize,
91    serde::Deserialize,
92    schemars::JsonSchema,
93)]
94#[serde(rename_all = "lowercase")]
95pub enum Kind {
96    Source,
97    Format,
98    Destination,
99}
100
101impl Kind {
102    pub fn as_str(self) -> &'static str {
103        match self {
104            Kind::Source => "source",
105            Kind::Format => "format",
106            Kind::Destination => "destination",
107        }
108    }
109
110    /// Parse a kind, singular or plural (`source`, `sources`).
111    pub fn parse(s: &str) -> Option<Kind> {
112        match s {
113            "source" | "sources" => Some(Kind::Source),
114            "format" | "formats" => Some(Kind::Format),
115            "destination" | "destinations" => Some(Kind::Destination),
116            _ => None,
117        }
118    }
119}
120
121impl std::fmt::Display for Kind {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        f.write_str(self.as_str())
124    }
125}
126
127/// One plugin: its kind and name. Written `<kind>/<name>` (`destination/s3`), in messages as
128/// well as in `dre.lock`.
129#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
130pub struct PluginId {
131    pub kind: Kind,
132    pub name: String,
133}
134
135impl PluginId {
136    pub fn new(kind: Kind, name: impl Into<String>) -> PluginId {
137        PluginId {
138            kind,
139            name: name.into(),
140        }
141    }
142}
143
144impl std::fmt::Display for PluginId {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        write!(f, "{}/{}", self.kind, self.name)
147    }
148}
149
150impl std::str::FromStr for PluginId {
151    type Err = String;
152
153    fn from_str(s: &str) -> Result<PluginId, String> {
154        let bad = || format!("`{s}` isn't `<kind>/<name>` (e.g. `destination/s3`)");
155        let (k, n) = s.split_once('/').ok_or_else(bad)?;
156        let kind = Kind::parse(k).ok_or_else(bad)?;
157        valid_name(n).then(|| PluginId::new(kind, n)).ok_or_else(bad)
158    }
159}
160
161impl serde::Serialize for PluginId {
162    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
163        s.collect_str(self)
164    }
165}
166
167impl schemars::JsonSchema for PluginId {
168    fn schema_name() -> std::borrow::Cow<'static, str> {
169        "PluginId".into()
170    }
171
172    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
173        schemars::json_schema!({
174            "description": "One plugin, written `<kind>/<name>` (`destination/s3`).",
175            "type": "string",
176            "pattern": "^(source|format|destination)/[a-z0-9_]+$"
177        })
178    }
179}
180
181impl<'de> serde::Deserialize<'de> for PluginId {
182    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
183        String::deserialize(d)?.parse().map_err(serde::de::Error::custom)
184    }
185}
186
187/// Whether `name` is a valid plugin or package name: `[a-z0-9_]+`.
188pub fn valid_name(name: &str) -> bool {
189    !name.is_empty()
190        && name
191            .bytes()
192            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
193}
194
195/// The executable file name for a package on this platform: `dre-plugin-<package>`.
196pub fn package_executable_name(package: &str) -> String {
197    format!("dre-plugin-{package}{}", std::env::consts::EXE_SUFFIX)
198}
199
200/// Parse `dre-plugin-<package>[.exe]` into the package name.
201pub fn parse_package_executable_name(file: &str) -> Option<String> {
202    let stem = file.strip_suffix(std::env::consts::EXE_SUFFIX).unwrap_or(file);
203    if !std::env::consts::EXE_SUFFIX.is_empty() && stem == file {
204        return None;
205    }
206    let name = stem.strip_prefix("dre-plugin-")?;
207    valid_name(name).then(|| name.to_string())
208}
209
210/// The executable file name for a single plugin on this platform.
211pub fn executable_name(kind: Kind, name: &str) -> String {
212    format!("dre-{}-{name}{}", kind.as_str(), std::env::consts::EXE_SUFFIX)
213}
214
215/// Parse `dre-<kind>-<name>[.exe]` into its kind and name. Names are `[a-z0-9_]+`.
216pub fn parse_executable_name(file: &str) -> Option<(Kind, String)> {
217    let stem = file.strip_suffix(std::env::consts::EXE_SUFFIX).unwrap_or(file);
218    if !std::env::consts::EXE_SUFFIX.is_empty() && stem == file {
219        return None;
220    }
221    let rest = stem.strip_prefix("dre-")?;
222    let (kind, name) = rest.split_once('-')?;
223    let kind = Kind::parse(kind)?;
224    valid_name(name).then(|| (kind, name.to_string()))
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn parses_plugin_executable_names() {
233        let exe = |s: &str| format!("{s}{}", std::env::consts::EXE_SUFFIX);
234        assert_eq!(
235            parse_executable_name(&exe("dre-source-duckdb")),
236            Some((Kind::Source, "duckdb".into()))
237        );
238        assert_eq!(
239            parse_executable_name(&exe("dre-destination-azure_blob")),
240            Some((Kind::Destination, "azure_blob".into()))
241        );
242        assert_eq!(parse_executable_name(&exe("dre-format-csv.d")), None);
243        assert_eq!(parse_executable_name(&exe("dre-widget-x")), None);
244        assert_eq!(parse_executable_name(&exe("dre")), None);
245        assert_eq!(parse_executable_name(&exe("dre-plugin-csv")), None);
246    }
247
248    #[test]
249    fn parses_package_executable_names() {
250        let exe = |s: &str| format!("{s}{}", std::env::consts::EXE_SUFFIX);
251        assert_eq!(
252            parse_package_executable_name(&exe("dre-plugin-object_store")).as_deref(),
253            Some("object_store")
254        );
255        assert_eq!(parse_package_executable_name(&exe("dre-source-duckdb")), None);
256        assert_eq!(parse_package_executable_name(&exe("dre-plugin-")), None);
257    }
258
259    #[test]
260    fn plugin_ids_read_and_write_as_kind_slash_name() {
261        let id: PluginId = "destination/s3".parse().unwrap();
262        assert_eq!(id, PluginId::new(Kind::Destination, "s3"));
263        assert_eq!(id.to_string(), "destination/s3");
264        assert_eq!(serde_json::to_string(&id).unwrap(), "\"destination/s3\"");
265        assert!("s3".parse::<PluginId>().is_err());
266        assert!("widget/s3".parse::<PluginId>().is_err());
267    }
268}