Skip to main content

arrow_flight/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! A native Rust implementation of [Apache Arrow Flight](https://arrow.apache.org/docs/format/Flight.html)
6//! for exchanging [Arrow](https://arrow.apache.org) data between processes.
7//!
8//! Please see the [arrow-flight crates.io](https://crates.io/crates/arrow-flight)
9//! page for feature flags and more information.
10//!
11//! # Overview
12//!
13//! This crate contains:
14//!
15//! 1. Low level [prost] generated structs
16//!    for Flight gRPC protobuf messages, such as [`FlightData`], [`FlightInfo`],
17//!    [`Location`] and [`Ticket`].
18//!
19//! 2. Low level [tonic] generated [`flight_service_client`] and
20//!    [`flight_service_server`].
21//!
22//! 3. Support for [Flight SQL] in [`sql`]. Requires the
23//!    `flight-sql` feature of this crate to be activated.
24//!
25//! [Flight SQL]: https://arrow.apache.org/docs/format/FlightSql.html
26//!
27//! # Platform Support
28//!
29//! Only little-endian platforms are officially supported and tested in CI.
30//! Big-endian platforms are not tested in CI and may not work correctly.
31//! Fixes for big-endian platforms are welcome and handled on a best-effort basis,
32//! but compatibility is not guaranteed.
33
34#![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// This code is generated so we don't want to fix any lint violations manually
55#[allow(clippy::allow_attributes)]
56#[allow(clippy::all)]
57mod r#gen {
58    #![allow(missing_docs)]
59    include!("arrow.flight.protocol.rs");
60}
61
62/// Defines a `Flight` for generation or retrieval.
63pub mod flight_descriptor {
64    use super::r#gen;
65    pub use r#gen::flight_descriptor::DescriptorType;
66}
67
68/// Low Level [tonic] [`FlightServiceClient`](gen::flight_service_client::FlightServiceClient).
69pub mod flight_service_client {
70    use super::r#gen;
71    pub use r#gen::flight_service_client::FlightServiceClient;
72}
73
74/// Low Level [tonic] [`FlightServiceServer`](gen::flight_service_server::FlightServiceServer)
75/// and [`FlightService`](gen::flight_service_server::FlightService).
76pub 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
82/// Mid Level [`FlightClient`]
83pub mod client;
84pub use client::FlightClient;
85
86/// Decoder to create [`RecordBatch`](arrow_array::RecordBatch) streams from [`FlightData`] streams.
87/// See [`FlightRecordBatchStream`](decode::FlightRecordBatchStream).
88pub mod decode;
89
90/// Encoder to create [`FlightData`] streams from [`RecordBatch`](arrow_array::RecordBatch) streams.
91/// See [`FlightDataEncoderBuilder`](encode::FlightDataEncoderBuilder).
92pub mod encode;
93
94/// Common error types
95pub 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
119/// Helper to extract HTTP/gRPC trailers from a tonic stream.
120mod trailers;
121
122pub mod utils;
123
124#[cfg(feature = "flight-sql")]
125pub mod sql;
126mod streams;
127
128use flight_descriptor::DescriptorType;
129
130/// SchemaAsIpc represents a pairing of a `Schema` with IpcWriteOptions
131pub struct SchemaAsIpc<'a> {
132    /// Data type representing a schema and its IPC write options
133    pub pair: (&'a Schema, &'a IpcWriteOptions),
134}
135
136/// IpcMessage represents a `Schema` in the format expected in
137/// `FlightInfo.schema`
138#[derive(Debug)]
139pub struct IpcMessage(pub Bytes);
140
141// Useful conversion functions
142
143fn 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
154// Implement a bunch of useful traits for various conversions, displays,
155// etc...
156
157// Deref
158
159impl 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
175// Display...
176
177/// Limits the output of value to limit...
178fn 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
357// From...
358
359impl 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        // According to the definition from `Flight.proto`
384        // The schema of the dataset in its IPC form:
385        //   4 bytes - an optional IPC_CONTINUATION_TOKEN prefix
386        //   4 bytes - the byte length of the payload
387        //   a flatbuffer Message whose header is the Schema
388        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
451// FlightData, FlightDescriptor, etc..
452
453impl FlightData {
454    /// Create a new [`FlightData`].
455    ///
456    /// # See Also
457    ///
458    /// See [`FlightDataEncoderBuilder`] for a higher level API to
459    /// convert a stream of [`RecordBatch`]es to [`FlightData`]s
460    ///
461    /// # Example:
462    ///
463    /// ```
464    /// # use bytes::Bytes;
465    /// # use arrow_flight::{FlightData, FlightDescriptor};
466    /// # fn encode_data() -> Bytes { Bytes::new() } // dummy data
467    /// // Get encoded Arrow IPC data:
468    /// let data_body: Bytes = encode_data();
469    /// // Create the FlightData message
470    /// let flight_data = FlightData::new()
471    ///   .with_descriptor(FlightDescriptor::new_cmd("the command"))
472    ///   .with_app_metadata("My apps metadata")
473    ///   .with_data_body(data_body);
474    /// ```
475    ///
476    /// [`FlightDataEncoderBuilder`]: crate::encode::FlightDataEncoderBuilder
477    /// [`RecordBatch`]: arrow_array::RecordBatch
478    pub fn new() -> Self {
479        Default::default()
480    }
481
482    /// Add a [`FlightDescriptor`] describing the data
483    pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
484        self.flight_descriptor = Some(flight_descriptor);
485        self
486    }
487
488    /// Add a data header
489    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    /// Add a data body. See [`IpcDataGenerator`] to create this data.
495    ///
496    /// [`IpcDataGenerator`]: arrow_ipc::writer::IpcDataGenerator
497    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    /// Add optional application specific metadata to the message
503    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    /// Create a new opaque command [`CMD`] `FlightDescriptor` to generate a dataset.
511    ///
512    /// [`CMD`]: https://github.com/apache/arrow/blob/6bd31f37ae66bd35594b077cb2f830be57e08acd/format/Flight.proto#L224-L227
513    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    /// Create a new named path [`PATH`] `FlightDescriptor` that identifies a dataset
522    ///
523    /// [`PATH`]: https://github.com/apache/arrow/blob/6bd31f37ae66bd35594b077cb2f830be57e08acd/format/Flight.proto#L217-L222
524    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    /// Create a new, empty `FlightInfo`, describing where to fetch flight data
535    ///
536    ///
537    /// # Example:
538    /// ```
539    /// # use arrow_flight::{FlightInfo, Ticket, FlightDescriptor, FlightEndpoint};
540    /// # use arrow_schema::{Schema, Field, DataType};
541    /// # fn get_schema() -> Schema {
542    /// #   Schema::new(vec![
543    /// #     Field::new("a", DataType::Utf8, false),
544    /// #   ])
545    /// # }
546    /// #
547    /// // Create a new FlightInfo
548    /// let flight_info = FlightInfo::new()
549    ///   // Encode the Arrow schema
550    ///   .try_with_schema(&get_schema())
551    ///   .expect("encoding failed")
552    ///   .with_endpoint(
553    ///      FlightEndpoint::new()
554    ///        .with_ticket(Ticket::new("ticket contents")
555    ///      )
556    ///    )
557    ///   .with_descriptor(FlightDescriptor::new_cmd("RUN QUERY"));
558    /// ```
559    pub fn new() -> FlightInfo {
560        FlightInfo {
561            schema: Bytes::new(),
562            flight_descriptor: None,
563            endpoint: vec![],
564            ordered: false,
565            // Flight says "Set these to -1 if unknown."
566            //
567            // https://github.com/apache/arrow-rs/blob/17ca4d51d0490f9c65f5adde144f677dbc8300e7/format/Flight.proto#L287-L289
568            total_records: -1,
569            total_bytes: -1,
570            app_metadata: Bytes::new(),
571        }
572    }
573
574    /// Try and convert the data in this  `FlightInfo` into a [`Schema`]
575    pub fn try_decode_schema(self) -> ArrowResult<Schema> {
576        let msg = IpcMessage(self.schema);
577        msg.try_into()
578    }
579
580    /// Specify the schema for the response.
581    ///
582    /// Note this takes the arrow [`Schema`] (not the IPC schema) and
583    /// encodes it using the default IPC options.
584    ///
585    /// Returns an error if `schema` can not be encoded into IPC form.
586    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    /// Add specific a endpoint for fetching the data
594    pub fn with_endpoint(mut self, endpoint: FlightEndpoint) -> Self {
595        self.endpoint.push(endpoint);
596        self
597    }
598
599    /// Add endpoints for fetching all data
600    pub fn with_endpoints(mut self, endpoints: Vec<FlightEndpoint>) -> Self {
601        self.endpoint = endpoints;
602        self
603    }
604
605    /// Add a [`FlightDescriptor`] describing what this data is
606    pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
607        self.flight_descriptor = Some(flight_descriptor);
608        self
609    }
610
611    /// Set the number of records in the result, if known
612    pub fn with_total_records(mut self, total_records: i64) -> Self {
613        self.total_records = total_records;
614        self
615    }
616
617    /// Set the number of bytes in the result, if known
618    pub fn with_total_bytes(mut self, total_bytes: i64) -> Self {
619        self.total_bytes = total_bytes;
620        self
621    }
622
623    /// Specify if the response is [ordered] across endpoints
624    ///
625    /// [ordered]: https://github.com/apache/arrow-rs/blob/17ca4d51d0490f9c65f5adde144f677dbc8300e7/format/Flight.proto#L269-L275
626    pub fn with_ordered(mut self, ordered: bool) -> Self {
627        self.ordered = ordered;
628        self
629    }
630
631    /// Add optional application specific metadata to the message
632    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    /// Create a new, empty [`PollInfo`], providing information for a long-running query
640    ///
641    /// # Example:
642    /// ```
643    /// # use arrow_flight::{FlightInfo, PollInfo, FlightDescriptor};
644    /// # use prost_types::Timestamp;
645    /// // Create a new PollInfo
646    /// let poll_info = PollInfo::new()
647    ///   .with_info(FlightInfo::new())
648    ///   .with_descriptor(FlightDescriptor::new_cmd("RUN QUERY"))
649    ///   .try_with_progress(0.5)
650    ///   .expect("progress should've been valid")
651    ///   .with_expiration_time(
652    ///     "1970-01-01".parse().expect("invalid timestamp")
653    ///   );
654    /// ```
655    pub fn new() -> Self {
656        Self {
657            info: None,
658            flight_descriptor: None,
659            progress: None,
660            expiration_time: None,
661        }
662    }
663
664    /// Add the current available results for the poll call as a [`FlightInfo`]
665    pub fn with_info(mut self, info: FlightInfo) -> Self {
666        self.info = Some(info);
667        self
668    }
669
670    /// Add a [`FlightDescriptor`] that the client should use for the next poll call,
671    /// if the query is not yet complete
672    pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
673        self.flight_descriptor = Some(flight_descriptor);
674        self
675    }
676
677    /// Set the query progress if known. Must be in the range [0.0, 1.0] else this will
678    /// return an error
679    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    /// Specify expiration time for this request
690    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    /// Create a new `SchemaAsIpc` from a `Schema` and `IpcWriteOptions`
698    pub fn new(schema: &'a Schema, options: &'a IpcWriteOptions) -> Self {
699        SchemaAsIpc {
700            pair: (schema, options),
701        }
702    }
703}
704
705impl CancelFlightInfoRequest {
706    /// Create a new [`CancelFlightInfoRequest`], providing the [`FlightInfo`]
707    /// of the query to cancel.
708    pub fn new(info: FlightInfo) -> Self {
709        Self { info: Some(info) }
710    }
711}
712
713impl CancelFlightInfoResult {
714    /// Create a new [`CancelFlightInfoResult`] from the provided [`CancelStatus`].
715    pub fn new(status: CancelStatus) -> Self {
716        Self {
717            status: status as i32,
718        }
719    }
720}
721
722impl RenewFlightEndpointRequest {
723    /// Create a new [`RenewFlightEndpointRequest`], providing the [`FlightEndpoint`]
724    /// for which is being requested an extension of its expiration.
725    pub fn new(endpoint: FlightEndpoint) -> Self {
726        Self {
727            endpoint: Some(endpoint),
728        }
729    }
730}
731
732impl Action {
733    /// Create a new Action with type and body
734    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    /// Create a new Result with the specified body
744    pub fn new(body: impl Into<Bytes>) -> Self {
745        Self { body: body.into() }
746    }
747}
748
749impl Ticket {
750    /// Create a new `Ticket`
751    ///
752    /// # Example
753    ///
754    /// ```
755    /// # use arrow_flight::Ticket;
756    /// let ticket = Ticket::new("SELECT * from FOO");
757    /// ```
758    pub fn new(ticket: impl Into<Bytes>) -> Self {
759        Self {
760            ticket: ticket.into(),
761        }
762    }
763}
764
765impl FlightEndpoint {
766    /// Create a new, empty `FlightEndpoint` that represents a location
767    /// to retrieve Flight results.
768    ///
769    /// # Example
770    /// ```
771    /// # use arrow_flight::{FlightEndpoint, Ticket};
772    /// #
773    /// // Specify the client should fetch results from this server
774    /// let endpoint = FlightEndpoint::new()
775    ///   .with_ticket(Ticket::new("the ticket"));
776    ///
777    /// // Specify the client should fetch results from either
778    /// // `http://example.com` or `https://example.com`
779    /// let endpoint = FlightEndpoint::new()
780    ///   .with_ticket(Ticket::new("the ticket"))
781    ///   .with_location("http://example.com")
782    ///   .with_location("https://example.com");
783    /// ```
784    pub fn new() -> FlightEndpoint {
785        Default::default()
786    }
787
788    /// Set the [`Ticket`] used to retrieve data from the endpoint
789    pub fn with_ticket(mut self, ticket: Ticket) -> Self {
790        self.ticket = Some(ticket);
791        self
792    }
793
794    /// Add a location `uri` to this endpoint. Note each endpoint can
795    /// have multiple locations.
796    ///
797    /// If no `uri` is specified, the [Flight Spec] says:
798    ///
799    /// ```text
800    /// * If the list is empty, the expectation is that the ticket can only
801    /// * be redeemed on the current service where the ticket was
802    /// * generated.
803    /// ```
804    /// [Flight Spec]: https://github.com/apache/arrow-rs/blob/17ca4d51d0490f9c65f5adde144f677dbc8300e7/format/Flight.proto#L307C2-L312
805    pub fn with_location(mut self, uri: impl Into<String>) -> Self {
806        self.location.push(Location { uri: uri.into() });
807        self
808    }
809
810    /// Specify expiration time for this stream
811    pub fn with_expiration_time(mut self, expiration_time: Timestamp) -> Self {
812        self.expiration_time = Some(expiration_time);
813        self
814    }
815
816    /// Add optional application specific metadata to the message
817    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        // V5 with write_legacy_ipc_format = false
883        // this will write the continuation marker
884        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        // V4 with write_legacy_ipc_format = true
891        // this will not write the continuation marker
892        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        // Test for https://github.com/apache/arrow-rs/issues/7058
902        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}