1#![doc(
35 html_logo_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_white-bg.svg",
36 html_favicon_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_transparent-bg.svg"
37)]
38#![cfg_attr(docsrs, feature(doc_cfg))]
39#![allow(rustdoc::invalid_html_tags)]
40#![warn(missing_docs)]
41
42use arrow_ipc::{convert, writer, writer::EncodedData, writer::IpcWriteOptions};
43use arrow_schema::{ArrowError, Schema};
44
45use arrow_ipc::convert::try_schema_from_ipc_buffer;
46use base64::Engine;
47use base64::prelude::BASE64_STANDARD;
48use bytes::Bytes;
49use prost_types::Timestamp;
50use std::{fmt, ops::Deref};
51
52type ArrowResult<T> = std::result::Result<T, ArrowError>;
53
54#[allow(clippy::allow_attributes)]
56#[allow(clippy::all)]
57mod r#gen {
58 #![allow(missing_docs)]
59 include!("arrow.flight.protocol.rs");
60}
61
62pub mod flight_descriptor {
64 use super::r#gen;
65 pub use r#gen::flight_descriptor::DescriptorType;
66}
67
68pub mod flight_service_client {
70 use super::r#gen;
71 pub use r#gen::flight_service_client::FlightServiceClient;
72}
73
74pub mod flight_service_server {
77 use super::r#gen;
78 pub use r#gen::flight_service_server::FlightService;
79 pub use r#gen::flight_service_server::FlightServiceServer;
80}
81
82pub mod client;
84pub use client::FlightClient;
85
86pub mod decode;
89
90pub mod encode;
93
94pub mod error;
96
97pub use r#gen::Action;
98pub use r#gen::ActionType;
99pub use r#gen::BasicAuth;
100pub use r#gen::CancelFlightInfoRequest;
101pub use r#gen::CancelFlightInfoResult;
102pub use r#gen::CancelStatus;
103pub use r#gen::Criteria;
104pub use r#gen::Empty;
105pub use r#gen::FlightData;
106pub use r#gen::FlightDescriptor;
107pub use r#gen::FlightEndpoint;
108pub use r#gen::FlightInfo;
109pub use r#gen::HandshakeRequest;
110pub use r#gen::HandshakeResponse;
111pub use r#gen::Location;
112pub use r#gen::PollInfo;
113pub use r#gen::PutResult;
114pub use r#gen::RenewFlightEndpointRequest;
115pub use r#gen::Result;
116pub use r#gen::SchemaResult;
117pub use r#gen::Ticket;
118
119mod trailers;
121
122pub mod utils;
123
124#[cfg(feature = "flight-sql")]
125pub mod sql;
126mod streams;
127
128use flight_descriptor::DescriptorType;
129
130pub struct SchemaAsIpc<'a> {
132 pub pair: (&'a Schema, &'a IpcWriteOptions),
134}
135
136#[derive(Debug)]
139pub struct IpcMessage(pub Bytes);
140
141fn flight_schema_as_encoded_data(arrow_schema: &Schema, options: &IpcWriteOptions) -> EncodedData {
144 let data_gen = writer::IpcDataGenerator::default();
145 let mut dict_tracker = writer::DictionaryTracker::new(false);
146 data_gen.schema_to_bytes_with_dictionary_tracker(arrow_schema, &mut dict_tracker, options)
147}
148
149fn flight_schema_as_flatbuffer(schema: &Schema, options: &IpcWriteOptions) -> IpcMessage {
150 let encoded_data = flight_schema_as_encoded_data(schema, options);
151 IpcMessage(encoded_data.ipc_message.into())
152}
153
154impl Deref for IpcMessage {
160 type Target = [u8];
161
162 fn deref(&self) -> &Self::Target {
163 &self.0
164 }
165}
166
167impl<'a> Deref for SchemaAsIpc<'a> {
168 type Target = (&'a Schema, &'a IpcWriteOptions);
169
170 fn deref(&self) -> &Self::Target {
171 &self.pair
172 }
173}
174
175fn limited_fmt(f: &mut fmt::Formatter<'_>, value: &[u8], limit: usize) -> fmt::Result {
179 if value.len() > limit {
180 write!(f, "{:?}", &value[..limit])
181 } else {
182 write!(f, "{value:?}")
183 }
184}
185
186impl fmt::Display for FlightData {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 write!(f, "FlightData {{")?;
189 write!(f, " descriptor: ")?;
190 match &self.flight_descriptor {
191 Some(d) => write!(f, "{d}")?,
192 None => write!(f, "None")?,
193 }
194 write!(f, ", header: ")?;
195 limited_fmt(f, &self.data_header, 8)?;
196 write!(f, ", metadata: ")?;
197 limited_fmt(f, &self.app_metadata, 8)?;
198 write!(f, ", body: ")?;
199 limited_fmt(f, &self.data_body, 8)?;
200 write!(f, " }}")
201 }
202}
203
204impl fmt::Display for FlightDescriptor {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 write!(f, "FlightDescriptor {{")?;
207 write!(f, " type: ")?;
208 match self.r#type() {
209 DescriptorType::Cmd => {
210 write!(f, "cmd, value: ")?;
211 limited_fmt(f, &self.cmd, 8)?;
212 }
213 DescriptorType::Path => {
214 write!(f, "path: [")?;
215 let mut sep = "";
216 for element in &self.path {
217 write!(f, "{sep}{element}")?;
218 sep = ", ";
219 }
220 write!(f, "]")?;
221 }
222 DescriptorType::Unknown => {
223 write!(f, "unknown")?;
224 }
225 }
226 write!(f, " }}")
227 }
228}
229
230impl fmt::Display for FlightEndpoint {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 write!(f, "FlightEndpoint {{")?;
233 write!(f, " ticket: ")?;
234 match &self.ticket {
235 Some(value) => write!(f, "{value}"),
236 None => write!(f, " None"),
237 }?;
238 write!(f, ", location: [")?;
239 let mut sep = "";
240 for location in &self.location {
241 write!(f, "{sep}{location}")?;
242 sep = ", ";
243 }
244 write!(f, "]")?;
245 write!(f, ", expiration_time:")?;
246 match &self.expiration_time {
247 Some(value) => write!(f, " {value}"),
248 None => write!(f, " None"),
249 }?;
250 write!(f, ", app_metadata: ")?;
251 limited_fmt(f, &self.app_metadata, 8)?;
252 write!(f, " }}")
253 }
254}
255
256impl fmt::Display for FlightInfo {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 let ipc_message = IpcMessage(self.schema.clone());
259 let schema: Schema = ipc_message.try_into().map_err(|_err| fmt::Error)?;
260 write!(f, "FlightInfo {{")?;
261 write!(f, " schema: {schema}")?;
262 write!(f, ", descriptor:")?;
263 match &self.flight_descriptor {
264 Some(d) => write!(f, " {d}"),
265 None => write!(f, " None"),
266 }?;
267 write!(f, ", endpoint: [")?;
268 let mut sep = "";
269 for endpoint in &self.endpoint {
270 write!(f, "{sep}{endpoint}")?;
271 sep = ", ";
272 }
273 write!(f, "], total_records: {}", self.total_records)?;
274 write!(f, ", total_bytes: {}", self.total_bytes)?;
275 write!(f, ", ordered: {}", self.ordered)?;
276 write!(f, ", app_metadata: ")?;
277 limited_fmt(f, &self.app_metadata, 8)?;
278 write!(f, " }}")
279 }
280}
281
282impl fmt::Display for PollInfo {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 write!(f, "PollInfo {{")?;
285 write!(f, " info:")?;
286 match &self.info {
287 Some(value) => write!(f, " {value}"),
288 None => write!(f, " None"),
289 }?;
290 write!(f, ", descriptor:")?;
291 match &self.flight_descriptor {
292 Some(d) => write!(f, " {d}"),
293 None => write!(f, " None"),
294 }?;
295 write!(f, ", progress:")?;
296 match &self.progress {
297 Some(value) => write!(f, " {value}"),
298 None => write!(f, " None"),
299 }?;
300 write!(f, ", expiration_time:")?;
301 match &self.expiration_time {
302 Some(value) => write!(f, " {value}"),
303 None => write!(f, " None"),
304 }?;
305 write!(f, " }}")
306 }
307}
308
309impl fmt::Display for CancelFlightInfoRequest {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 write!(f, "CancelFlightInfoRequest {{")?;
312 write!(f, " info: ")?;
313 match &self.info {
314 Some(value) => write!(f, "{value}")?,
315 None => write!(f, "None")?,
316 }
317 write!(f, " }}")
318 }
319}
320
321impl fmt::Display for CancelFlightInfoResult {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 write!(f, "CancelFlightInfoResult {{")?;
324 write!(f, " status: {}", self.status().as_str_name())?;
325 write!(f, " }}")
326 }
327}
328
329impl fmt::Display for RenewFlightEndpointRequest {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 write!(f, "RenewFlightEndpointRequest {{")?;
332 write!(f, " endpoint: ")?;
333 match &self.endpoint {
334 Some(value) => write!(f, "{value}")?,
335 None => write!(f, "None")?,
336 }
337 write!(f, " }}")
338 }
339}
340
341impl fmt::Display for Location {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 write!(f, "Location {{")?;
344 write!(f, " uri: ")?;
345 write!(f, "{}", self.uri)
346 }
347}
348
349impl fmt::Display for Ticket {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 write!(f, "Ticket {{")?;
352 write!(f, " ticket: ")?;
353 write!(f, "{}", BASE64_STANDARD.encode(&self.ticket))
354 }
355}
356
357impl From<EncodedData> for FlightData {
360 fn from(data: EncodedData) -> Self {
361 FlightData {
362 data_header: data.ipc_message.into(),
363 data_body: data.arrow_data.into(),
364 ..Default::default()
365 }
366 }
367}
368
369impl From<SchemaAsIpc<'_>> for FlightData {
370 fn from(schema_ipc: SchemaAsIpc) -> Self {
371 let IpcMessage(vals) = flight_schema_as_flatbuffer(schema_ipc.0, schema_ipc.1);
372 FlightData {
373 data_header: vals,
374 ..Default::default()
375 }
376 }
377}
378
379impl TryFrom<SchemaAsIpc<'_>> for SchemaResult {
380 type Error = ArrowError;
381
382 fn try_from(schema_ipc: SchemaAsIpc) -> ArrowResult<Self> {
383 let IpcMessage(vals) = schema_to_ipc_format(schema_ipc)?;
389 Ok(SchemaResult { schema: vals })
390 }
391}
392
393impl TryFrom<SchemaAsIpc<'_>> for IpcMessage {
394 type Error = ArrowError;
395
396 fn try_from(schema_ipc: SchemaAsIpc) -> ArrowResult<Self> {
397 schema_to_ipc_format(schema_ipc)
398 }
399}
400
401fn schema_to_ipc_format(schema_ipc: SchemaAsIpc) -> ArrowResult<IpcMessage> {
402 let pair = *schema_ipc;
403 let encoded_data = flight_schema_as_encoded_data(pair.0, pair.1);
404
405 let mut schema = vec![];
406 writer::write_message(&mut schema, encoded_data, pair.1)?;
407 Ok(IpcMessage(schema.into()))
408}
409
410impl TryFrom<&FlightData> for Schema {
411 type Error = ArrowError;
412 fn try_from(data: &FlightData) -> ArrowResult<Self> {
413 convert::try_schema_from_flatbuffer_bytes(&data.data_header[..]).map_err(|err| {
414 ArrowError::ParseError(format!(
415 "Unable to convert flight data to Arrow schema: {err}"
416 ))
417 })
418 }
419}
420
421impl TryFrom<FlightInfo> for Schema {
422 type Error = ArrowError;
423
424 fn try_from(value: FlightInfo) -> ArrowResult<Self> {
425 value.try_decode_schema()
426 }
427}
428
429impl TryFrom<IpcMessage> for Schema {
430 type Error = ArrowError;
431
432 fn try_from(value: IpcMessage) -> ArrowResult<Self> {
433 try_schema_from_ipc_buffer(&value)
434 }
435}
436
437impl TryFrom<&SchemaResult> for Schema {
438 type Error = ArrowError;
439 fn try_from(data: &SchemaResult) -> ArrowResult<Self> {
440 try_schema_from_ipc_buffer(&data.schema)
441 }
442}
443
444impl TryFrom<SchemaResult> for Schema {
445 type Error = ArrowError;
446 fn try_from(data: SchemaResult) -> ArrowResult<Self> {
447 (&data).try_into()
448 }
449}
450
451impl FlightData {
454 pub fn new() -> Self {
479 Default::default()
480 }
481
482 pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
484 self.flight_descriptor = Some(flight_descriptor);
485 self
486 }
487
488 pub fn with_data_header(mut self, data_header: impl Into<Bytes>) -> Self {
490 self.data_header = data_header.into();
491 self
492 }
493
494 pub fn with_data_body(mut self, data_body: impl Into<Bytes>) -> Self {
498 self.data_body = data_body.into();
499 self
500 }
501
502 pub fn with_app_metadata(mut self, app_metadata: impl Into<Bytes>) -> Self {
504 self.app_metadata = app_metadata.into();
505 self
506 }
507}
508
509impl FlightDescriptor {
510 pub fn new_cmd(cmd: impl Into<Bytes>) -> Self {
514 FlightDescriptor {
515 r#type: DescriptorType::Cmd.into(),
516 cmd: cmd.into(),
517 ..Default::default()
518 }
519 }
520
521 pub fn new_path(path: Vec<String>) -> Self {
525 FlightDescriptor {
526 r#type: DescriptorType::Path.into(),
527 path,
528 ..Default::default()
529 }
530 }
531}
532
533impl FlightInfo {
534 pub fn new() -> FlightInfo {
560 FlightInfo {
561 schema: Bytes::new(),
562 flight_descriptor: None,
563 endpoint: vec![],
564 ordered: false,
565 total_records: -1,
569 total_bytes: -1,
570 app_metadata: Bytes::new(),
571 }
572 }
573
574 pub fn try_decode_schema(self) -> ArrowResult<Schema> {
576 let msg = IpcMessage(self.schema);
577 msg.try_into()
578 }
579
580 pub fn try_with_schema(mut self, schema: &Schema) -> ArrowResult<Self> {
587 let options = IpcWriteOptions::default();
588 let IpcMessage(schema) = SchemaAsIpc::new(schema, &options).try_into()?;
589 self.schema = schema;
590 Ok(self)
591 }
592
593 pub fn with_endpoint(mut self, endpoint: FlightEndpoint) -> Self {
595 self.endpoint.push(endpoint);
596 self
597 }
598
599 pub fn with_endpoints(mut self, endpoints: Vec<FlightEndpoint>) -> Self {
601 self.endpoint = endpoints;
602 self
603 }
604
605 pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
607 self.flight_descriptor = Some(flight_descriptor);
608 self
609 }
610
611 pub fn with_total_records(mut self, total_records: i64) -> Self {
613 self.total_records = total_records;
614 self
615 }
616
617 pub fn with_total_bytes(mut self, total_bytes: i64) -> Self {
619 self.total_bytes = total_bytes;
620 self
621 }
622
623 pub fn with_ordered(mut self, ordered: bool) -> Self {
627 self.ordered = ordered;
628 self
629 }
630
631 pub fn with_app_metadata(mut self, app_metadata: impl Into<Bytes>) -> Self {
633 self.app_metadata = app_metadata.into();
634 self
635 }
636}
637
638impl PollInfo {
639 pub fn new() -> Self {
656 Self {
657 info: None,
658 flight_descriptor: None,
659 progress: None,
660 expiration_time: None,
661 }
662 }
663
664 pub fn with_info(mut self, info: FlightInfo) -> Self {
666 self.info = Some(info);
667 self
668 }
669
670 pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
673 self.flight_descriptor = Some(flight_descriptor);
674 self
675 }
676
677 pub fn try_with_progress(mut self, progress: f64) -> ArrowResult<Self> {
680 if !(0.0..=1.0).contains(&progress) {
681 return Err(ArrowError::InvalidArgumentError(format!(
682 "PollInfo progress must be in the range [0.0, 1.0], got {progress}"
683 )));
684 }
685 self.progress = Some(progress);
686 Ok(self)
687 }
688
689 pub fn with_expiration_time(mut self, expiration_time: Timestamp) -> Self {
691 self.expiration_time = Some(expiration_time);
692 self
693 }
694}
695
696impl<'a> SchemaAsIpc<'a> {
697 pub fn new(schema: &'a Schema, options: &'a IpcWriteOptions) -> Self {
699 SchemaAsIpc {
700 pair: (schema, options),
701 }
702 }
703}
704
705impl CancelFlightInfoRequest {
706 pub fn new(info: FlightInfo) -> Self {
709 Self { info: Some(info) }
710 }
711}
712
713impl CancelFlightInfoResult {
714 pub fn new(status: CancelStatus) -> Self {
716 Self {
717 status: status as i32,
718 }
719 }
720}
721
722impl RenewFlightEndpointRequest {
723 pub fn new(endpoint: FlightEndpoint) -> Self {
726 Self {
727 endpoint: Some(endpoint),
728 }
729 }
730}
731
732impl Action {
733 pub fn new(action_type: impl Into<String>, body: impl Into<Bytes>) -> Self {
735 Self {
736 r#type: action_type.into(),
737 body: body.into(),
738 }
739 }
740}
741
742impl Result {
743 pub fn new(body: impl Into<Bytes>) -> Self {
745 Self { body: body.into() }
746 }
747}
748
749impl Ticket {
750 pub fn new(ticket: impl Into<Bytes>) -> Self {
759 Self {
760 ticket: ticket.into(),
761 }
762 }
763}
764
765impl FlightEndpoint {
766 pub fn new() -> FlightEndpoint {
785 Default::default()
786 }
787
788 pub fn with_ticket(mut self, ticket: Ticket) -> Self {
790 self.ticket = Some(ticket);
791 self
792 }
793
794 pub fn with_location(mut self, uri: impl Into<String>) -> Self {
806 self.location.push(Location { uri: uri.into() });
807 self
808 }
809
810 pub fn with_expiration_time(mut self, expiration_time: Timestamp) -> Self {
812 self.expiration_time = Some(expiration_time);
813 self
814 }
815
816 pub fn with_app_metadata(mut self, app_metadata: impl Into<Bytes>) -> Self {
818 self.app_metadata = app_metadata.into();
819 self
820 }
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826 use arrow_ipc::MetadataVersion;
827 use arrow_schema::{DataType, Field, TimeUnit};
828
829 struct TestVector(Vec<u8>, usize);
830
831 impl fmt::Display for TestVector {
832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 limited_fmt(f, &self.0, self.1)
834 }
835 }
836
837 #[test]
838 fn it_creates_flight_descriptor_command() {
839 let expected_cmd = b"my_command";
840 let fd = FlightDescriptor::new_cmd(expected_cmd.to_vec());
841 assert_eq!(fd.r#type(), DescriptorType::Cmd);
842 assert_eq!(fd.cmd, expected_cmd.to_vec());
843 }
844
845 #[test]
846 fn it_accepts_equal_output() {
847 let input = TestVector(vec![91; 10], 10);
848
849 let actual = format!("{input}");
850 let expected = format!("{:?}", vec![91; 10]);
851 assert_eq!(actual, expected);
852 }
853
854 #[test]
855 fn it_accepts_short_output() {
856 let input = TestVector(vec![91; 6], 10);
857
858 let actual = format!("{input}");
859 let expected = format!("{:?}", vec![91; 6]);
860 assert_eq!(actual, expected);
861 }
862
863 #[test]
864 fn it_accepts_long_output() {
865 let input = TestVector(vec![91; 10], 9);
866
867 let actual = format!("{input}");
868 let expected = format!("{:?}", vec![91; 9]);
869 assert_eq!(actual, expected);
870 }
871
872 #[test]
873 fn ser_deser_schema_result() {
874 let schema = Schema::new(vec![
875 Field::new("c1", DataType::Utf8, false),
876 Field::new("c2", DataType::Float64, true),
877 Field::new("c3", DataType::UInt32, false),
878 Field::new("c4", DataType::Boolean, true),
879 Field::new("c5", DataType::Timestamp(TimeUnit::Millisecond, None), true),
880 Field::new("c6", DataType::Time32(TimeUnit::Second), false),
881 ]);
882 let option = IpcWriteOptions::default();
885 let schema_ipc = SchemaAsIpc::new(&schema, &option);
886 let result: SchemaResult = schema_ipc.try_into().unwrap();
887 let des_schema: Schema = (&result).try_into().unwrap();
888 assert_eq!(schema, des_schema);
889
890 let option = IpcWriteOptions::try_new(8, true, MetadataVersion::V4).unwrap();
893 let schema_ipc = SchemaAsIpc::new(&schema, &option);
894 let result: SchemaResult = schema_ipc.try_into().unwrap();
895 let des_schema: Schema = (&result).try_into().unwrap();
896 assert_eq!(schema, des_schema);
897 }
898
899 #[test]
900 fn test_dict_schema() {
901 let schema = Schema::new(vec![
903 Field::new(
904 "a",
905 DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8)),
906 false,
907 ),
908 Field::new(
909 "b",
910 DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8)),
911 false,
912 ),
913 ]);
914
915 let flight_info = FlightInfo::new().try_with_schema(&schema).unwrap();
916
917 let new_schema = Schema::try_from(flight_info).unwrap();
918 assert_eq!(schema, new_schema);
919 }
920}