dre-protocol 0.7.0

The DRE plugin protocol: frames, messages, host side, plugin SDK and conformance suite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Control messages. Every JSON frame is an object with a `type` field. From protocol 1, every
//! message after the handshake also carries the `id` of the request it belongs to ([`Envelope`]).

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

pub use crate::options::OptionField;
use crate::{Kind, PluginId};

/// A message with the id of the request it belongs to. Core numbers its requests; every reply,
/// and every message streamed as part of a request (`result_set_end`, `finish`, `result`,
/// `result_end`, `log`, `progress`), carries that request's id. `hello` has none, and neither
/// does anything a protocol 0 peer sends.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope<T> {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<u64>,
    #[serde(flatten)]
    pub body: T,
}

impl<T> Envelope<T> {
    pub fn new(id: Option<u64>, body: T) -> Envelope<T> {
        Envelope { id, body }
    }
}

/// Core → plugin.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Request {
    /// Always first. The plugin picks a version in both ranges or replies `version_mismatch`.
    Hello {
        min_version: u32,
        max_version: u32,
        core_version: String,
        /// The plugin core wants served, for an executable that provides several. A package
        /// that doesn't provide it replies `error`; without it, the package serves its first.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        plugin: Option<PluginId>,
    },
    /// Describe the connection fields a profile output for this plugin takes (used by `dre init`)
    /// and the options a report's config block for it takes.
    Describe {},
    /// Check one config block of options (a format's `output:` keys, a destination entry's keys)
    /// without doing anything. Replies `validated`.
    Validate {
        options: Map<String, Value>,
        /// Format: what the plugin needs to check the output's template too. For the html and
        /// pdf formats, `{"file": <absolute path or null>, "project_root", "queries": [...]}`.
        /// Optional; older plugins ignore it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        template: Option<Value>,
    },
    /// Source or destination (protocol 1): check a profile entry's connection settings without
    /// connecting: the declared fields' generic checks, then the plugin's own rules. Keys in
    /// `unresolved` (an unset `env_var()`) arrive as `null` and count as set, unchecked. Replies
    /// `validated`, with `warnings` for unknown keys.
    ValidateConnection {
        connection: Map<String, Value>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        unresolved: Vec<String>,
    },
    /// Source: open a session. All later `execute`/`check` requests run on it.
    Open {
        connection: Map<String, Value>,
        read_only: bool,
        /// Core's `dre query`: the session must not reach files, programs or the network
        /// beyond the database (protocol 1, optional; older plugins ignore it).
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        sandbox: bool,
    },
    /// Source: run one statement. Replies `result` (then Arrow frames, then `result_end`) or
    /// `no_result`.
    Execute {
        sql: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        row_limit: Option<u64>,
    },
    /// Source: verify one statement without executing it. Replies `ok` or `error`.
    Check {
        sql: String,
    },
    /// Format: write result sets to `path`. Followed, per result set, by Arrow frames (at least one,
    /// carrying the schema) and a `result_set_end`, then `finish`. Replies `written`.
    Write {
        path: String,
        format: String,
        options: Map<String, Value>,
        result_sets: Vec<ResultSetMeta>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        template: Option<Value>,
    },
    ResultSetEnd {},
    Finish {},
    /// Destination: deliver a local file, or with `files` (only to a plugin advertising
    /// `multi_file`) every file of one output at once. Exactly one of `local_path`/`files` is set,
    /// unless `message` is: then `files` (possibly empty) holds the files to attach to it, and is
    /// sent only to a plugin advertising `message`. `options` are the destination entry's plugin
    /// options, rendered by core. Replies `delivered`.
    Deliver {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        local_path: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        remote_path: Option<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        files: Vec<DeliveryFile>,
        connection: Map<String, Value>,
        #[serde(default)]
        options: Map<String, Value>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<Message>,
    },
    /// Source: load rows into a temporary table on the session, named after `name`. Followed by
    /// Arrow frames (at least one, carrying the schema) and a `result_set_end`. Replies `loaded`.
    /// Only sent to plugins advertising `load`.
    Load {
        name: String,
    },
    /// End the conversation; the plugin exits 0.
    Close {},
    /// Protocol 1: stop the request whose id the envelope carries. It has no reply of its own:
    /// the request replies `error` with kind `cancelled`, or its usual reply if it finished
    /// first. A cancel for a request that isn't running is ignored.
    Cancel {},
}

/// Plugin → core.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Response {
    Hello {
        protocol_version: u32,
        kind: Kind,
        name: String,
        version: String,
        #[serde(default)]
        capabilities: Vec<String>,
        /// Every plugin the executable serves; empty for one that serves only `kind`/`name`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        provides: Vec<PluginId>,
    },
    VersionMismatch {
        min_version: u32,
        max_version: u32,
    },
    Describe {
        connection_fields: Vec<ConnectionField>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        option_fields: Vec<OptionField>,
        /// Source: the character the database quotes identifiers with (`"` for DuckDB and
        /// Postgres, a backtick for Databricks). Core uses it to quote names a project asks to
        /// quote (a source's `quoting:`). Every source sets it; other kinds leave it out.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        identifier_quote: Option<String>,
        /// Source: how core spells a string holding `'` or `\` when it writes one into SQL (an
        /// inlined lookup): absent or `chr` for `chr(39)`/`chr(92)`, `backslash` for `\'`/`\\`
        /// inside the quotes (a database without `chr()`, such as ClickHouse).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        string_literal: Option<String>,
        /// Destination advertising `message`: the most characters a message may have in the
        /// service, after translation. Core shows it next to a message's length in a preview.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message_limit: Option<u64>,
    },
    /// Every problem with the options, each a sentence naming the key; empty when they're fine.
    Validated {
        errors: Vec<String>,
        /// Problems that don't stop a run (an unknown key); `validate_connection` only.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        warnings: Vec<String>,
    },
    Ok {},
    /// A result set follows as Arrow frames, ended by `result_end`.
    Result {
        columns: Vec<String>,
    },
    ResultEnd {
        rows: u64,
    },
    NoResult {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rows_affected: Option<u64>,
    },
    Written {
        files: Vec<String>,
        /// Things the person should know about the files (a value written as text, say).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        warnings: Vec<String>,
    },
    Delivered {
        location: String,
        /// How many tries the delivery took, when it was more than one (protocol 1).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        attempts: Option<u32>,
    },
    /// `relation` is what SQL uses to read the loaded rows. `warning`, when set, is shown to the
    /// user (e.g. the database has no bulk path, so a load this size is slow).
    Loaded {
        relation: String,
        rows: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        warning: Option<String>,
    },
    /// The request failed. `kind` is one of [`ERROR_KINDS`]; `code` names the problem,
    /// namespaced by the plugin (`sftp/host-key-mismatch`). Both are optional (protocol 0 has
    /// neither): without a `code`, core reports the failure under its own code for the step;
    /// a `code` without a `kind` counts as `internal`.
    Error {
        message: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        kind: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        code: Option<String>,
    },
    /// Protocol 1: a log line, while a request runs (with its id) or between requests.
    Log {
        level: LogLevel,
        message: String,
        /// Structured context (`{"attempt": 2}`); never secrets.
        #[serde(default, skip_serializing_if = "Map::is_empty")]
        fields: Map<String, Value>,
    },
    /// Protocol 1, optional: how far a long request has got. Core shows it when present.
    Progress {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        done: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        total: Option<u64>,
    },
}

impl Response {
    /// An `error` reply with only a message.
    pub fn error(message: impl Into<String>) -> Response {
        Response::Error {
            message: message.into(),
            kind: None,
            code: None,
        }
    }
}

/// The kinds an `error` reply may give, from DRE's error-code registry.
pub const ERROR_KINDS: &[&str] = &[
    "config",
    "plugin",
    "refused",
    "connection",
    "auth",
    "query",
    "delivery",
    "internal",
    "cancelled",
    "timed_out",
];

/// How important a `log` message is. Core shows `info` and above to the person, and keeps
/// `debug` and `trace` for `-v` and the log file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

/// A rendered message, as `deliver` carries it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
    /// One line, plain text.
    pub title: String,
    /// The portable Markdown subset ([`crate::markdown`]).
    pub text: String,
    /// An HTML body, when one was made; core leaves it out today. A plugin that can show HTML
    /// (email) uses it when present, else converts `text`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    /// The `.md` file core wrote: `# title`, then the text.
    pub path: String,
}

/// One file of a multi-file `deliver`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeliveryFile {
    pub local_path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_path: Option<String>,
}

/// Per result set, what a format plugin needs to lay it out.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResultSetMeta {
    /// Sheet name (xlsx) or file suffix (single-table formats).
    pub name: String,
    /// The query (`.sql` basename) that produced it.
    pub query: String,
    /// 1-based index among that query's result sets.
    pub result_index: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub header: Option<bool>,
    /// The query entry's `columns:` map: per result column, how to show it.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub columns: std::collections::BTreeMap<String, ColumnOptions>,
    /// The query entry's `autofit` (xlsx): size this tab's columns from their content, over the
    /// output's `autofit`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub autofit: Option<bool>,
    /// The query entry's `style` (xlsx), over the output's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<crate::style::SheetStyle>,
}

/// One entry of a `columns:` map.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ColumnOptions {
    /// An Excel number format code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    /// A row formula (`={qty}*{price}`), written in place of the column's value, which becomes
    /// its cached result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub formula: Option<String>,
    /// A totals row entry under the data: `sum`, `average`, `count`, `min`, `max`, or a formula
    /// over whole columns (`=SUM({amount:*})/COUNT({qty:*})`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total: Option<String>,
    /// The column's width (xlsx), over the tab's and output's `autofit`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<ColumnWidth>,
    /// How the column's data cells look (xlsx), over the tab's and output's `style`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<crate::style::CellStyle>,
}

/// A column width: sized from the content, or a number of characters.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ColumnWidth {
    Chars(f64),
    Auto(AutoWidth),
}

/// The word `auto`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AutoWidth {
    Auto,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionField {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub required: bool,
    /// Offered as an `env_var()` reference by default in `dre init`.
    #[serde(default)]
    pub secret: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<Value>,
    /// A source type whose profile has the same field: `dre init` offers the value entered for
    /// that source as this field's default (e.g. one Databricks host for source and destination).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub same_as_source: Option<String>,
    /// Set by hand in `profiles.yml`: `dre init` doesn't ask for it. For alternatives to a
    /// prompted field (a key given as text instead of a file) and nested blocks (`ssh:`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub manual: bool,
    /// What the value must be, checked by `validate_connection` (and `dre init` as you type).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<FieldKind>,
    /// The only values it may take (`dre init` offers them as a choice).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<String>,
}

/// What a connection field's value must be.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldKind {
    String,
    /// A whole number, or a string of one (`port: "5432"`).
    Integer,
    Boolean,
    /// A file that must exist; a leading `~/` is the home directory.
    Path,
    /// `30s`, `2m`, `1h`, or seconds.
    Duration,
    /// A block of settings (`ssh:`), checked by the plugin's own rules.
    Map,
}

impl ConnectionField {
    pub fn new(name: &str, description: &str) -> Self {
        ConnectionField {
            name: name.into(),
            description: description.into(),
            required: false,
            secret: false,
            default: None,
            same_as_source: None,
            manual: false,
            kind: None,
            choices: Vec::new(),
        }
    }
    pub fn kind(mut self, kind: FieldKind) -> Self {
        self.kind = Some(kind);
        self
    }
    pub fn choices(mut self, choices: &[&str]) -> Self {
        self.choices = choices.iter().map(|c| c.to_string()).collect();
        self.kind.get_or_insert(FieldKind::String);
        self
    }
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }
    pub fn secret(mut self) -> Self {
        self.secret = true;
        self
    }
    pub fn default(mut self, v: impl Into<Value>) -> Self {
        self.default = Some(v.into());
        self
    }
    pub fn same_as_source(mut self, source_type: &str) -> Self {
        self.same_as_source = Some(source_type.into());
        self
    }
    pub fn manual(mut self) -> Self {
        self.manual = true;
        self
    }
}