1#![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 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
48pub fn run(path: &Path) -> Vec<Check> {
50 run_with_env(path, &[])
51}
52
53pub 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
98fn 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 "protocol 0 is still spoken, for an older core",
147 (|| {
148 let p = start_versions(path, asked, env, (0, 0)).map_err(|e| e.to_string())?;
149 match p.info().protocol_version {
150 0 => p.close().map_err(|e| e.to_string()),
151 v => Err(format!("offered only version 0, the plugin chose {v}")),
152 }
153 })(),
154 );
155
156 check(
157 "protocol 1 is spoken",
158 (|| {
159 let p = start(path).map_err(|e| e.to_string())?;
160 match p.info().protocol_version {
161 v if v >= 1 => p.close().map_err(|e| e.to_string()),
162 v => Err(format!(
163 "offered versions up to {MAX_VERSION}, the plugin chose {v}"
164 )),
165 }
166 })(),
167 );
168
169 check(
170 "replies carry the request's id, and a cancel for a request that isn't running is ignored",
171 (|| {
172 let mut p = start(path).map_err(|e| e.to_string())?;
173 p.write_raw(&frame_json(r#"{"type":"cancel","id":999}"#))
174 .map_err(|e| e.to_string())?;
175 for (req, want) in [
176 (r#"{"type":"describe","id":41}"#, "describe"),
177 (r#"{"type":"frobnicate","id":42}"#, "error"),
178 ] {
179 p.write_raw(&frame_json(req)).map_err(|e| e.to_string())?;
180 let v = p.recv_raw(TIMEOUT).map_err(|e| e.to_string())?;
181 let id = req[req.len() - 3..req.len() - 1].parse::<u64>().unwrap();
182 if v["type"] != want || v["id"] != id {
183 return Err(format!(
184 "sent {req}, expected a `{want}` reply with id {id}, got {v}"
185 ));
186 }
187 }
188 p.close().map_err(|e| e.to_string())
189 })(),
190 );
191
192 check(
193 "describe is answered",
194 (|| {
195 let mut p = start(path).map_err(|e| e.to_string())?;
196 p.describe().map_err(|e| e.to_string())?;
197 p.close().map_err(|e| e.to_string())
198 })(),
199 );
200
201 if id.kind == crate::Kind::Source {
202 check(
203 "describe gives the identifier quote character",
204 (|| {
205 let mut p = start(path).map_err(|e| e.to_string())?;
206 let d = p.description().map_err(|e| e.to_string())?;
207 match d.identifier_quote.as_deref() {
208 Some(q) if q.chars().count() == 1 => {}
209 Some(q) => return Err(format!("`identifier_quote` must be one character, got {q:?}")),
210 None => return Err("a source's describe reply has no `identifier_quote`".into()),
211 }
212 p.close().map_err(|e| e.to_string())
213 })(),
214 );
215 }
216
217 check(
218 "validate is advertised, answered, and refuses an option the plugin doesn't declare",
219 (|| {
220 let mut p = start(path).map_err(|e| e.to_string())?;
221 if !p.has(crate::CAP_VALIDATE) {
222 return Err("the plugin doesn't advertise `validate`".into());
223 }
224 let (_, fields) = p.describe_all().map_err(|e| e.to_string())?;
225 p.validate(Map::new()).map_err(|e| e.to_string())?;
226 let key = "dre_conformance_unknown_option";
227 if fields.iter().any(|f| f.name == key) {
228 return Err(format!("the plugin declares `{key}`"));
229 }
230 let errors = p
231 .validate(json!({key: true}).as_object().unwrap().clone())
232 .map_err(|e| e.to_string())?;
233 if !errors.iter().any(|e| e.contains(key)) {
234 return Err(format!("an unknown option was accepted: {errors:?}"));
235 }
236 p.close().map_err(|e| e.to_string())
237 })(),
238 );
239
240 if id.kind != crate::Kind::Format {
241 check(
242 "validate_connection is answered without connecting, and an unknown key only warns",
243 (|| {
244 let mut p = start(path).map_err(|e| e.to_string())?;
245 let key = "dre_conformance_unknown_key";
246 let (_, warnings) = p
247 .validate_connection(json!({key: true}).as_object().unwrap().clone(), Vec::new())
248 .map_err(|e| e.to_string())?;
249 if !warnings.iter().any(|w| w.contains(key)) {
250 return Err(format!("an unknown key gave no warning: {warnings:?}"));
251 }
252 p.close().map_err(|e| e.to_string())
253 })(),
254 );
255 }
256
257 check(
258 "an unknown request gets an error reply and the plugin keeps serving",
259 (|| {
260 let mut p = start(path).map_err(|e| e.to_string())?;
261 p.write_raw(&frame_json(r#"{"type":"frobnicate"}"#))
262 .map_err(|e| e.to_string())?;
263 match p
264 .recv(Some(TIMEOUT), "an error reply")
265 .map_err(|e| e.to_string())?
266 {
267 Incoming::Json(Response::Error { .. }) => {}
268 other => return Err(format!("expected an error reply, got {other:?}")),
269 }
270 p.describe()
271 .map_err(|e| format!("plugin stopped serving after an unknown request: {e}"))?;
272 p.close().map_err(|e| e.to_string())
273 })(),
274 );
275
276 check(
277 "a request meant for another plugin kind gets an error reply",
278 (|| {
279 let mut p = start(path).map_err(|e| e.to_string())?;
280 let req = match p.info().kind {
281 crate::Kind::Source => Request::Finish {},
282 _ => Request::Check {
283 sql: "select 1".into(),
284 },
285 };
286 p.send(&req).map_err(|e| e.to_string())?;
287 match p
288 .recv(Some(TIMEOUT), "an error reply")
289 .map_err(|e| e.to_string())?
290 {
291 Incoming::Json(Response::Error { .. }) => {}
292 other => return Err(format!("expected an error reply, got {other:?}")),
293 }
294 p.close().map_err(|e| e.to_string())
295 })(),
296 );
297
298 check(
299 "a malformed frame is reported or ends the plugin, never hangs",
300 (|| {
301 let mut p = start(path).map_err(|e| e.to_string())?;
302 let _ = p.write_raw(&[0, 0, 0, 2, b'X', b'!']);
303 match p.recv(Some(TIMEOUT), "a reply to a malformed frame") {
304 Ok(Incoming::Json(Response::Error { .. })) | Err(HostError::Crashed { .. }) => Ok(()),
305 Err(HostError::Timeout { .. }) => Err("the plugin hung on a malformed frame".into()),
306 other => Err(format!("unexpected reply to a malformed frame: {other:?}")),
307 }
308 })(),
309 );
310
311 let destination = start(path).ok().map(|p| {
314 let info = p.info().clone();
315 let _ = p.close();
316 info
317 });
318 if let Some(info) = destination.filter(|i| i.kind == crate::Kind::Destination) {
319 let missing = |n: &str| DeliveryFile {
320 local_path: format!("/nonexistent/dre-conformance/{n}"),
321 remote_path: Some(format!("dre-conformance/{n}")),
322 };
323 let one = missing("a.csv");
324 let mut forms = vec![(
325 "deliver with options gets a reply and the plugin keeps serving",
326 Request::Deliver {
327 local_path: Some(one.local_path),
328 remote_path: one.remote_path,
329 files: Vec::new(),
330 connection: Map::new(),
331 options: json!({"conformance": true}).as_object().unwrap().clone(),
332 message: None,
333 },
334 )];
335 if info.capabilities.iter().any(|c| c == crate::CAP_MULTI_FILE) {
336 forms.push((
337 "a multi-file deliver gets a reply and the plugin keeps serving",
338 Request::Deliver {
339 local_path: None,
340 remote_path: None,
341 files: vec![missing("a.csv"), missing("b.csv")],
342 connection: Map::new(),
343 options: Map::new(),
344 message: None,
345 },
346 ));
347 }
348 let has = |c: &str| info.capabilities.iter().any(|x| x == c);
349 if has(crate::CAP_MESSAGE) {
350 forms.push((
351 "a message deliver gets a reply and the plugin keeps serving",
352 Request::Deliver {
353 local_path: None,
354 remote_path: None,
355 files: Vec::new(),
356 connection: Map::new(),
357 options: Map::new(),
358 message: Some(crate::msg::Message {
359 title: "Conformance".into(),
360 text: "**DRE** conformance check".into(),
361 html: None,
362 path: "/nonexistent/dre-conformance/message.md".into(),
363 }),
364 },
365 ));
366 }
367 if has(crate::CAP_MESSAGE_ONLY) {
368 check(
369 "a message_only plugin also advertises message",
370 if has(crate::CAP_MESSAGE) {
371 Ok(())
372 } else {
373 Err("advertises `message_only` without `message`".into())
374 },
375 );
376 check(
377 "a message_only plugin refuses a file deliver and keeps serving",
378 (|| {
379 let mut p = start(path).map_err(|e| e.to_string())?;
380 let f = missing("a.csv");
381 p.send(&Request::Deliver {
382 local_path: Some(f.local_path),
383 remote_path: f.remote_path,
384 files: Vec::new(),
385 connection: Map::new(),
386 options: Map::new(),
387 message: None,
388 })
389 .map_err(|e| e.to_string())?;
390 match p
391 .recv(Some(TIMEOUT), "a deliver reply")
392 .map_err(|e| e.to_string())?
393 {
394 Incoming::Json(Response::Error { .. }) => {}
395 other => return Err(format!("expected an error, got {other:?}")),
396 }
397 p.describe()
398 .map_err(|e| format!("plugin stopped serving after a deliver: {e}"))?;
399 p.close().map_err(|e| e.to_string())
400 })(),
401 );
402 }
403 for (name, req) in forms {
404 check(
405 name,
406 (|| {
407 let mut p = start(path).map_err(|e| e.to_string())?;
408 p.send(&req).map_err(|e| e.to_string())?;
409 match p
410 .recv(Some(TIMEOUT), "a deliver reply")
411 .map_err(|e| e.to_string())?
412 {
413 Incoming::Json(Response::Delivered { .. } | Response::Error { .. }) => {}
414 other => return Err(format!("expected delivered or error, got {other:?}")),
415 }
416 p.describe()
417 .map_err(|e| format!("plugin stopped serving after a deliver: {e}"))?;
418 p.close().map_err(|e| e.to_string())
419 })(),
420 );
421 }
422 }
423
424 check(
425 "close ends the process with exit code 0",
426 (|| {
427 let mut p = start(path).map_err(|e| e.to_string())?;
428 p.send(&Request::Close {}).map_err(|e| e.to_string())?;
429 let _ = p.recv(Some(TIMEOUT), "the close reply");
430 match p.wait_exit(TIMEOUT) {
431 Some(s) if s.success() => Ok(()),
432 Some(s) => Err(format!("exited with {s}")),
433 None => Err("still running after close".into()),
434 }
435 })(),
436 );
437
438 check(
439 "end of input ends the process",
440 (|| {
441 let mut p = start(path).map_err(|e| e.to_string())?;
442 match p.wait_exit(TIMEOUT) {
443 Some(_) => Ok(()),
444 None => Err("still running after stdin closed".into()),
445 }
446 })(),
447 );
448
449 out
450}
451
452pub fn assert_conforms(path: &Path) {
454 let checks = run(path);
455 let failed: Vec<String> = checks
456 .iter()
457 .filter(|c| !c.passed)
458 .map(|c| format!(" ✗ {}: {}: {}", c.plugin, c.name, c.detail))
459 .collect();
460 assert!(
461 failed.is_empty(),
462 "{} fails protocol conformance:\n{}",
463 path.display(),
464 failed.join("\n")
465 );
466}
467
468fn frame_json(body: &str) -> Vec<u8> {
469 let mut v = Vec::new();
470 v.extend_from_slice(&((body.len() + 1) as u32).to_be_bytes());
471 v.push(crate::frame::JSON_TAG);
472 v.extend_from_slice(body.as_bytes());
473 v
474}