Skip to main content

dre_protocol/
msg.rs

1//! Control messages. Every JSON frame is an object with a `type` field. From protocol 1, every
2//! message after the handshake also carries the `id` of the request it belongs to ([`Envelope`]).
3
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6
7pub use crate::options::OptionField;
8use crate::{Kind, PluginId};
9
10/// A message with the id of the request it belongs to. Core numbers its requests; every reply,
11/// and every message streamed as part of a request (`result_set_end`, `finish`, `result`,
12/// `result_end`, `log`, `progress`), carries that request's id. `hello` has none, and neither
13/// does anything a protocol 0 peer sends.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct Envelope<T> {
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub id: Option<u64>,
18    #[serde(flatten)]
19    pub body: T,
20}
21
22impl<T> Envelope<T> {
23    pub fn new(id: Option<u64>, body: T) -> Envelope<T> {
24        Envelope { id, body }
25    }
26}
27
28/// Core → plugin.
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30#[serde(tag = "type", rename_all = "snake_case")]
31pub enum Request {
32    /// Always first. The plugin picks a version in both ranges or replies `version_mismatch`.
33    Hello {
34        min_version: u32,
35        max_version: u32,
36        core_version: String,
37        /// The plugin core wants served, for an executable that provides several. A package
38        /// that doesn't provide it replies `error`; without it, the package serves its first.
39        #[serde(default, skip_serializing_if = "Option::is_none")]
40        plugin: Option<PluginId>,
41    },
42    /// Describe the connection fields a profile output for this plugin takes (used by `dre init`)
43    /// and the options a report's config block for it takes.
44    Describe {},
45    /// Check one config block of options (a format's `output:` keys, a destination entry's keys)
46    /// without doing anything. Replies `validated`.
47    Validate {
48        options: Map<String, Value>,
49    },
50    /// Source or destination (protocol 1): check a profile entry's connection settings without
51    /// connecting: the declared fields' generic checks, then the plugin's own rules. Keys in
52    /// `unresolved` (an unset `env_var()`) arrive as `null` and count as set, unchecked. Replies
53    /// `validated`, with `warnings` for unknown keys.
54    ValidateConnection {
55        connection: Map<String, Value>,
56        #[serde(default, skip_serializing_if = "Vec::is_empty")]
57        unresolved: Vec<String>,
58    },
59    /// Source: open a session. All later `execute`/`check` requests run on it.
60    Open {
61        connection: Map<String, Value>,
62        read_only: bool,
63        /// Core's `dre query`: the session must not reach files, programs or the network
64        /// beyond the database (protocol 1, optional; older plugins ignore it).
65        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
66        sandbox: bool,
67    },
68    /// Source: run one statement. Replies `result` (then Arrow frames, then `result_end`) or
69    /// `no_result`.
70    Execute {
71        sql: String,
72        #[serde(default, skip_serializing_if = "Option::is_none")]
73        row_limit: Option<u64>,
74    },
75    /// Source: verify one statement without executing it. Replies `ok` or `error`.
76    Check {
77        sql: String,
78    },
79    /// Format: write result sets to `path`. Followed, per result set, by Arrow frames (at least one,
80    /// carrying the schema) and a `result_set_end`, then `finish`. Replies `written`.
81    Write {
82        path: String,
83        format: String,
84        options: Map<String, Value>,
85        result_sets: Vec<ResultSetMeta>,
86        #[serde(default, skip_serializing_if = "Option::is_none")]
87        template: Option<Value>,
88    },
89    ResultSetEnd {},
90    Finish {},
91    /// Destination: deliver a local file, or with `files` (only to a plugin advertising
92    /// `multi_file`) every file of one output at once. Exactly one of `local_path`/`files` is set,
93    /// unless `message` is: then `files` (possibly empty) holds the files to attach to it, and is
94    /// sent only to a plugin advertising `message`. `options` are the destination entry's plugin
95    /// options, rendered by core. Replies `delivered`.
96    Deliver {
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        local_path: Option<String>,
99        #[serde(default, skip_serializing_if = "Option::is_none")]
100        remote_path: Option<String>,
101        #[serde(default, skip_serializing_if = "Vec::is_empty")]
102        files: Vec<DeliveryFile>,
103        connection: Map<String, Value>,
104        #[serde(default)]
105        options: Map<String, Value>,
106        #[serde(default, skip_serializing_if = "Option::is_none")]
107        message: Option<Message>,
108    },
109    /// Source: load rows into a temporary table on the session, named after `name`. Followed by
110    /// Arrow frames (at least one, carrying the schema) and a `result_set_end`. Replies `loaded`.
111    /// Only sent to plugins advertising `load`.
112    Load {
113        name: String,
114    },
115    /// End the conversation; the plugin exits 0.
116    Close {},
117    /// Protocol 1: stop the request whose id the envelope carries. It has no reply of its own:
118    /// the request replies `error` with kind `cancelled`, or its usual reply if it finished
119    /// first. A cancel for a request that isn't running is ignored.
120    Cancel {},
121}
122
123/// Plugin → core.
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(tag = "type", rename_all = "snake_case")]
126pub enum Response {
127    Hello {
128        protocol_version: u32,
129        kind: Kind,
130        name: String,
131        version: String,
132        #[serde(default)]
133        capabilities: Vec<String>,
134        /// Every plugin the executable serves; empty for one that serves only `kind`/`name`.
135        #[serde(default, skip_serializing_if = "Vec::is_empty")]
136        provides: Vec<PluginId>,
137    },
138    VersionMismatch {
139        min_version: u32,
140        max_version: u32,
141    },
142    Describe {
143        connection_fields: Vec<ConnectionField>,
144        #[serde(default, skip_serializing_if = "Vec::is_empty")]
145        option_fields: Vec<OptionField>,
146        /// Source: the character the database quotes identifiers with (`"` for DuckDB and
147        /// Postgres, a backtick for Databricks). Core uses it to quote names a project asks to
148        /// quote (a source's `quoting:`). Every source sets it; other kinds leave it out.
149        #[serde(default, skip_serializing_if = "Option::is_none")]
150        identifier_quote: Option<String>,
151        /// Source: how core spells a string holding `'` or `\` when it writes one into SQL (an
152        /// inlined lookup): absent or `chr` for `chr(39)`/`chr(92)`, `backslash` for `\'`/`\\`
153        /// inside the quotes (a database without `chr()`, such as ClickHouse).
154        #[serde(default, skip_serializing_if = "Option::is_none")]
155        string_literal: Option<String>,
156        /// Destination advertising `message`: the most characters a message may have in the
157        /// service, after translation. Core shows it next to a message's length in a preview.
158        #[serde(default, skip_serializing_if = "Option::is_none")]
159        message_limit: Option<u64>,
160    },
161    /// Every problem with the options, each a sentence naming the key; empty when they're fine.
162    Validated {
163        errors: Vec<String>,
164        /// Problems that don't stop a run (an unknown key); `validate_connection` only.
165        #[serde(default, skip_serializing_if = "Vec::is_empty")]
166        warnings: Vec<String>,
167    },
168    Ok {},
169    /// A result set follows as Arrow frames, ended by `result_end`.
170    Result {
171        columns: Vec<String>,
172    },
173    ResultEnd {
174        rows: u64,
175    },
176    NoResult {
177        #[serde(default, skip_serializing_if = "Option::is_none")]
178        rows_affected: Option<u64>,
179    },
180    Written {
181        files: Vec<String>,
182        /// Things the person should know about the files (a value written as text, say).
183        #[serde(default, skip_serializing_if = "Vec::is_empty")]
184        warnings: Vec<String>,
185    },
186    Delivered {
187        location: String,
188        /// How many tries the delivery took, when it was more than one (protocol 1).
189        #[serde(default, skip_serializing_if = "Option::is_none")]
190        attempts: Option<u32>,
191    },
192    /// `relation` is what SQL uses to read the loaded rows. `warning`, when set, is shown to the
193    /// user (e.g. the database has no bulk path, so a load this size is slow).
194    Loaded {
195        relation: String,
196        rows: u64,
197        #[serde(default, skip_serializing_if = "Option::is_none")]
198        warning: Option<String>,
199    },
200    /// The request failed. `kind` is one of [`ERROR_KINDS`]; `code` names the problem,
201    /// namespaced by the plugin (`sftp/host-key-mismatch`). Both are optional (protocol 0 has
202    /// neither): without a `code`, core reports the failure under its own code for the step;
203    /// a `code` without a `kind` counts as `internal`.
204    Error {
205        message: String,
206        #[serde(default, skip_serializing_if = "Option::is_none")]
207        kind: Option<String>,
208        #[serde(default, skip_serializing_if = "Option::is_none")]
209        code: Option<String>,
210    },
211    /// Protocol 1: a log line, while a request runs (with its id) or between requests.
212    Log {
213        level: LogLevel,
214        message: String,
215        /// Structured context (`{"attempt": 2}`); never secrets.
216        #[serde(default, skip_serializing_if = "Map::is_empty")]
217        fields: Map<String, Value>,
218    },
219    /// Protocol 1, optional: how far a long request has got. Core shows it when present.
220    Progress {
221        #[serde(default, skip_serializing_if = "Option::is_none")]
222        message: Option<String>,
223        #[serde(default, skip_serializing_if = "Option::is_none")]
224        done: Option<u64>,
225        #[serde(default, skip_serializing_if = "Option::is_none")]
226        total: Option<u64>,
227    },
228}
229
230impl Response {
231    /// An `error` reply with only a message.
232    pub fn error(message: impl Into<String>) -> Response {
233        Response::Error {
234            message: message.into(),
235            kind: None,
236            code: None,
237        }
238    }
239}
240
241/// The kinds an `error` reply may give, from DRE's error-code registry.
242pub const ERROR_KINDS: &[&str] = &[
243    "config",
244    "plugin",
245    "refused",
246    "connection",
247    "auth",
248    "query",
249    "delivery",
250    "internal",
251    "cancelled",
252    "timed_out",
253];
254
255/// How important a `log` message is. Core shows `info` and above to the person, and keeps
256/// `debug` and `trace` for `-v` and the log file.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
258#[serde(rename_all = "lowercase")]
259pub enum LogLevel {
260    Error,
261    Warn,
262    Info,
263    Debug,
264    Trace,
265}
266
267/// A rendered message, as `deliver` carries it.
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269pub struct Message {
270    /// One line, plain text.
271    pub title: String,
272    /// The portable Markdown subset ([`crate::markdown`]).
273    pub text: String,
274    /// An HTML body, when one was made; core leaves it out today. A plugin that can show HTML
275    /// (email) uses it when present, else converts `text`.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub html: Option<String>,
278    /// The `.md` file core wrote: `# title`, then the text.
279    pub path: String,
280}
281
282/// One file of a multi-file `deliver`.
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284pub struct DeliveryFile {
285    pub local_path: String,
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub remote_path: Option<String>,
288}
289
290/// Per result set, what a format plugin needs to lay it out.
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub struct ResultSetMeta {
293    /// Sheet name (xlsx) or file suffix (single-table formats).
294    pub name: String,
295    /// The query (`.sql` basename) that produced it.
296    pub query: String,
297    /// 1-based index among that query's result sets.
298    pub result_index: usize,
299    #[serde(default, skip_serializing_if = "Option::is_none")]
300    pub anchor: Option<String>,
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub header: Option<bool>,
303    /// The query entry's `columns:` map: per result column, how to show it.
304    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
305    pub columns: std::collections::BTreeMap<String, ColumnOptions>,
306    /// The query entry's `autofit` (xlsx): size this tab's columns from their content, over the
307    /// output's `autofit`.
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub autofit: Option<bool>,
310    /// The query entry's `style` (xlsx), over the output's.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub style: Option<crate::style::SheetStyle>,
313}
314
315/// One entry of a `columns:` map.
316#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
317pub struct ColumnOptions {
318    /// An Excel number format code.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub format: Option<String>,
321    /// A row formula (`={qty}*{price}`), written in place of the column's value, which becomes
322    /// its cached result.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub formula: Option<String>,
325    /// A totals row entry under the data: `sum`, `average`, `count`, `min`, `max`, or a formula
326    /// over whole columns (`=SUM({amount:*})/COUNT({qty:*})`).
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub total: Option<String>,
329    /// The column's width (xlsx), over the tab's and output's `autofit`.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub width: Option<ColumnWidth>,
332    /// How the column's data cells look (xlsx), over the tab's and output's `style`.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub style: Option<crate::style::CellStyle>,
335}
336
337/// A column width: sized from the content, or a number of characters.
338#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
339#[serde(untagged)]
340pub enum ColumnWidth {
341    Chars(f64),
342    Auto(AutoWidth),
343}
344
345/// The word `auto`.
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(rename_all = "lowercase")]
348pub enum AutoWidth {
349    Auto,
350}
351
352#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
353pub struct ConnectionField {
354    pub name: String,
355    #[serde(default)]
356    pub description: String,
357    #[serde(default)]
358    pub required: bool,
359    /// Offered as an `env_var()` reference by default in `dre init`.
360    #[serde(default)]
361    pub secret: bool,
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub default: Option<Value>,
364    /// A source type whose profile has the same field: `dre init` offers the value entered for
365    /// that source as this field's default (e.g. one Databricks host for source and destination).
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub same_as_source: Option<String>,
368    /// Set by hand in `profiles.yml`: `dre init` doesn't ask for it. For alternatives to a
369    /// prompted field (a key given as text instead of a file) and nested blocks (`ssh:`).
370    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
371    pub manual: bool,
372    /// What the value must be, checked by `validate_connection` (and `dre init` as you type).
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub kind: Option<FieldKind>,
375    /// The only values it may take (`dre init` offers them as a choice).
376    #[serde(default, skip_serializing_if = "Vec::is_empty")]
377    pub choices: Vec<String>,
378}
379
380/// What a connection field's value must be.
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
382#[serde(rename_all = "snake_case")]
383pub enum FieldKind {
384    String,
385    /// A whole number, or a string of one (`port: "5432"`).
386    Integer,
387    Boolean,
388    /// A file that must exist; a leading `~/` is the home directory.
389    Path,
390    /// `30s`, `2m`, `1h`, or seconds.
391    Duration,
392    /// A block of settings (`ssh:`), checked by the plugin's own rules.
393    Map,
394}
395
396impl ConnectionField {
397    pub fn new(name: &str, description: &str) -> Self {
398        ConnectionField {
399            name: name.into(),
400            description: description.into(),
401            required: false,
402            secret: false,
403            default: None,
404            same_as_source: None,
405            manual: false,
406            kind: None,
407            choices: Vec::new(),
408        }
409    }
410    pub fn kind(mut self, kind: FieldKind) -> Self {
411        self.kind = Some(kind);
412        self
413    }
414    pub fn choices(mut self, choices: &[&str]) -> Self {
415        self.choices = choices.iter().map(|c| c.to_string()).collect();
416        self.kind.get_or_insert(FieldKind::String);
417        self
418    }
419    pub fn required(mut self) -> Self {
420        self.required = true;
421        self
422    }
423    pub fn secret(mut self) -> Self {
424        self.secret = true;
425        self
426    }
427    pub fn default(mut self, v: impl Into<Value>) -> Self {
428        self.default = Some(v.into());
429        self
430    }
431    pub fn same_as_source(mut self, source_type: &str) -> Self {
432        self.same_as_source = Some(source_type.into());
433        self
434    }
435    pub fn manual(mut self) -> Self {
436        self.manual = true;
437        self
438    }
439}