1use std::io::{BufReader, BufWriter, Stdout};
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 pub fn code(mut self, code: impl Into<String>) -> PluginError {
95 self.code = Some(code.into());
96 self
97 }
98}
99
100impl std::fmt::Display for PluginError {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 f.write_str(&self.message)
103 }
104}
105
106impl std::error::Error for PluginError {}
107
108struct Shared {
111 out: Mutex<BufWriter<Stdout>>,
112 version: AtomicU32,
114 current: AtomicU64,
116 cancelled: AtomicU64,
118 hook: Mutex<Option<CancelHook>>,
119 name: OnceLock<String>,
121}
122
123type CancelHook = Arc<dyn Fn() + Send + Sync>;
124
125fn shared() -> &'static Shared {
126 static SHARED: OnceLock<Shared> = OnceLock::new();
127 SHARED.get_or_init(|| Shared {
128 out: Mutex::new(BufWriter::new(std::io::stdout())),
129 version: AtomicU32::new(0),
130 current: AtomicU64::new(0),
131 cancelled: AtomicU64::new(0),
132 hook: Mutex::new(None),
133 name: OnceLock::new(),
134 })
135}
136
137pub fn cancelled() -> bool {
139 let s = shared();
140 let current = s.current.load(Ordering::SeqCst);
141 current != 0 && s.cancelled.load(Ordering::SeqCst) == current
142}
143
144pub fn on_cancel(hook: impl Fn() + Send + Sync + 'static) {
148 *shared().hook.lock().unwrap() = Some(Arc::new(hook));
149}
150
151fn cancel(id: u64) {
154 let s = shared();
155 s.cancelled.store(id, Ordering::SeqCst);
156 if id != 0 && s.current.load(Ordering::SeqCst) == id {
157 let hook = s.hook.lock().unwrap().clone();
158 if let Some(hook) = hook {
159 hook();
160 }
161 }
162}
163
164pub fn log_fields(level: LogLevel, message: &str, fields: Map<String, Value>) {
166 let s = shared();
167 if s.version.load(Ordering::SeqCst) == 0 {
168 let prefix = match level {
170 LogLevel::Error | LogLevel::Warn => "warning: ",
171 LogLevel::Info => "info: ",
172 LogLevel::Debug | LogLevel::Trace => "",
173 };
174 eprintln!("{prefix}{message}");
175 return;
176 }
177 send(&Response::Log {
178 level,
179 message: message.to_string(),
180 fields,
181 });
182}
183
184pub fn log(level: LogLevel, message: &str) {
186 log_fields(level, message, Map::new())
187}
188
189pub fn progress(message: Option<&str>, done: Option<u64>, total: Option<u64>) {
191 if shared().version.load(Ordering::SeqCst) == 0 {
192 if let Some(m) = message {
193 log(LogLevel::Info, m);
194 }
195 return;
196 }
197 send(&Response::Progress {
198 message: message.map(str::to_string),
199 done,
200 total,
201 });
202}
203
204struct FrameLogger;
206
207impl ::log::Log for FrameLogger {
208 fn enabled(&self, m: &::log::Metadata) -> bool {
209 m.level() <= ::log::Level::Debug
210 }
211
212 fn log(&self, r: &::log::Record) {
213 if !self.enabled(r.metadata()) {
214 return;
215 }
216 let level = match r.level() {
217 ::log::Level::Error => LogLevel::Error,
218 ::log::Level::Warn => LogLevel::Warn,
219 ::log::Level::Info => LogLevel::Info,
220 ::log::Level::Debug => LogLevel::Debug,
221 ::log::Level::Trace => LogLevel::Trace,
222 };
223 let level = if r.target().starts_with("dre") {
225 level
226 } else {
227 level.max(LogLevel::Debug)
228 };
229 log(level, &r.args().to_string());
230 }
231
232 fn flush(&self) {}
233}
234
235fn send(r: &Response) {
237 let s = shared();
238 let id = match s.version.load(Ordering::SeqCst) {
239 0 => None,
240 _ => Some(s.current.load(Ordering::SeqCst)).filter(|id| *id != 0),
241 };
242 let mut out = s.out.lock().unwrap();
243 if frame::write_json(&mut *out, &Envelope::new(id, r)).is_err() {
244 std::process::exit(1);
246 }
247}
248
249fn error_reply(e: &Error) -> Response {
252 if cancelled() {
253 return Response::Error {
254 message: e.to_string(),
255 kind: Some("cancelled".into()),
256 code: None,
257 };
258 }
259 match e.downcast_ref::<PluginError>() {
260 Some(pe) => Response::Error {
261 message: pe.message.clone(),
262 kind: Some(pe.kind.as_str().into()),
263 code: pe.code.as_ref().map(|c| match shared().name.get() {
264 Some(name) if !c.contains('/') => format!("{name}/{c}"),
265 _ => c.clone(),
266 }),
267 },
268 None => Response::error(e.to_string()),
269 }
270}
271
272#[derive(Debug, Clone)]
274pub struct About {
275 pub name: &'static str,
276 pub version: &'static str,
277 pub capabilities: &'static [&'static str],
278}
279
280impl About {
281 pub fn new(name: &'static str, version: &'static str) -> About {
283 let version = if version == "0.0.0" { "unreleased" } else { version };
284 About {
285 name,
286 version,
287 capabilities: &[],
288 }
289 }
290
291 pub fn capabilities(mut self, caps: &'static [&'static str]) -> About {
292 self.capabilities = caps;
293 self
294 }
295}
296
297pub trait ResultSink {
300 fn no_result(&mut self, rows_affected: Option<u64>) -> Result<()>;
301 fn begin(&mut self, schema: SchemaRef) -> Result<()>;
302 fn batch(&mut self, batch: RecordBatch) -> Result<bool>;
304}
305
306pub trait Source {
307 fn connection_fields(&self) -> Vec<ConnectionField> {
308 Vec::new()
309 }
310 fn identifier_quote(&self) -> Option<&'static str> {
313 None
314 }
315 fn validate_connection(&self, _connection: &Map<String, Value>) -> Vec<String> {
320 Vec::new()
321 }
322 fn open(&mut self, connection: &Map<String, Value>, read_only: bool) -> Result<()>;
323 fn execute(&mut self, sql: &str, row_limit: Option<u64>, out: &mut dyn ResultSink) -> Result<()>;
325 fn check(&mut self, _sql: &str) -> Result<()> {
327 Err("this source can't check statements".into())
328 }
329 fn load(&mut self, _name: &str, _data: &mut ResultSet<'_>) -> Result<Loaded> {
332 Err("this source can't load rows".into())
333 }
334 fn close(&mut self) {}
336}
337
338pub struct Loaded {
340 pub relation: String,
342 pub rows: u64,
343 pub warning: Option<String>,
345}
346
347pub struct ResultSet<'a> {
349 pub meta: ResultSetMeta,
350 pub schema: SchemaRef,
351 first: Option<Vec<RecordBatch>>,
352 input: &'a mut Input,
353 done: bool,
354}
355
356impl ResultSet<'_> {
357 pub fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
359 loop {
360 if let Some(first) = self.first.as_mut() {
361 if !first.is_empty() {
362 return Ok(Some(first.remove(0)));
363 }
364 self.first = None;
365 }
366 if self.done {
367 return Ok(None);
368 }
369 match self.input.read()? {
370 Frame::Arrow(ipc) => {
371 let (_, batches) = frame::decode_batches(&ipc)?;
372 self.first = Some(batches);
373 }
374 Frame::Json(v) => match serde_json::from_value::<Request>(v)? {
375 Request::ResultSetEnd {} => {
376 self.done = true;
377 return Ok(None);
378 }
379 other => return Err(format!("expected result data, got {other:?}").into()),
380 },
381 }
382 }
383 }
384
385 fn drain(&mut self) -> Result<()> {
386 while self.next_batch()?.is_some() {}
387 Ok(())
388 }
389}
390
391pub struct WriteRequest {
393 pub path: String,
394 pub format: String,
395 pub options: Map<String, Value>,
396 pub result_sets: Vec<ResultSetMeta>,
397 pub template: Option<Value>,
398}
399
400pub struct ResultSets<'a> {
402 metas: std::vec::IntoIter<ResultSetMeta>,
403 input: &'a mut Input,
404 warnings: Vec<String>,
405}
406
407impl ResultSets<'_> {
408 pub fn warn(&mut self, message: impl Into<String>) {
410 self.warnings.push(message.into());
411 }
412
413 pub fn next_set(&mut self) -> Result<Option<ResultSet<'_>>> {
416 let Some(meta) = self.metas.next() else {
417 return Ok(None);
418 };
419 let ipc = match self.input.read()? {
420 Frame::Arrow(ipc) => ipc,
421 Frame::Json(v) => {
422 return Err(format!(
423 "expected an Arrow frame starting result set `{}`, got {v}",
424 meta.name
425 )
426 .into());
427 }
428 };
429 let (schema, batches) = frame::decode_batches(&ipc)?;
430 Ok(Some(ResultSet {
431 meta,
432 schema,
433 first: Some(batches),
434 input: &mut *self.input,
435 done: false,
436 }))
437 }
438}
439
440pub trait Format {
441 fn options(&self) -> Vec<OptionField> {
444 Vec::new()
445 }
446 fn validate(&self, _options: &Map<String, Value>) -> Vec<String> {
449 Vec::new()
450 }
451 fn write(&mut self, req: &WriteRequest, sets: &mut ResultSets<'_>) -> Result<Vec<String>>;
454}
455
456pub struct Delivery {
458 pub files: Vec<DeliveryFile>,
461 pub connection: Map<String, Value>,
462 pub options: Map<String, Value>,
464 pub message: Option<crate::msg::Message>,
466}
467
468pub struct DeliveryFile {
470 pub local: PathBuf,
471 pub remote: Option<String>,
472}
473
474pub trait Destination {
475 fn connection_fields(&self) -> Vec<ConnectionField> {
476 Vec::new()
477 }
478 fn options(&self) -> Vec<OptionField> {
482 Vec::new()
483 }
484 fn validate(&self, _options: &Map<String, Value>) -> Vec<String> {
487 Vec::new()
488 }
489 fn validate_connection(&self, _connection: &Map<String, Value>) -> Vec<String> {
493 Vec::new()
494 }
495 fn deliver(
498 &mut self,
499 _local: &Path,
500 _remote: Option<&str>,
501 _connection: &Map<String, Value>,
502 ) -> Result<String> {
503 Err("this destination doesn't implement `deliver`".into())
504 }
505 fn message_limit(&self) -> Option<u64> {
508 None
509 }
510 fn deliver_message(&mut self, _d: &Delivery, _m: &crate::msg::Message) -> Result<String> {
513 Err("this destination doesn't take messages".into())
514 }
515 fn deliver_files(&mut self, d: &Delivery) -> Result<String> {
518 match d.files.as_slice() {
519 [f] => self.deliver(&f.local, f.remote.as_deref(), &d.connection),
520 _ => Err("this destination takes one file per delivery".into()),
521 }
522 }
523}
524
525pub struct Input {
527 rx: Receiver<std::result::Result<Frame, FrameError>>,
528}
529
530impl Input {
531 fn next(&mut self) -> std::result::Result<Frame, FrameError> {
532 self.rx.recv().unwrap_or(Err(FrameError::Eof))
533 }
534
535 fn read(&mut self) -> Result<Frame> {
536 self.next().map_err(|e| -> Error {
537 match e {
538 FrameError::Eof => "core closed the connection".into(),
539 e => e.to_string().into(),
540 }
541 })
542 }
543}
544
545fn read_stdin(tx: Sender<std::result::Result<Frame, FrameError>>) {
548 let mut r = BufReader::new(std::io::stdin());
549 loop {
550 let f = frame::read_frame(&mut r);
551 match &f {
552 Ok(Frame::Json(v)) if v.get("type").and_then(Value::as_str) == Some("cancel") => {
553 cancel(v.get("id").and_then(Value::as_u64).unwrap_or(0));
554 continue;
555 }
556 Err(_) => cancel(shared().current.load(Ordering::SeqCst)),
557 Ok(_) => {}
558 }
559 let stop = f.is_err();
560 if tx.send(f).is_err() || stop {
561 break;
562 }
563 }
564}
565
566struct Output;
568
569impl Output {
570 fn send(&mut self, r: &Response) {
571 send(r)
572 }
573
574 fn batch(&mut self, b: &RecordBatch) -> Result<()> {
575 let ipc = frame::encode_batch(b)?;
576 let mut out = shared().out.lock().unwrap();
577 frame::write_arrow(&mut *out, &ipc).map_err(|_| -> Error { "core closed the connection".into() })
578 }
579}
580
581enum Handler<'a> {
582 Source(&'a mut dyn Source),
583 Format(&'a mut dyn Format),
584 Destination(&'a mut dyn Destination),
585}
586
587impl Handler<'_> {
588 fn kind(&self) -> Kind {
589 match self {
590 Handler::Source(_) => Kind::Source,
591 Handler::Format(_) => Kind::Format,
592 Handler::Destination(_) => Kind::Destination,
593 }
594 }
595
596 fn option_fields(&self) -> Vec<OptionField> {
597 match self {
598 Handler::Source(_) => Vec::new(),
599 Handler::Format(f) => f.options(),
600 Handler::Destination(d) => d.options(),
601 }
602 }
603
604 fn check(&self, name: &str, o: &Map<String, Value>) -> Vec<String> {
607 let errs = options::check(self.kind(), name, &self.option_fields(), o);
608 if !errs.is_empty() {
609 return errs;
610 }
611 match self {
612 Handler::Source(_) => Vec::new(),
613 Handler::Format(f) => f.validate(o),
614 Handler::Destination(d) => d.validate(o),
615 }
616 }
617
618 fn checked(&self, name: &str, o: &Map<String, Value>) -> Result<()> {
620 let errs = self.check(name, o);
621 if errs.is_empty() {
622 Ok(())
623 } else {
624 Err(errs.join("; ").into())
625 }
626 }
627}
628
629pub fn serve_source(about: About, s: impl Source + 'static) -> ! {
630 serve_package(vec![Plugin::Source(about, Box::new(s))])
631}
632
633pub fn serve_format(about: About, f: impl Format + 'static) -> ! {
634 serve_package(vec![Plugin::Format(about, Box::new(f))])
635}
636
637pub fn serve_destination(about: About, d: impl Destination + 'static) -> ! {
638 serve_package(vec![Plugin::Destination(about, Box::new(d))])
639}
640
641pub enum Plugin {
643 Source(About, Box<dyn Source>),
644 Format(About, Box<dyn Format>),
645 Destination(About, Box<dyn Destination>),
646}
647
648impl Plugin {
649 fn id(&self) -> PluginId {
650 let (kind, about) = match self {
651 Plugin::Source(a, _) => (Kind::Source, a),
652 Plugin::Format(a, _) => (Kind::Format, a),
653 Plugin::Destination(a, _) => (Kind::Destination, a),
654 };
655 PluginId::new(kind, about.name)
656 }
657
658 fn handler(&mut self) -> (&About, Handler<'_>) {
659 match self {
660 Plugin::Source(a, s) => (a, Handler::Source(s.as_mut())),
661 Plugin::Format(a, f) => (a, Handler::Format(f.as_mut())),
662 Plugin::Destination(a, d) => (a, Handler::Destination(d.as_mut())),
663 }
664 }
665}
666
667pub fn serve_package(mut plugins: Vec<Plugin>) -> ! {
670 assert!(!plugins.is_empty(), "a package serves at least one plugin");
671 let (tx, rx) = std::sync::mpsc::channel();
672 std::thread::spawn(move || read_stdin(tx));
673 let mut input = Input { rx };
674 let mut out = Output;
675 if ::log::set_logger(&FrameLogger).is_ok() {
676 ::log::set_max_level(::log::LevelFilter::Debug);
677 }
678 let provides: Vec<PluginId> = plugins.iter().map(Plugin::id).collect();
679 let chosen = loop {
680 let req = match next_request(&mut input, &mut out) {
681 Some(r) => r,
682 None => continue,
683 };
684 let Request::Hello {
685 min_version,
686 max_version,
687 plugin,
688 ..
689 } = req
690 else {
691 out.send(&Response::error("the first request must be `hello`"));
692 continue;
693 };
694 let Some(chosen) = negotiate((min_version, max_version), (MIN_VERSION, MAX_VERSION)) else {
695 out.send(&Response::VersionMismatch {
696 min_version: MIN_VERSION,
697 max_version: MAX_VERSION,
698 });
699 std::process::exit(1);
700 };
701 let i = match &plugin {
702 None => 0,
703 Some(want) => match provides.iter().position(|p| p == want) {
704 Some(i) => i,
705 None => {
706 let list: Vec<String> = provides.iter().map(|p| p.to_string()).collect();
707 out.send(&Response::error(format!(
708 "this executable provides {}, not {want}",
709 list.join(", ")
710 )));
711 std::process::exit(1);
712 }
713 },
714 };
715 let (about, h) = plugins[i].handler();
716 let _ = shared().name.set(about.name.to_string());
717 out.send(&Response::Hello {
718 protocol_version: chosen,
719 kind: h.kind(),
720 name: about.name.to_string(),
721 version: about.version.to_string(),
722 capabilities: about
723 .capabilities
724 .iter()
725 .chain(std::iter::once(&CAP_VALIDATE))
726 .map(|c| c.to_string())
727 .collect(),
728 provides: if provides.len() > 1 {
729 provides.clone()
730 } else {
731 Vec::new()
732 },
733 });
734 shared().version.store(chosen, Ordering::SeqCst);
735 break i;
736 };
737 let (about, h) = plugins[chosen].handler();
738 serve(about.name, h, input, out)
739}
740
741fn next_request(input: &mut Input, out: &mut Output) -> Option<Request> {
743 let frame = match input.next() {
744 Ok(f) => f,
745 Err(FrameError::Eof) => std::process::exit(0),
746 Err(e) => {
747 eprintln!("{e}");
748 out.send(&Response::error(e.to_string()));
749 std::process::exit(2);
750 }
751 };
752 match frame {
753 Frame::Json(v) => match serde_json::from_value::<Request>(v.clone()) {
754 Ok(r) => Some(r),
755 Err(_) => {
756 let t = v.get("type").and_then(Value::as_str).unwrap_or("?").to_string();
757 out.send(&Response::error(format!("unsupported request `{t}`")));
758 None
759 }
760 },
761 Frame::Arrow(_) => {
762 out.send(&Response::error("unexpected Arrow frame"));
763 None
764 }
765 }
766}
767
768fn serve(name: &str, mut h: Handler<'_>, mut input: Input, mut out: Output) -> ! {
770 loop {
771 let frame = match input.next() {
772 Ok(f) => f,
773 Err(FrameError::Eof) => {
774 if let Handler::Source(src) = &mut h {
775 src.close();
776 }
777 std::process::exit(0)
778 }
779 Err(e) => {
780 eprintln!("{e}");
781 out.send(&Response::error(e.to_string()));
782 std::process::exit(2);
783 }
784 };
785 let s = shared();
786 let id = match &frame {
787 Frame::Json(v) => v.get("id").and_then(Value::as_u64).unwrap_or(0),
788 Frame::Arrow(_) => 0,
789 };
790 s.current.store(id, Ordering::SeqCst);
791 let req = match frame {
792 Frame::Json(v) => match serde_json::from_value::<Request>(v.clone()) {
793 Ok(r) => r,
794 Err(_) => {
795 let t = v.get("type").and_then(Value::as_str).unwrap_or("?").to_string();
796 out.send(&Response::error(format!("unsupported request `{t}`")));
797 s.current.store(0, Ordering::SeqCst);
798 continue;
799 }
800 },
801 Frame::Arrow(_) => {
802 out.send(&Response::error("unexpected Arrow frame"));
803 continue;
804 }
805 };
806 if let Request::Hello { .. } = req {
807 out.send(&Response::error("`hello` was already answered"));
808 s.current.store(0, Ordering::SeqCst);
809 continue;
810 }
811 if let Request::Close {} = req {
812 if let Handler::Source(src) = &mut h {
813 src.close();
814 }
815 out.send(&Response::Ok {});
816 std::process::exit(0);
817 }
818 let result = if cancelled() {
820 Ok(Err("cancelled before it started".into()))
821 } else {
822 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
823 handle(&mut h, name, req, &mut input, &mut out)
824 }))
825 };
826 match result {
827 Ok(Ok(())) => {}
828 Ok(Err(e)) => out.send(&error_reply(&e)),
829 Err(p) => {
830 let msg = p
831 .downcast_ref::<String>()
832 .cloned()
833 .or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string()))
834 .unwrap_or_else(|| "unknown panic".into());
835 out.send(&Response::Error {
836 message: format!("plugin panicked: {msg}"),
837 kind: Some("internal".into()),
838 code: None,
839 });
840 std::process::exit(101);
841 }
842 }
843 s.current.store(0, Ordering::SeqCst);
844 }
845}
846
847fn check_connection(
850 h: &Handler<'_>,
851 name: &str,
852 connection: &Map<String, Value>,
853 unresolved: &[String],
854) -> Result<crate::connection::Checked> {
855 let (kind, fields) = match h {
856 Handler::Source(s) => (Kind::Source, s.connection_fields()),
857 Handler::Destination(d) => (Kind::Destination, d.connection_fields()),
858 Handler::Format(_) => return Err("a format has no connection settings".into()),
859 };
860 let mut c = crate::connection::check(kind, name, &fields, connection, unresolved);
861 if c.errors.is_empty() {
862 c.errors = match h {
865 Handler::Source(s) => s.validate_connection(connection),
866 Handler::Destination(d) => d.validate_connection(connection),
867 Handler::Format(_) => Vec::new(),
868 };
869 }
870 c.errors = crate::connection::redact(c.errors, &fields, connection);
871 c.warnings = crate::connection::redact(c.warnings, &fields, connection);
872 Ok(c)
873}
874
875fn handle(h: &mut Handler<'_>, name: &str, req: Request, input: &mut Input, out: &mut Output) -> Result<()> {
876 if let Request::Describe {} = req {
877 let connection_fields = match h {
878 Handler::Source(s) => s.connection_fields(),
879 Handler::Destination(d) => d.connection_fields(),
880 Handler::Format(_) => Vec::new(),
881 };
882 let identifier_quote = match h {
883 Handler::Source(s) => s.identifier_quote().map(str::to_string),
884 _ => None,
885 };
886 let message_limit = match h {
887 Handler::Destination(d) => d.message_limit(),
888 _ => None,
889 };
890 out.send(&Response::Describe {
891 connection_fields,
892 option_fields: h.option_fields(),
893 identifier_quote,
894 message_limit,
895 });
896 return Ok(());
897 }
898 if let Request::Validate { options } = req {
899 out.send(&Response::Validated {
900 errors: h.check(name, &options),
901 warnings: Vec::new(),
902 });
903 return Ok(());
904 }
905 if let Request::ValidateConnection {
906 connection,
907 unresolved,
908 } = req
909 {
910 let c = check_connection(h, name, &connection, &unresolved)?;
911 out.send(&Response::Validated {
912 errors: c.errors,
913 warnings: c.warnings,
914 });
915 return Ok(());
916 }
917 if let Request::Open { connection, .. } | Request::Deliver { connection, .. } = &req {
919 let c = check_connection(h, name, connection, &[])?;
920 for w in &c.warnings {
921 crate::log::warn!("{w}");
922 }
923 if !c.errors.is_empty() {
924 return Err(PluginError::new(ErrorKind::Config, c.errors.join("; ")).into());
925 }
926 }
927 let checked = match &req {
928 Request::Write { options, .. } | Request::Deliver { options, .. } => h.checked(name, options),
929 _ => Ok(()),
930 };
931 match (h, req) {
932 (
933 Handler::Source(s),
934 Request::Open {
935 connection,
936 read_only,
937 },
938 ) => {
939 s.open(&connection, read_only)?;
940 out.send(&Response::Ok {});
941 }
942 (Handler::Source(s), Request::Load { name }) => {
943 let ipc = match input.read()? {
944 Frame::Arrow(ipc) => ipc,
945 Frame::Json(v) => return Err(format!("expected the rows to load, got {v}").into()),
946 };
947 let (schema, batches) = frame::decode_batches(&ipc)?;
948 let mut data = ResultSet {
949 meta: ResultSetMeta {
950 name: name.clone(),
951 query: name.clone(),
952 result_index: 1,
953 anchor: None,
954 header: None,
955 columns: Default::default(),
956 autofit: None,
957 style: None,
958 },
959 schema,
960 first: Some(batches),
961 input,
962 done: false,
963 };
964 let r = s.load(&name, &mut data);
965 data.drain()?;
966 let loaded = r?;
967 out.send(&Response::Loaded {
968 relation: loaded.relation,
969 rows: loaded.rows,
970 warning: loaded.warning,
971 });
972 }
973 (Handler::Source(s), Request::Check { sql }) => {
974 s.check(&sql)?;
975 out.send(&Response::Ok {});
976 }
977 (Handler::Source(s), Request::Execute { sql, row_limit }) => {
978 let mut sink = FrameSink {
979 out,
980 row_limit,
981 rows: 0,
982 state: SinkState::Idle,
983 schema: None,
984 sent_any: false,
985 };
986 let r = s.execute(&sql, row_limit, &mut sink);
987 match (r, sink.state) {
988 (Err(e), _) => return Err(e),
989 (Ok(()), SinkState::Idle) => {
990 return Err("the source produced neither a result nor `no_result`".into());
991 }
992 (Ok(()), SinkState::NoResult) => {}
993 (Ok(()), SinkState::Result) => {
994 if !sink.sent_any {
995 let schema = sink.schema.clone().unwrap();
996 sink.out.batch(&RecordBatch::new_empty(schema))?;
997 }
998 let rows = sink.rows;
999 sink.out.send(&Response::ResultEnd { rows });
1000 }
1001 }
1002 }
1003 (
1004 Handler::Format(f),
1005 Request::Write {
1006 path,
1007 format,
1008 options,
1009 result_sets,
1010 template,
1011 },
1012 ) => {
1013 let req = WriteRequest {
1014 path,
1015 format,
1016 options,
1017 result_sets: result_sets.clone(),
1018 template,
1019 };
1020 let mut sets = ResultSets {
1021 metas: result_sets.into_iter(),
1022 input,
1023 warnings: Vec::new(),
1024 };
1025 let written = checked.and_then(|()| f.write(&req, &mut sets));
1026 if let Err(e) = &written {
1029 out.send(&error_reply(e));
1030 }
1031 loop {
1034 match sets.input.read()? {
1035 Frame::Json(v) if v.get("type").and_then(Value::as_str) == Some("finish") => break,
1036 Frame::Json(v) if v.get("type").and_then(Value::as_str) == Some("result_set_end") => {}
1037 Frame::Arrow(_) => {}
1038 other => return Err(format!("expected `finish`, got {other:?}").into()),
1039 }
1040 }
1041 if let Ok(files) = written {
1042 out.send(&Response::Written {
1043 files,
1044 warnings: sets.warnings,
1045 });
1046 }
1047 }
1048 (
1049 Handler::Destination(d),
1050 Request::Deliver {
1051 local_path,
1052 remote_path,
1053 files,
1054 connection,
1055 options,
1056 message,
1057 },
1058 ) => {
1059 checked?;
1060 let files = match (local_path, files.is_empty(), &message) {
1061 (Some(local), true, None) => vec![DeliveryFile {
1062 local: PathBuf::from(local),
1063 remote: remote_path,
1064 }],
1065 (None, false, _) | (None, true, Some(_)) => files
1066 .into_iter()
1067 .map(|f| DeliveryFile {
1068 local: PathBuf::from(f.local_path),
1069 remote: f.remote_path,
1070 })
1071 .collect(),
1072 _ => return Err("`deliver` needs exactly one of `local_path` or `files`".into()),
1073 };
1074 let delivery = Delivery {
1075 files,
1076 connection,
1077 options,
1078 message,
1079 };
1080 crate::delivery::take_attempts();
1081 let location = match &delivery.message {
1082 Some(m) => d.deliver_message(&delivery, m)?,
1083 None => d.deliver_files(&delivery)?,
1084 };
1085 let attempts = Some(crate::delivery::take_attempts()).filter(|n| *n > 1);
1086 out.send(&Response::Delivered { location, attempts });
1087 }
1088 (h, req) => {
1089 let t = serde_json::to_value(&req)
1090 .ok()
1091 .and_then(|v| v.get("type").cloned())
1092 .unwrap_or_default();
1093 return Err(format!("a {} plugin doesn't handle {t} requests", h.kind()).into());
1094 }
1095 }
1096 Ok(())
1097}
1098
1099#[derive(PartialEq)]
1100enum SinkState {
1101 Idle,
1102 NoResult,
1103 Result,
1104}
1105
1106struct FrameSink<'a> {
1107 out: &'a mut Output,
1108 row_limit: Option<u64>,
1109 rows: u64,
1110 state: SinkState,
1111 schema: Option<SchemaRef>,
1112 sent_any: bool,
1113}
1114
1115impl ResultSink for FrameSink<'_> {
1116 fn no_result(&mut self, rows_affected: Option<u64>) -> Result<()> {
1117 if self.state != SinkState::Idle {
1118 return Err("`no_result` after the result started".into());
1119 }
1120 self.state = SinkState::NoResult;
1121 self.out.send(&Response::NoResult { rows_affected });
1122 Ok(())
1123 }
1124
1125 fn begin(&mut self, schema: SchemaRef) -> Result<()> {
1126 if self.state != SinkState::Idle {
1127 return Err("a statement can only produce one result".into());
1128 }
1129 self.state = SinkState::Result;
1130 self.out.send(&Response::Result {
1131 columns: schema.fields().iter().map(|f| f.name().clone()).collect(),
1132 });
1133 self.schema = Some(schema);
1134 Ok(())
1135 }
1136
1137 fn batch(&mut self, b: RecordBatch) -> Result<bool> {
1138 if self.state != SinkState::Result {
1139 return Err("`batch` before `begin`".into());
1140 }
1141 if self.row_limit.is_some_and(|l| self.rows >= l) {
1142 return Ok(false);
1143 }
1144 let b = match self.row_limit {
1145 Some(l) if self.rows + b.num_rows() as u64 > l => b.slice(0, (l - self.rows) as usize),
1146 _ => b,
1147 };
1148 if b.num_rows() > 0 || !self.sent_any {
1149 self.rows += b.num_rows() as u64;
1150 self.out.batch(&b)?;
1151 self.sent_any = true;
1152 }
1153 Ok(self.row_limit.is_none_or(|l| self.rows < l))
1154 }
1155}
1156
1157fn negotiate(core: (u32, u32), ours: (u32, u32)) -> Option<u32> {
1159 let (lo, hi) = (core.0.max(ours.0), core.1.min(ours.1));
1160 (lo <= hi).then_some(hi)
1161}
1162
1163pub fn conn_str<'a>(c: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
1165 c.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
1166}
1167
1168pub fn conn_required<'a>(c: &'a Map<String, Value>, key: &str) -> Result<&'a str> {
1170 conn_str(c, key).ok_or_else(|| format!("the profile output needs a `{key}` field").into())
1171}
1172
1173pub fn conn_bool(c: &Map<String, Value>, key: &str) -> Option<bool> {
1175 match c.get(key)? {
1176 Value::Bool(b) => Some(*b),
1177 Value::String(s) => Some(matches!(s.as_str(), "true" | "yes" | "1")),
1178 _ => None,
1179 }
1180}