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 "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 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 },
269 )];
270 if info.capabilities.iter().any(|c| c == crate::CAP_MULTI_FILE) {
271 forms.push((
272 "a multi-file deliver gets a reply and the plugin keeps serving",
273 Request::Deliver {
274 local_path: None,
275 remote_path: None,
276 files: vec![missing("a.csv"), missing("b.csv")],
277 connection: Map::new(),
278 options: Map::new(),
279 },
280 ));
281 }
282 for (name, req) in forms {
283 check(
284 name,
285 (|| {
286 let mut p = start(path).map_err(|e| e.to_string())?;
287 p.send(&req).map_err(|e| e.to_string())?;
288 match p
289 .recv(Some(TIMEOUT), "a deliver reply")
290 .map_err(|e| e.to_string())?
291 {
292 Incoming::Json(Response::Delivered { .. } | Response::Error { .. }) => {}
293 other => return Err(format!("expected delivered or error, got {other:?}")),
294 }
295 p.describe()
296 .map_err(|e| format!("plugin stopped serving after a deliver: {e}"))?;
297 p.close().map_err(|e| e.to_string())
298 })(),
299 );
300 }
301 }
302
303 check(
304 "close ends the process with exit code 0",
305 (|| {
306 let mut p = start(path).map_err(|e| e.to_string())?;
307 p.send(&Request::Close {}).map_err(|e| e.to_string())?;
308 let _ = p.recv(Some(TIMEOUT), "the close reply");
309 match p.wait_exit(TIMEOUT) {
310 Some(s) if s.success() => Ok(()),
311 Some(s) => Err(format!("exited with {s}")),
312 None => Err("still running after close".into()),
313 }
314 })(),
315 );
316
317 check(
318 "end of input ends the process",
319 (|| {
320 let mut p = start(path).map_err(|e| e.to_string())?;
321 match p.wait_exit(TIMEOUT) {
322 Some(_) => Ok(()),
323 None => Err("still running after stdin closed".into()),
324 }
325 })(),
326 );
327
328 out
329}
330
331pub fn assert_conforms(path: &Path) {
333 let checks = run(path);
334 let failed: Vec<String> = checks
335 .iter()
336 .filter(|c| !c.passed)
337 .map(|c| format!(" ✗ {}: {}: {}", c.plugin, c.name, c.detail))
338 .collect();
339 assert!(
340 failed.is_empty(),
341 "{} fails protocol conformance:\n{}",
342 path.display(),
343 failed.join("\n")
344 );
345}
346
347fn frame_json(body: &str) -> Vec<u8> {
348 let mut v = Vec::new();
349 v.extend_from_slice(&((body.len() + 1) as u32).to_be_bytes());
350 v.push(crate::frame::JSON_TAG);
351 v.extend_from_slice(body.as_bytes());
352 v
353}