1use std::io::{BufReader, BufWriter};
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
21use std::sync::mpsc::{Receiver, Sender};
22use std::sync::{Arc, Mutex, OnceLock};
23
24use arrow::array::RecordBatch;
25use arrow::datatypes::SchemaRef;
26use serde_json::{Map, Value};
27
28use crate::frame::{self, Frame, FrameError};
29use crate::msg::{ConnectionField, Envelope, LogLevel, Request, Response, ResultSetMeta};
30use crate::options::{self, OptionField};
31use crate::{CAP_VALIDATE, Kind, MAX_VERSION, MIN_VERSION, PluginId};
32
33pub type Error = Box<dyn std::error::Error + Send + Sync>;
34pub type Result<T> = std::result::Result<T, Error>;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum ErrorKind {
39 Config,
41 Plugin,
43 Refused,
45 Connection,
47 Auth,
49 Query,
51 Delivery,
53 Internal,
55 Cancelled,
56 TimedOut,
57}
58
59impl ErrorKind {
60 pub fn as_str(self) -> &'static str {
61 match self {
62 ErrorKind::Config => "config",
63 ErrorKind::Plugin => "plugin",
64 ErrorKind::Refused => "refused",
65 ErrorKind::Connection => "connection",
66 ErrorKind::Auth => "auth",
67 ErrorKind::Query => "query",
68 ErrorKind::Delivery => "delivery",
69 ErrorKind::Internal => "internal",
70 ErrorKind::Cancelled => "cancelled",
71 ErrorKind::TimedOut => "timed_out",
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct PluginError {
80 pub kind: ErrorKind,
81 pub code: Option<String>,
82 pub message: String,
83}
84
85impl PluginError {
86 pub fn new(kind: ErrorKind, message: impl Into<String>) -> PluginError {
87 PluginError {
88 kind,
89 code: None,
90 message: message.into(),
91 }
92 }
93
94 #[must_use]
95 pub fn code(mut self, code: impl Into<String>) -> PluginError {
96 self.code = Some(code.into());
97 self
98 }
99}
100
101impl std::fmt::Display for PluginError {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.write_str(&self.message)
104 }
105}
106
107impl std::error::Error for PluginError {}
108
109struct Shared {
112 out: Mutex<BufWriter<Box<dyn std::io::Write + Send>>>,
113 version: AtomicU32,
115 current: AtomicU64,
117 cancelled: AtomicU64,
119 hook: Mutex<Option<CancelHook>>,
120 name: OnceLock<String>,
122}
123
124type CancelHook = Arc<dyn Fn() + Send + Sync>;
125
126fn shared() -> &'static Shared {
127 static SHARED: OnceLock<Shared> = OnceLock::new();
128 SHARED.get_or_init(|| Shared {
129 out: Mutex::new(BufWriter::new(protocol_out())),
130 version: AtomicU32::new(0),
131 current: AtomicU64::new(0),
132 cancelled: AtomicU64::new(0),
133 hook: Mutex::new(None),
134 name: OnceLock::new(),
135 })
136}
137
138fn protocol_out() -> Box<dyn std::io::Write + Send> {
142 #[cfg(unix)]
143 {
144 use std::os::fd::FromRawFd;
145 unsafe {
147 let fd = libc::dup(1);
148 if fd >= 0 && libc::dup2(2, 1) >= 0 {
149 return Box::new(std::fs::File::from_raw_fd(fd));
150 }
151 }
152 }
153 #[cfg(windows)]
154 {
155 use std::os::windows::io::FromRawHandle;
156 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
157 use windows_sys::Win32::System::Console::{
158 GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, SetStdHandle,
159 };
160 unsafe {
163 let out = GetStdHandle(STD_OUTPUT_HANDLE);
164 let err = GetStdHandle(STD_ERROR_HANDLE);
165 if !out.is_null() && out != INVALID_HANDLE_VALUE && SetStdHandle(STD_OUTPUT_HANDLE, err) != 0 {
166 return Box::new(std::fs::File::from_raw_handle(out as _));
167 }
168 }
169 }
170 Box::new(std::io::stdout())
171}
172
173pub fn cancelled() -> bool {
175 let s = shared();
176 let current = s.current.load(Ordering::SeqCst);
177 current != 0 && s.cancelled.load(Ordering::SeqCst) == current
178}
179
180pub fn on_cancel(hook: impl Fn() + Send + Sync + 'static) {
188 *shared().hook.lock().unwrap() = Some(Arc::new(hook));
189}
190
191fn cancel(id: u64) {
194 let s = shared();
195 s.cancelled.store(id, Ordering::SeqCst);
196 if id != 0 && s.current.load(Ordering::SeqCst) == id {
197 let hook = s.hook.lock().unwrap().clone();
198 if let Some(hook) = hook {
199 hook();
200 }
201 }
202}
203
204pub fn log_fields(level: LogLevel, message: &str, fields: Map<String, Value>) {
206 let s = shared();
207 if s.version.load(Ordering::SeqCst) == 0 {
208 let prefix = match level {
210 LogLevel::Error | LogLevel::Warn => "warning: ",
211 LogLevel::Info => "info: ",
212 LogLevel::Debug | LogLevel::Trace => "",
213 };
214 eprintln!("{prefix}{message}");
215 return;
216 }
217 send(&Response::Log {
218 level,
219 message: message.to_string(),
220 fields,
221 });
222}
223
224pub fn log(level: LogLevel, message: &str) {
226 log_fields(level, message, Map::new())
227}
228
229pub fn progress(message: Option<&str>, done: Option<u64>, total: Option<u64>) {
231 if shared().version.load(Ordering::SeqCst) == 0 {
232 if let Some(m) = message {
233 log(LogLevel::Info, m);
234 }
235 return;
236 }
237 send(&Response::Progress {
238 message: message.map(str::to_string),
239 done,
240 total,
241 });
242}
243
244struct FrameLogger;
246
247impl ::log::Log for FrameLogger {
248 fn enabled(&self, m: &::log::Metadata) -> bool {
251 m.level() <= ::log::Level::Info || (m.level() <= ::log::Level::Debug && m.target().starts_with("dre"))
252 }
253
254 fn log(&self, r: &::log::Record) {
255 if !self.enabled(r.metadata()) {
256 return;
257 }
258 let level = match r.level() {
259 ::log::Level::Error => LogLevel::Error,
260 ::log::Level::Warn => LogLevel::Warn,
261 ::log::Level::Info => LogLevel::Info,
262 ::log::Level::Debug => LogLevel::Debug,
263 ::log::Level::Trace => LogLevel::Trace,
264 };
265 let level = if r.target().starts_with("dre") {
267 level
268 } else {
269 level.max(LogLevel::Debug)
270 };
271 log(level, &r.args().to_string());
272 }
273
274 fn flush(&self) {}
275}
276
277fn send(r: &Response) {
279 let s = shared();
280 let id = match s.version.load(Ordering::SeqCst) {
281 0 => None,
282 _ => Some(s.current.load(Ordering::SeqCst)).filter(|id| *id != 0),
283 };
284 let mut out = s.out.lock().unwrap();
285 if frame::write_json(&mut *out, &Envelope::new(id, r)).is_err() {
286 std::process::exit(1);
288 }
289}
290
291fn error_reply(e: &Error) -> Response {
294 if cancelled() {
295 return Response::Error {
296 message: e.to_string(),
297 kind: Some("cancelled".into()),
298 code: None,
299 };
300 }
301 match e.downcast_ref::<PluginError>() {
302 Some(pe) => Response::Error {
303 message: pe.message.clone(),
304 kind: Some(pe.kind.as_str().into()),
305 code: pe.code.as_ref().map(|c| match shared().name.get() {
306 Some(name) if !c.contains('/') => format!("{name}/{c}"),
307 _ => c.clone(),
308 }),
309 },
310 None => Response::error(e.to_string()),
311 }
312}
313
314#[derive(Debug, Clone)]
316pub struct About {
317 pub name: &'static str,
318 pub version: &'static str,
319 pub capabilities: &'static [&'static str],
320}
321
322impl About {
323 pub fn new(name: &'static str, version: &'static str) -> About {
325 let version = if version == "0.0.0" { "unreleased" } else { version };
326 About {
327 name,
328 version,
329 capabilities: &[],
330 }
331 }
332
333 #[must_use]
334 pub fn capabilities(mut self, caps: &'static [&'static str]) -> About {
335 self.capabilities = caps;
336 self
337 }
338}
339
340pub trait ResultSink {
343 fn no_result(&mut self, rows_affected: Option<u64>) -> Result<()>;
344 fn begin(&mut self, schema: SchemaRef) -> Result<()>;
345 fn batch(&mut self, batch: RecordBatch) -> Result<bool>;
347}
348
349pub trait Source {
350 fn connection_fields(&self) -> Vec<ConnectionField> {
351 Vec::new()
352 }
353 fn identifier_quote(&self) -> Option<&'static str> {
356 None
357 }
358 fn string_literal(&self) -> Option<&'static str> {
362 None
363 }
364 fn single_writer(&self) -> Option<crate::msg::SingleWriter> {
368 None
369 }
370 fn validate_connection(&self, _connection: &Map<String, Value>) -> Vec<String> {
375 Vec::new()
376 }
377 fn open(&mut self, connection: &Map<String, Value>, read_only: bool) -> Result<()>;
378 fn open_sandboxed(&mut self, connection: &Map<String, Value>) -> Result<()> {
381 self.open(connection, true)
382 }
383 fn execute(&mut self, sql: &str, row_limit: Option<u64>, out: &mut dyn ResultSink) -> Result<()>;
385 fn check(&mut self, _sql: &str) -> Result<()> {
387 Err("this source can't check statements".into())
388 }
389 fn load(&mut self, _name: &str, _data: &mut ResultSet<'_>) -> Result<Loaded> {
392 Err("this source can't load rows".into())
393 }
394 fn close(&mut self) {}
396}
397
398pub struct Loaded {
400 pub relation: String,
402 pub rows: u64,
403 pub warning: Option<String>,
405}
406
407pub struct ResultSet<'a> {
409 pub meta: ResultSetMeta,
410 pub schema: SchemaRef,
411 first: Option<Vec<RecordBatch>>,
412 input: &'a mut Input,
413 done: bool,
414}
415
416impl ResultSet<'_> {
417 pub fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
419 loop {
420 if let Some(first) = self.first.as_mut() {
421 if !first.is_empty() {
422 return Ok(Some(first.remove(0)));
423 }
424 self.first = None;
425 }
426 if self.done {
427 return Ok(None);
428 }
429 match self.input.read()? {
430 Frame::Arrow(ipc) => {
431 let (_, batches) = frame::decode_batches(&ipc)?;
432 self.first = Some(batches);
433 }
434 Frame::Json(v) => match serde_json::from_value::<Request>(v)? {
435 Request::ResultSetEnd {} => {
436 self.done = true;
437 return Ok(None);
438 }
439 other => return Err(format!("expected result data, got {other:?}").into()),
440 },
441 }
442 }
443 }
444
445 fn drain(&mut self) -> Result<()> {
446 while self.next_batch()?.is_some() {}
447 Ok(())
448 }
449}
450
451pub struct WriteRequest {
453 pub path: String,
454 pub format: String,
455 pub options: Map<String, Value>,
456 pub result_sets: Vec<ResultSetMeta>,
457 pub template: Option<Value>,
458 pub font_requests: bool,
459}
460
461pub struct ResultSets<'a> {
463 metas: std::vec::IntoIter<ResultSetMeta>,
464 input: &'a mut Input,
465 warnings: Vec<String>,
466 finished: bool,
467}
468
469impl ResultSets<'_> {
470 pub fn warn(&mut self, message: impl Into<String>) {
472 self.warnings.push(message.into());
473 }
474
475 pub fn request_fonts(
479 &mut self,
480 font: crate::msg::FontRequest,
481 ) -> Result<std::result::Result<Vec<String>, crate::msg::FontError>> {
482 if self.metas.len() != 0 {
483 return Err("read all result sets before requesting fonts".into());
484 }
485 if !self.finished {
486 match self.input.read()? {
487 Frame::Json(v) if v.get("type").and_then(Value::as_str) == Some("finish") => {}
488 other => return Err(format!("expected finish before font request, got {other:?}").into()),
489 }
490 self.finished = true;
491 }
492 send(&Response::NeedFonts { font });
493 match self.input.read()? {
494 Frame::Json(v) => match serde_json::from_value::<crate::msg::Envelope<Request>>(v)?.body {
495 Request::Fonts {
496 paths, error: None, ..
497 } => Ok(Ok(paths)),
498 Request::Fonts {
499 error: Some(message),
500 repeated,
501 ..
502 } => Ok(Err(crate::msg::FontError { message, repeated })),
503 other => Err(format!("expected font paths, got {other:?}").into()),
504 },
505 other => Err(format!("expected font paths, got {other:?}").into()),
506 }
507 }
508
509 pub fn next_set(&mut self) -> Result<Option<ResultSet<'_>>> {
512 let Some(meta) = self.metas.next() else {
513 return Ok(None);
514 };
515 let ipc = match self.input.read()? {
516 Frame::Arrow(ipc) => ipc,
517 Frame::Json(v) => {
518 return Err(format!(
519 "expected an Arrow frame starting result set `{}`, got {v}",
520 meta.name
521 )
522 .into());
523 }
524 };
525 let (schema, batches) = frame::decode_batches(&ipc)?;
526 Ok(Some(ResultSet {
527 meta,
528 schema,
529 first: Some(batches),
530 input: &mut *self.input,
531 done: false,
532 }))
533 }
534}
535
536pub trait Format {
537 fn options(&self) -> Vec<OptionField> {
540 Vec::new()
541 }
542 fn validate(&self, _options: &Map<String, Value>) -> Vec<String> {
545 Vec::new()
546 }
547 fn validate_template(
550 &self,
551 _options: &Map<String, Value>,
552 _template: &Value,
553 ) -> (Vec<String>, Vec<String>) {
554 (Vec::new(), Vec::new())
555 }
556 fn unknown_option_hint(&self, _key: &str) -> Option<String> {
559 None
560 }
561 fn write(&mut self, req: &WriteRequest, sets: &mut ResultSets<'_>) -> Result<Vec<String>>;
564}
565
566pub struct Delivery {
568 pub files: Vec<DeliveryFile>,
571 pub connection: Map<String, Value>,
572 pub options: Map<String, Value>,
574 pub message: Option<crate::msg::Message>,
576}
577
578pub struct DeliveryFile {
580 pub local: PathBuf,
581 pub remote: Option<String>,
582}
583
584pub trait Destination {
585 fn connection_fields(&self) -> Vec<ConnectionField> {
586 Vec::new()
587 }
588 fn options(&self) -> Vec<OptionField> {
592 Vec::new()
593 }
594 fn validate(&self, _options: &Map<String, Value>) -> Vec<String> {
597 Vec::new()
598 }
599 fn validate_connection(&self, _connection: &Map<String, Value>) -> Vec<String> {
603 Vec::new()
604 }
605 fn deliver(
608 &mut self,
609 _local: &Path,
610 _remote: Option<&str>,
611 _connection: &Map<String, Value>,
612 ) -> Result<String> {
613 Err("this destination doesn't implement `deliver`".into())
614 }
615 fn message_limit(&self) -> Option<u64> {
618 None
619 }
620 fn deliver_message(&mut self, _d: &Delivery, _m: &crate::msg::Message) -> Result<String> {
623 Err("this destination doesn't take messages".into())
624 }
625 fn deliver_files(&mut self, d: &Delivery) -> Result<String> {
628 match d.files.as_slice() {
629 [f] => self.deliver(&f.local, f.remote.as_deref(), &d.connection),
630 _ => Err("this destination takes one file per delivery".into()),
631 }
632 }
633}
634
635pub struct Input {
637 rx: Receiver<std::result::Result<Frame, FrameError>>,
638}
639
640impl Input {
641 fn next(&mut self) -> std::result::Result<Frame, FrameError> {
642 self.rx.recv().unwrap_or(Err(FrameError::Eof))
643 }
644
645 fn read(&mut self) -> Result<Frame> {
646 self.next().map_err(|e| -> Error {
647 match e {
648 FrameError::Eof => "core closed the connection".into(),
649 e => e.to_string().into(),
650 }
651 })
652 }
653}
654
655fn read_stdin(tx: Sender<std::result::Result<Frame, FrameError>>) {
658 let mut r = BufReader::new(std::io::stdin());
659 loop {
660 let f = frame::read_frame(&mut r);
661 match &f {
662 Ok(Frame::Json(v)) if v.get("type").and_then(Value::as_str) == Some("cancel") => {
663 cancel(v.get("id").and_then(Value::as_u64).unwrap_or(0));
664 continue;
665 }
666 Err(_) => cancel(shared().current.load(Ordering::SeqCst)),
667 Ok(_) => {}
668 }
669 let stop = f.is_err();
670 if tx.send(f).is_err() || stop {
671 break;
672 }
673 }
674}
675
676struct Output;
678
679impl Output {
680 fn send(&mut self, r: &Response) {
681 send(r)
682 }
683
684 fn batch(&mut self, b: &RecordBatch) -> Result<()> {
685 let ipc = frame::encode_batch(b)?;
686 let mut out = shared().out.lock().unwrap();
687 frame::write_arrow(&mut *out, &ipc).map_err(|_| -> Error { "core closed the connection".into() })
688 }
689}
690
691enum Handler<'a> {
692 Source(&'a mut dyn Source),
693 Format(&'a mut dyn Format),
694 Destination(&'a mut dyn Destination),
695}
696
697impl Handler<'_> {
698 fn kind(&self) -> Kind {
699 match self {
700 Handler::Source(_) => Kind::Source,
701 Handler::Format(_) => Kind::Format,
702 Handler::Destination(_) => Kind::Destination,
703 }
704 }
705
706 fn option_fields(&self) -> Vec<OptionField> {
707 match self {
708 Handler::Source(_) => Vec::new(),
709 Handler::Format(f) => f.options(),
710 Handler::Destination(d) => d.options(),
711 }
712 }
713
714 fn check(&self, name: &str, o: &Map<String, Value>) -> Vec<String> {
717 let mut errs = options::check(self.kind(), name, &self.option_fields(), o);
718 if let Handler::Format(f) = self {
719 for e in &mut errs {
720 let hint = o
721 .keys()
722 .find(|k| e.starts_with(&format!("unknown option `{k}`")))
723 .and_then(|k| f.unknown_option_hint(k));
724 if let Some(h) = hint {
725 e.push_str("; ");
726 e.push_str(&h);
727 }
728 }
729 }
730 if !errs.is_empty() {
731 return errs;
732 }
733 match self {
734 Handler::Source(_) => Vec::new(),
735 Handler::Format(f) => f.validate(o),
736 Handler::Destination(d) => d.validate(o),
737 }
738 }
739
740 fn checked(&self, name: &str, o: &Map<String, Value>) -> Result<()> {
742 let errs = self.check(name, o);
743 if errs.is_empty() {
744 Ok(())
745 } else {
746 Err(PluginError::new(ErrorKind::Config, errs.join("; ")).into())
748 }
749 }
750}
751
752pub fn serve_source(about: About, s: impl Source + 'static) -> ! {
753 serve_package(vec![Plugin::Source(about, Box::new(s))])
754}
755
756pub fn serve_format(about: About, f: impl Format + 'static) -> ! {
757 serve_package(vec![Plugin::Format(about, Box::new(f))])
758}
759
760pub fn serve_destination(about: About, d: impl Destination + 'static) -> ! {
761 serve_package(vec![Plugin::Destination(about, Box::new(d))])
762}
763
764pub enum Plugin {
766 Source(About, Box<dyn Source>),
767 Format(About, Box<dyn Format>),
768 Destination(About, Box<dyn Destination>),
769}
770
771impl Plugin {
772 fn id(&self) -> PluginId {
773 let (kind, about) = match self {
774 Plugin::Source(a, _) => (Kind::Source, a),
775 Plugin::Format(a, _) => (Kind::Format, a),
776 Plugin::Destination(a, _) => (Kind::Destination, a),
777 };
778 PluginId::new(kind, about.name)
779 }
780
781 fn handler(&mut self) -> (&About, Handler<'_>) {
782 match self {
783 Plugin::Source(a, s) => (a, Handler::Source(s.as_mut())),
784 Plugin::Format(a, f) => (a, Handler::Format(f.as_mut())),
785 Plugin::Destination(a, d) => (a, Handler::Destination(d.as_mut())),
786 }
787 }
788}
789
790pub fn serve_package(mut plugins: Vec<Plugin>) -> ! {
797 assert!(!plugins.is_empty(), "a package serves at least one plugin");
798 shared();
800 let (tx, rx) = std::sync::mpsc::channel();
801 std::thread::spawn(move || read_stdin(tx));
802 let mut input = Input { rx };
803 let mut out = Output;
804 if ::log::set_logger(&FrameLogger).is_ok() {
805 ::log::set_max_level(::log::LevelFilter::Debug);
806 }
807 let provides: Vec<PluginId> = plugins.iter().map(Plugin::id).collect();
808 let chosen = loop {
809 let Some(req) = next_request(&mut input, &mut out) else {
810 continue;
811 };
812 let Request::Hello {
813 min_version,
814 max_version,
815 plugin,
816 ..
817 } = req
818 else {
819 out.send(&Response::error("the first request must be `hello`"));
820 continue;
821 };
822 let Some(chosen) = negotiate((min_version, max_version), (MIN_VERSION, MAX_VERSION)) else {
823 out.send(&Response::VersionMismatch {
824 min_version: MIN_VERSION,
825 max_version: MAX_VERSION,
826 });
827 std::process::exit(1);
828 };
829 let i = match &plugin {
830 None => 0,
831 Some(want) => match provides.iter().position(|p| p == want) {
832 Some(i) => i,
833 None => {
834 let list: Vec<String> = provides.iter().map(|p| p.to_string()).collect();
835 out.send(&Response::error(format!(
836 "this executable provides {}, not {want}",
837 list.join(", ")
838 )));
839 std::process::exit(1);
840 }
841 },
842 };
843 let (about, h) = plugins[i].handler();
845 let _ = shared().name.set(about.name.to_string());
846 out.send(&Response::Hello {
847 protocol_version: chosen,
848 kind: h.kind(),
849 name: about.name.to_string(),
850 version: about.version.to_string(),
851 capabilities: about
852 .capabilities
853 .iter()
854 .chain(std::iter::once(&CAP_VALIDATE))
855 .map(|c| c.to_string())
856 .collect(),
857 provides: if provides.len() > 1 { provides } else { Vec::new() },
858 });
859 shared().version.store(chosen, Ordering::SeqCst);
860 break i;
861 };
862 let (about, h) = plugins[chosen].handler();
863 serve(about.name, h, input, out)
864}
865
866fn next_request(input: &mut Input, out: &mut Output) -> Option<Request> {
868 let frame = match input.next() {
869 Ok(f) => f,
870 Err(FrameError::Eof) => std::process::exit(0),
871 Err(e) => {
872 eprintln!("{e}");
873 out.send(&Response::error(e.to_string()));
874 std::process::exit(2);
875 }
876 };
877 match frame {
878 Frame::Json(v) => match serde_json::from_value::<Request>(v.clone()) {
879 Ok(r) => Some(r),
880 Err(_) => {
881 let t = v.get("type").and_then(Value::as_str).unwrap_or("?").to_string();
882 out.send(&Response::error(format!("unsupported request `{t}`")));
883 None
884 }
885 },
886 Frame::Arrow(_) => {
887 out.send(&Response::error("unexpected Arrow frame"));
888 None
889 }
890 }
891}
892
893fn serve(name: &str, mut h: Handler<'_>, mut input: Input, mut out: Output) -> ! {
895 loop {
896 let frame = match input.next() {
897 Ok(f) => f,
898 Err(FrameError::Eof) => {
899 if let Handler::Source(src) = &mut h {
900 src.close();
901 }
902 std::process::exit(0)
903 }
904 Err(e) => {
905 eprintln!("{e}");
906 out.send(&Response::error(e.to_string()));
907 std::process::exit(2);
908 }
909 };
910 let s = shared();
911 let id = match &frame {
912 Frame::Json(v) => v.get("id").and_then(Value::as_u64).unwrap_or(0),
913 Frame::Arrow(_) => 0,
914 };
915 s.current.store(id, Ordering::SeqCst);
916 let req = match frame {
917 Frame::Json(v) => match serde_json::from_value::<Request>(v.clone()) {
918 Ok(r) => r,
919 Err(_) => {
920 let t = v.get("type").and_then(Value::as_str).unwrap_or("?").to_string();
921 out.send(&Response::error(format!("unsupported request `{t}`")));
922 s.current.store(0, Ordering::SeqCst);
923 continue;
924 }
925 },
926 Frame::Arrow(_) => {
927 out.send(&Response::error("unexpected Arrow frame"));
928 continue;
929 }
930 };
931 if let Request::Hello { .. } = req {
932 out.send(&Response::error("`hello` was already answered"));
933 s.current.store(0, Ordering::SeqCst);
934 continue;
935 }
936 if let Request::Close {} = req {
937 if let Handler::Source(src) = &mut h {
938 src.close();
939 }
940 out.send(&Response::Ok {});
941 std::process::exit(0);
942 }
943 let result = if cancelled() {
945 Ok(Err("cancelled before it started".into()))
946 } else {
947 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
950 handle(&mut h, name, req, &mut input, &mut out)
951 }))
952 };
953 match result {
954 Ok(Ok(())) => {}
955 Ok(Err(e)) => out.send(&error_reply(&e)),
956 Err(p) => {
957 let msg = p
958 .downcast_ref::<String>()
959 .cloned()
960 .or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string()))
961 .unwrap_or_else(|| "unknown panic".into());
962 out.send(&Response::Error {
963 message: format!("plugin panicked: {msg}"),
964 kind: Some("internal".into()),
965 code: None,
966 });
967 std::process::exit(101);
968 }
969 }
970 s.current.store(0, Ordering::SeqCst);
971 }
972}
973
974fn check_connection(
977 h: &Handler<'_>,
978 name: &str,
979 connection: &Map<String, Value>,
980 unresolved: &[String],
981) -> Result<crate::connection::Checked> {
982 let (kind, fields) = match h {
983 Handler::Source(s) => (Kind::Source, s.connection_fields()),
984 Handler::Destination(d) => (Kind::Destination, d.connection_fields()),
985 Handler::Format(_) => return Err("a format has no connection settings".into()),
986 };
987 let mut c = crate::connection::check(kind, name, &fields, connection, unresolved);
988 if c.errors.is_empty() {
989 c.errors = match h {
992 Handler::Source(s) => s.validate_connection(connection),
993 Handler::Destination(d) => d.validate_connection(connection),
994 Handler::Format(_) => Vec::new(),
995 };
996 }
997 c.errors = crate::connection::redact(c.errors, &fields, connection);
998 c.warnings = crate::connection::redact(c.warnings, &fields, connection);
999 Ok(c)
1000}
1001
1002fn handle(h: &mut Handler<'_>, name: &str, req: Request, input: &mut Input, out: &mut Output) -> Result<()> {
1003 if let Request::Describe {} = req {
1004 let connection_fields = match h {
1005 Handler::Source(s) => s.connection_fields(),
1006 Handler::Destination(d) => d.connection_fields(),
1007 Handler::Format(_) => Vec::new(),
1008 };
1009 let (identifier_quote, string_literal, single_writer) = match h {
1010 Handler::Source(s) => (
1011 s.identifier_quote().map(str::to_string),
1012 s.string_literal().map(str::to_string),
1013 s.single_writer(),
1014 ),
1015 _ => (None, None, None),
1016 };
1017 let message_limit = match h {
1018 Handler::Destination(d) => d.message_limit(),
1019 _ => None,
1020 };
1021 out.send(&Response::Describe {
1022 connection_fields,
1023 option_fields: h.option_fields(),
1024 identifier_quote,
1025 string_literal,
1026 message_limit,
1027 single_writer,
1028 });
1029 return Ok(());
1030 }
1031 if let Request::Validate { options, template } = req {
1032 let mut errors = h.check(name, &options);
1033 let mut warnings = Vec::new();
1034 if let (Handler::Format(f), Some(t), true) = (&*h, &template, errors.is_empty()) {
1035 let (e, w) = f.validate_template(&options, t);
1036 errors.extend(e);
1037 warnings.extend(w);
1038 }
1039 out.send(&Response::Validated { errors, warnings });
1040 return Ok(());
1041 }
1042 if let Request::ValidateConnection {
1043 connection,
1044 unresolved,
1045 } = req
1046 {
1047 let c = check_connection(h, name, &connection, &unresolved)?;
1048 out.send(&Response::Validated {
1049 errors: c.errors,
1050 warnings: c.warnings,
1051 });
1052 return Ok(());
1053 }
1054 if let Request::Open { connection, .. } | Request::Deliver { connection, .. } = &req {
1056 let c = check_connection(h, name, connection, &[])?;
1057 for w in &c.warnings {
1058 crate::log::warn!("{w}");
1059 }
1060 if !c.errors.is_empty() {
1061 return Err(PluginError::new(ErrorKind::Config, c.errors.join("; ")).into());
1062 }
1063 }
1064 let checked = match &req {
1065 Request::Write { options, .. } | Request::Deliver { options, .. } => h.checked(name, options),
1066 _ => Ok(()),
1067 };
1068 match (h, req) {
1069 (
1070 Handler::Source(s),
1071 Request::Open {
1072 connection,
1073 read_only,
1074 sandbox,
1075 },
1076 ) => {
1077 if sandbox {
1078 s.open_sandboxed(&connection)?;
1079 } else {
1080 s.open(&connection, read_only)?;
1081 }
1082 out.send(&Response::Ok {});
1083 }
1084 (Handler::Source(s), Request::Load { name }) => {
1085 let ipc = match input.read()? {
1086 Frame::Arrow(ipc) => ipc,
1087 Frame::Json(v) => return Err(format!("expected the rows to load, got {v}").into()),
1088 };
1089 let (schema, batches) = frame::decode_batches(&ipc)?;
1090 let mut data = ResultSet {
1091 meta: ResultSetMeta {
1092 name: name.clone(),
1093 query: name.clone(),
1094 result_index: 1,
1095 anchor: None,
1096 header: None,
1097 columns: Default::default(),
1098 autofit: None,
1099 style: None,
1100 },
1101 schema,
1102 first: Some(batches),
1103 input,
1104 done: false,
1105 };
1106 let r = s.load(&name, &mut data);
1107 data.drain()?;
1108 let loaded = r?;
1109 out.send(&Response::Loaded {
1110 relation: loaded.relation,
1111 rows: loaded.rows,
1112 warning: loaded.warning,
1113 });
1114 }
1115 (Handler::Source(s), Request::Check { sql }) => {
1116 s.check(&sql)?;
1117 out.send(&Response::Ok {});
1118 }
1119 (Handler::Source(s), Request::Execute { sql, row_limit }) => {
1120 let mut sink = FrameSink {
1121 out,
1122 row_limit,
1123 rows: 0,
1124 state: SinkState::Idle,
1125 schema: None,
1126 sent_any: false,
1127 };
1128 let r = s.execute(&sql, row_limit, &mut sink);
1129 match (r, sink.state) {
1130 (Err(e), _) => return Err(e),
1131 (Ok(()), SinkState::Idle) => {
1132 return Err("the source produced neither a result nor `no_result`".into());
1133 }
1134 (Ok(()), SinkState::NoResult) => {}
1135 (Ok(()), SinkState::Result) => {
1136 if !sink.sent_any {
1137 let schema = sink.schema.clone().expect("a result sets the schema");
1138 sink.out.batch(&RecordBatch::new_empty(schema))?;
1139 }
1140 let rows = sink.rows;
1141 sink.out.send(&Response::ResultEnd { rows });
1142 }
1143 }
1144 }
1145 (
1146 Handler::Format(f),
1147 Request::Write {
1148 path,
1149 format,
1150 options,
1151 result_sets,
1152 template,
1153 font_requests,
1154 },
1155 ) => {
1156 let req = WriteRequest {
1157 path,
1158 format,
1159 options,
1160 result_sets: result_sets.clone(),
1161 template,
1162 font_requests,
1163 };
1164 let mut sets = ResultSets {
1165 metas: result_sets.into_iter(),
1166 input,
1167 warnings: Vec::new(),
1168 finished: false,
1169 };
1170 let written = checked.and_then(|()| f.write(&req, &mut sets));
1171 if let Err(e) = &written {
1174 out.send(&error_reply(e));
1175 }
1176 while !sets.finished {
1179 match sets.input.read()? {
1180 Frame::Json(v) if v.get("type").and_then(Value::as_str) == Some("finish") => break,
1181 Frame::Json(v) if v.get("type").and_then(Value::as_str) == Some("result_set_end") => {}
1182 Frame::Arrow(_) => {}
1183 other => return Err(format!("expected `finish`, got {other:?}").into()),
1184 }
1185 }
1186 if let Ok(files) = written {
1187 out.send(&Response::Written {
1188 files,
1189 warnings: sets.warnings,
1190 });
1191 }
1192 }
1193 (
1194 Handler::Destination(d),
1195 Request::Deliver {
1196 local_path,
1197 remote_path,
1198 files,
1199 connection,
1200 options,
1201 message,
1202 },
1203 ) => {
1204 checked?;
1205 let files = match (local_path, files.is_empty(), &message) {
1206 (Some(local), true, None) => vec![DeliveryFile {
1207 local: PathBuf::from(local),
1208 remote: remote_path,
1209 }],
1210 (None, false, _) | (None, true, Some(_)) => files
1211 .into_iter()
1212 .map(|f| DeliveryFile {
1213 local: PathBuf::from(f.local_path),
1214 remote: f.remote_path,
1215 })
1216 .collect(),
1217 _ => return Err("`deliver` needs exactly one of `local_path` or `files`".into()),
1218 };
1219 let delivery = Delivery {
1220 files,
1221 connection,
1222 options,
1223 message,
1224 };
1225 crate::delivery::take_attempts();
1226 let location = match &delivery.message {
1227 Some(m) => d.deliver_message(&delivery, m)?,
1228 None => d.deliver_files(&delivery)?,
1229 };
1230 let attempts = Some(crate::delivery::take_attempts()).filter(|n| *n > 1);
1231 out.send(&Response::Delivered { location, attempts });
1232 }
1233 (h, req) => {
1234 let t = serde_json::to_value(&req)
1235 .ok()
1236 .and_then(|v| v.get("type").cloned())
1237 .unwrap_or_default();
1238 return Err(format!("a {} plugin doesn't handle {t} requests", h.kind()).into());
1239 }
1240 }
1241 Ok(())
1242}
1243
1244#[derive(PartialEq)]
1245enum SinkState {
1246 Idle,
1247 NoResult,
1248 Result,
1249}
1250
1251struct FrameSink<'a> {
1252 out: &'a mut Output,
1253 row_limit: Option<u64>,
1254 rows: u64,
1255 state: SinkState,
1256 schema: Option<SchemaRef>,
1257 sent_any: bool,
1258}
1259
1260impl ResultSink for FrameSink<'_> {
1261 fn no_result(&mut self, rows_affected: Option<u64>) -> Result<()> {
1262 if self.state != SinkState::Idle {
1263 return Err("`no_result` after the result started".into());
1264 }
1265 self.state = SinkState::NoResult;
1266 self.out.send(&Response::NoResult { rows_affected });
1267 Ok(())
1268 }
1269
1270 fn begin(&mut self, schema: SchemaRef) -> Result<()> {
1271 if self.state != SinkState::Idle {
1272 return Err("a statement can only produce one result".into());
1273 }
1274 self.state = SinkState::Result;
1275 self.out.send(&Response::Result {
1276 columns: schema.fields().iter().map(|f| f.name().clone()).collect(),
1277 });
1278 self.schema = Some(schema);
1279 Ok(())
1280 }
1281
1282 fn batch(&mut self, b: RecordBatch) -> Result<bool> {
1283 if self.state != SinkState::Result {
1284 return Err("`batch` before `begin`".into());
1285 }
1286 if self.row_limit.is_some_and(|l| self.rows >= l) {
1287 return Ok(false);
1288 }
1289 let b = match self.row_limit {
1290 Some(l) if self.rows + b.num_rows() as u64 > l => b.slice(0, (l - self.rows) as usize),
1291 _ => b,
1292 };
1293 if b.num_rows() > 0 || !self.sent_any {
1294 self.rows += b.num_rows() as u64;
1295 self.out.batch(&b)?;
1296 self.sent_any = true;
1297 }
1298 Ok(self.row_limit.is_none_or(|l| self.rows < l))
1299 }
1300}
1301
1302fn negotiate(core: (u32, u32), ours: (u32, u32)) -> Option<u32> {
1304 let (lo, hi) = (core.0.max(ours.0), core.1.min(ours.1));
1305 (lo <= hi).then_some(hi)
1306}
1307
1308pub fn conn_str<'a>(c: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
1310 c.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
1311}
1312
1313pub fn conn_required<'a>(c: &'a Map<String, Value>, key: &str) -> Result<&'a str> {
1315 conn_str(c, key).ok_or_else(|| format!("the profile output needs a `{key}` field").into())
1316}
1317
1318pub fn conn_bool(c: &Map<String, Value>, key: &str) -> Option<bool> {
1320 match c.get(key)? {
1321 Value::Bool(b) => Some(*b),
1322 Value::String(s) => Some(matches!(s.as_str(), "true" | "yes" | "1")),
1323 _ => None,
1324 }
1325}