Skip to main content

dre_protocol/
conformance.rs

1//! The protocol conformance suite. Every first-party plugin runs it in its tests; third-party
2//! plugin authors can run it too. It only checks protocol behaviour common to every plugin kind;
3//! each plugin's own tests cover what it does with real data. A package executable
4//! (`dre-plugin-<package>`) is checked once per plugin it provides.
5
6// Each check is an immediately-invoked closure so `?` works inside it.
7#![allow(clippy::redundant_closure_call)]
8
9use std::path::Path;
10use std::sync::Arc;
11use std::time::Duration;
12
13use crate::host::{HostError, Incoming, LogSink, PluginProcess};
14use serde_json::{Map, json};
15
16use crate::msg::{DeliveryFile, Request, Response};
17use crate::{MAX_VERSION, MIN_VERSION, PluginId, parse_executable_name, parse_package_executable_name};
18
19const TIMEOUT: Duration = Duration::from_secs(20);
20
21#[derive(Debug)]
22pub struct Check {
23    /// The plugin checked (`<kind>/<name>`), or the package for checks of the package itself.
24    pub plugin: String,
25    pub name: &'static str,
26    pub passed: bool,
27    pub detail: String,
28}
29
30fn quiet() -> LogSink {
31    Arc::new(|_, _| {})
32}
33
34fn start_versions(
35    path: &Path,
36    plugin: Option<&PluginId>,
37    env: &[(&str, &str)],
38    versions: (u32, u32),
39) -> Result<PluginProcess, HostError> {
40    let mut p = PluginProcess::spawn_env(path, quiet(), env)?;
41    if plugin.is_some() {
42        p.ask_for(plugin.cloned());
43    }
44    p.handshake(versions, TIMEOUT)?;
45    Ok(p)
46}
47
48/// Run every check against the plugin executable at `path`.
49pub fn run(path: &Path) -> Vec<Check> {
50    run_with_env(path, &[])
51}
52
53/// Like [`run`], with extra environment variables for every plugin process (for plugins whose
54/// capabilities depend on their environment).
55pub fn run_with_env(path: &Path, env: &[(&str, &str)]) -> Vec<Check> {
56    let file = path.file_name().unwrap().to_string_lossy().to_string();
57    if let Some((kind, name)) = parse_executable_name(&file) {
58        return run_plugin(path, &PluginId::new(kind, name), false, env);
59    }
60    let fail = |detail: String| {
61        vec![Check {
62            plugin: file.clone(),
63            name: "the executable is named dre-plugin-<package> or dre-<kind>-<name>",
64            passed: false,
65            detail,
66        }]
67    };
68    let Some(package) = parse_package_executable_name(&file) else {
69        return fail(format!("`{file}` is neither"));
70    };
71    let provides = match start_versions(path, None, env, (MIN_VERSION, MAX_VERSION)) {
72        Ok(p) => {
73            let provides = p.info().provides.clone();
74            let _ = p.close();
75            provides
76        }
77        Err(e) => return fail(format!("the handshake failed: {e}")),
78    };
79    let mut out = Vec::new();
80    let unknown = PluginId::new(crate::Kind::Format, "dre_conformance_unknown");
81    let refused = match start_versions(path, Some(&unknown), env, (MIN_VERSION, MAX_VERSION)) {
82        Err(HostError::Plugin { .. }) => Ok(()),
83        Err(e) => Err(format!("expected an error reply, got: {e}")),
84        Ok(_) => Err(format!("the package served {unknown}, which it doesn't provide")),
85    };
86    out.push(Check {
87        plugin: package,
88        name: "asking for a plugin the package doesn't provide gets an error reply",
89        passed: refused.is_ok(),
90        detail: refused.err().unwrap_or_default(),
91    });
92    for id in &provides {
93        out.extend(run_plugin(path, id, true, env));
94    }
95    out
96}
97
98/// Every check, for one plugin. `ask`: name it in the handshake (a package's plugins).
99fn run_plugin(path: &Path, id: &PluginId, ask: bool, env: &[(&str, &str)]) -> Vec<Check> {
100    let asked = ask.then_some(id);
101    let start = |path: &Path| start_versions(path, asked, env, (MIN_VERSION, MAX_VERSION));
102    let mut out = Vec::new();
103    let mut check = |name: &'static str, r: Result<(), String>| {
104        out.push(Check {
105            plugin: id.to_string(),
106            name,
107            passed: r.is_ok(),
108            detail: r.err().unwrap_or_default(),
109        });
110    };
111
112    check(
113        "handshake negotiates a supported version and reports its identity",
114        (|| {
115            let p = start(path).map_err(|e| e.to_string())?;
116            let info = p.info().clone();
117            if info.kind != id.kind || info.name != id.name {
118                return Err(format!(
119                    "expected {id}, handshake says {}/{}",
120                    info.kind, info.name
121                ));
122            }
123            if !info.provides.contains(id) {
124                return Err(format!("`provides` doesn't list {id}: {:?}", info.provides));
125            }
126            if info.version.is_empty() {
127                return Err("empty plugin version".into());
128            }
129            p.close().map_err(|e| e.to_string())
130        })(),
131    );
132
133    check(
134        "an unsupported protocol range is refused, not hung on",
135        (|| {
136            let far = MAX_VERSION + 1000;
137            match start_versions(path, asked, env, (far, far)) {
138                Err(HostError::Incompatible { plugin_range, .. }) if plugin_range.1 < far => Ok(()),
139                Err(e) => Err(format!("expected a version mismatch, got: {e}")),
140                Ok(_) => Err("the plugin accepted a protocol version it can't speak".into()),
141            }
142        })(),
143    );
144
145    check(
146        "describe is answered",
147        (|| {
148            let mut p = start(path).map_err(|e| e.to_string())?;
149            p.describe().map_err(|e| e.to_string())?;
150            p.close().map_err(|e| e.to_string())
151        })(),
152    );
153
154    if id.kind == crate::Kind::Source {
155        check(
156            "describe gives the identifier quote character",
157            (|| {
158                let mut p = start(path).map_err(|e| e.to_string())?;
159                let d = p.description().map_err(|e| e.to_string())?;
160                match d.identifier_quote.as_deref() {
161                    Some(q) if q.chars().count() == 1 => {}
162                    Some(q) => return Err(format!("`identifier_quote` must be one character, got {q:?}")),
163                    None => return Err("a source's describe reply has no `identifier_quote`".into()),
164                }
165                p.close().map_err(|e| e.to_string())
166            })(),
167        );
168    }
169
170    check(
171        "validate is advertised, answered, and refuses an option the plugin doesn't declare",
172        (|| {
173            let mut p = start(path).map_err(|e| e.to_string())?;
174            if !p.has(crate::CAP_VALIDATE) {
175                return Err("the plugin doesn't advertise `validate`".into());
176            }
177            let (_, fields) = p.describe_all().map_err(|e| e.to_string())?;
178            p.validate(Map::new()).map_err(|e| e.to_string())?;
179            let key = "dre_conformance_unknown_option";
180            if fields.iter().any(|f| f.name == key) {
181                return Err(format!("the plugin declares `{key}`"));
182            }
183            let errors = p
184                .validate(json!({key: true}).as_object().unwrap().clone())
185                .map_err(|e| e.to_string())?;
186            if !errors.iter().any(|e| e.contains(key)) {
187                return Err(format!("an unknown option was accepted: {errors:?}"));
188            }
189            p.close().map_err(|e| e.to_string())
190        })(),
191    );
192
193    check(
194        "an unknown request gets an error reply and the plugin keeps serving",
195        (|| {
196            let mut p = start(path).map_err(|e| e.to_string())?;
197            p.write_raw(&frame_json(r#"{"type":"frobnicate"}"#))
198                .map_err(|e| e.to_string())?;
199            match p
200                .recv(Some(TIMEOUT), "an error reply")
201                .map_err(|e| e.to_string())?
202            {
203                Incoming::Json(Response::Error { .. }) => {}
204                other => return Err(format!("expected an error reply, got {other:?}")),
205            }
206            p.describe()
207                .map_err(|e| format!("plugin stopped serving after an unknown request: {e}"))?;
208            p.close().map_err(|e| e.to_string())
209        })(),
210    );
211
212    check(
213        "a request meant for another plugin kind gets an error reply",
214        (|| {
215            let mut p = start(path).map_err(|e| e.to_string())?;
216            let req = match p.info().kind {
217                crate::Kind::Source => Request::Finish {},
218                _ => Request::Check {
219                    sql: "select 1".into(),
220                },
221            };
222            p.send(&req).map_err(|e| e.to_string())?;
223            match p
224                .recv(Some(TIMEOUT), "an error reply")
225                .map_err(|e| e.to_string())?
226            {
227                Incoming::Json(Response::Error { .. }) => {}
228                other => return Err(format!("expected an error reply, got {other:?}")),
229            }
230            p.close().map_err(|e| e.to_string())
231        })(),
232    );
233
234    check(
235        "a malformed frame is reported or ends the plugin, never hangs",
236        (|| {
237            let mut p = start(path).map_err(|e| e.to_string())?;
238            let _ = p.write_raw(&[0, 0, 0, 2, b'X', b'!']);
239            match p.recv(Some(TIMEOUT), "a reply to a malformed frame") {
240                Ok(Incoming::Json(Response::Error { .. })) | Err(HostError::Crashed { .. }) => Ok(()),
241                Err(HostError::Timeout { .. }) => Err("the plugin hung on a malformed frame".into()),
242                other => Err(format!("unexpected reply to a malformed frame: {other:?}")),
243            }
244        })(),
245    );
246
247    // Destinations: `deliver` with options (and, with `multi_file`, several files) is parsed and
248    // answered. The file doesn't exist, so a delivered or an error reply are both fine.
249    let destination = start(path).ok().map(|p| {
250        let info = p.info().clone();
251        let _ = p.close();
252        info
253    });
254    if let Some(info) = destination.filter(|i| i.kind == crate::Kind::Destination) {
255        let missing = |n: &str| DeliveryFile {
256            local_path: format!("/nonexistent/dre-conformance/{n}"),
257            remote_path: Some(format!("dre-conformance/{n}")),
258        };
259        let one = missing("a.csv");
260        let mut forms = vec![(
261            "deliver with options gets a reply and the plugin keeps serving",
262            Request::Deliver {
263                local_path: Some(one.local_path),
264                remote_path: one.remote_path,
265                files: Vec::new(),
266                connection: Map::new(),
267                options: json!({"conformance": true}).as_object().unwrap().clone(),
268                message: None,
269            },
270        )];
271        if info.capabilities.iter().any(|c| c == crate::CAP_MULTI_FILE) {
272            forms.push((
273                "a multi-file deliver gets a reply and the plugin keeps serving",
274                Request::Deliver {
275                    local_path: None,
276                    remote_path: None,
277                    files: vec![missing("a.csv"), missing("b.csv")],
278                    connection: Map::new(),
279                    options: Map::new(),
280                    message: None,
281                },
282            ));
283        }
284        let has = |c: &str| info.capabilities.iter().any(|x| x == c);
285        if has(crate::CAP_MESSAGE) {
286            forms.push((
287                "a message deliver gets a reply and the plugin keeps serving",
288                Request::Deliver {
289                    local_path: None,
290                    remote_path: None,
291                    files: Vec::new(),
292                    connection: Map::new(),
293                    options: Map::new(),
294                    message: Some(crate::msg::Message {
295                        title: "Conformance".into(),
296                        text: "**DRE** conformance check".into(),
297                        html: None,
298                        path: "/nonexistent/dre-conformance/message.md".into(),
299                    }),
300                },
301            ));
302        }
303        if has(crate::CAP_MESSAGE_ONLY) {
304            check(
305                "a message_only plugin also advertises message",
306                if has(crate::CAP_MESSAGE) {
307                    Ok(())
308                } else {
309                    Err("advertises `message_only` without `message`".into())
310                },
311            );
312            check(
313                "a message_only plugin refuses a file deliver and keeps serving",
314                (|| {
315                    let mut p = start(path).map_err(|e| e.to_string())?;
316                    let f = missing("a.csv");
317                    p.send(&Request::Deliver {
318                        local_path: Some(f.local_path),
319                        remote_path: f.remote_path,
320                        files: Vec::new(),
321                        connection: Map::new(),
322                        options: Map::new(),
323                        message: None,
324                    })
325                    .map_err(|e| e.to_string())?;
326                    match p
327                        .recv(Some(TIMEOUT), "a deliver reply")
328                        .map_err(|e| e.to_string())?
329                    {
330                        Incoming::Json(Response::Error { .. }) => {}
331                        other => return Err(format!("expected an error, got {other:?}")),
332                    }
333                    p.describe()
334                        .map_err(|e| format!("plugin stopped serving after a deliver: {e}"))?;
335                    p.close().map_err(|e| e.to_string())
336                })(),
337            );
338        }
339        for (name, req) in forms {
340            check(
341                name,
342                (|| {
343                    let mut p = start(path).map_err(|e| e.to_string())?;
344                    p.send(&req).map_err(|e| e.to_string())?;
345                    match p
346                        .recv(Some(TIMEOUT), "a deliver reply")
347                        .map_err(|e| e.to_string())?
348                    {
349                        Incoming::Json(Response::Delivered { .. } | Response::Error { .. }) => {}
350                        other => return Err(format!("expected delivered or error, got {other:?}")),
351                    }
352                    p.describe()
353                        .map_err(|e| format!("plugin stopped serving after a deliver: {e}"))?;
354                    p.close().map_err(|e| e.to_string())
355                })(),
356            );
357        }
358    }
359
360    check(
361        "close ends the process with exit code 0",
362        (|| {
363            let mut p = start(path).map_err(|e| e.to_string())?;
364            p.send(&Request::Close {}).map_err(|e| e.to_string())?;
365            let _ = p.recv(Some(TIMEOUT), "the close reply");
366            match p.wait_exit(TIMEOUT) {
367                Some(s) if s.success() => Ok(()),
368                Some(s) => Err(format!("exited with {s}")),
369                None => Err("still running after close".into()),
370            }
371        })(),
372    );
373
374    check(
375        "end of input ends the process",
376        (|| {
377            let mut p = start(path).map_err(|e| e.to_string())?;
378            match p.wait_exit(TIMEOUT) {
379                Some(_) => Ok(()),
380                None => Err("still running after stdin closed".into()),
381            }
382        })(),
383    );
384
385    out
386}
387
388/// Panic with a readable report unless every check passes. For use in plugin tests.
389pub fn assert_conforms(path: &Path) {
390    let checks = run(path);
391    let failed: Vec<String> = checks
392        .iter()
393        .filter(|c| !c.passed)
394        .map(|c| format!("  ✗ {}: {}: {}", c.plugin, c.name, c.detail))
395        .collect();
396    assert!(
397        failed.is_empty(),
398        "{} fails protocol conformance:\n{}",
399        path.display(),
400        failed.join("\n")
401    );
402}
403
404fn frame_json(body: &str) -> Vec<u8> {
405    let mut v = Vec::new();
406    v.extend_from_slice(&((body.len() + 1) as u32).to_be_bytes());
407    v.push(crate::frame::JSON_TAG);
408    v.extend_from_slice(body.as_bytes());
409    v
410}