Skip to main content

datafusion_datasource/
decoder.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//! Module containing helper methods for the various file formats
6//! See write.rs for write related helper methods
7
8use ::arrow::array::RecordBatch;
9
10use arrow::error::ArrowError;
11use bytes::Buf;
12use bytes::Bytes;
13use datafusion_common::Result;
14use futures::StreamExt as _;
15use futures::stream::BoxStream;
16use futures::{Stream, ready};
17use std::collections::VecDeque;
18use std::fmt;
19use std::task::Poll;
20
21/// Possible outputs of a [`BatchDeserializer`].
22#[derive(Debug, PartialEq)]
23pub enum DeserializerOutput {
24    /// A successfully deserialized [`RecordBatch`].
25    RecordBatch(RecordBatch),
26    /// The deserializer requires more data to make progress.
27    RequiresMoreData,
28    /// The input data has been exhausted.
29    InputExhausted,
30}
31
32/// Trait defining a scheme for deserializing byte streams into structured data.
33/// Implementors of this trait are responsible for converting raw bytes into
34/// `RecordBatch` objects.
35pub trait BatchDeserializer<T>: Send + fmt::Debug {
36    /// Feeds a message for deserialization, updating the internal state of
37    /// this `BatchDeserializer`. Note that one can call this function multiple
38    /// times before calling `next`, which will queue multiple messages for
39    /// deserialization. Returns the number of bytes consumed.
40    fn digest(&mut self, message: T) -> usize;
41
42    /// Attempts to deserialize any pending messages and returns a
43    /// `DeserializerOutput` to indicate progress.
44    fn next(&mut self) -> Result<DeserializerOutput, ArrowError>;
45
46    /// Informs the deserializer that no more messages will be provided for
47    /// deserialization.
48    fn finish(&mut self);
49}
50
51/// A general interface for decoders such as [`arrow::json::reader::Decoder`] and
52/// [`arrow::csv::reader::Decoder`]. Defines an interface similar to
53/// [`Decoder::decode`] and [`Decoder::flush`] methods, but also includes
54/// a method to check if the decoder can flush early. Intended to be used in
55/// conjunction with [`DecoderDeserializer`].
56///
57/// [`arrow::json::reader::Decoder`]: ::arrow::json::reader::Decoder
58/// [`arrow::csv::reader::Decoder`]: ::arrow::csv::reader::Decoder
59/// [`Decoder::decode`]: ::arrow::json::reader::Decoder::decode
60/// [`Decoder::flush`]: ::arrow::json::reader::Decoder::flush
61pub trait Decoder: Send + fmt::Debug {
62    /// See [`arrow::json::reader::Decoder::decode`].
63    ///
64    /// [`arrow::json::reader::Decoder::decode`]: ::arrow::json::reader::Decoder::decode
65    fn decode(&mut self, buf: &[u8]) -> Result<usize, ArrowError>;
66
67    /// See [`arrow::json::reader::Decoder::flush`].
68    ///
69    /// [`arrow::json::reader::Decoder::flush`]: ::arrow::json::reader::Decoder::flush
70    fn flush(&mut self) -> Result<Option<RecordBatch>, ArrowError>;
71
72    /// Whether the decoder can flush early in its current state.
73    fn can_flush_early(&self) -> bool;
74}
75
76impl<T: Decoder> fmt::Debug for DecoderDeserializer<T> {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.debug_struct("Deserializer")
79            .field("buffered_queue", &self.buffered_queue)
80            .field("finalized", &self.finalized)
81            .finish()
82    }
83}
84
85impl<T: Decoder> BatchDeserializer<Bytes> for DecoderDeserializer<T> {
86    fn digest(&mut self, message: Bytes) -> usize {
87        if message.is_empty() {
88            return 0;
89        }
90
91        let consumed = message.len();
92        self.buffered_queue.push_back(message);
93        consumed
94    }
95
96    fn next(&mut self) -> Result<DeserializerOutput, ArrowError> {
97        while let Some(buffered) = self.buffered_queue.front_mut() {
98            let decoded = self.decoder.decode(buffered)?;
99            buffered.advance(decoded);
100
101            if buffered.is_empty() {
102                self.buffered_queue.pop_front();
103            }
104
105            // Flush when the stream ends or batch size is reached
106            // Certain implementations can flush early
107            if decoded == 0 || self.decoder.can_flush_early() {
108                return match self.decoder.flush() {
109                    Ok(Some(batch)) => Ok(DeserializerOutput::RecordBatch(batch)),
110                    Ok(None) => continue,
111                    Err(e) => Err(e),
112                };
113            }
114        }
115        if self.finalized {
116            Ok(DeserializerOutput::InputExhausted)
117        } else {
118            Ok(DeserializerOutput::RequiresMoreData)
119        }
120    }
121
122    fn finish(&mut self) {
123        self.finalized = true;
124        // Ensure the decoder is flushed:
125        self.buffered_queue.push_back(Bytes::new());
126    }
127}
128
129/// A generic, decoder-based deserialization scheme for processing encoded data.
130///
131/// This struct is responsible for converting a stream of bytes, which represent
132/// encoded data, into a stream of `RecordBatch` objects, following the specified
133/// schema and formatting options. It also handles any buffering necessary to satisfy
134/// the `Decoder` interface.
135pub struct DecoderDeserializer<T: Decoder> {
136    /// The underlying decoder used for deserialization
137    pub(crate) decoder: T,
138    /// The buffer used to store the remaining bytes to be decoded
139    pub(crate) buffered_queue: VecDeque<Bytes>,
140    /// Whether the input stream has been fully consumed
141    pub(crate) finalized: bool,
142}
143
144impl<T: Decoder> DecoderDeserializer<T> {
145    /// Creates a new `DecoderDeserializer` with the provided decoder.
146    pub fn new(decoder: T) -> Self {
147        DecoderDeserializer {
148            decoder,
149            buffered_queue: VecDeque::new(),
150            finalized: false,
151        }
152    }
153}
154
155/// Deserializes a stream of bytes into a stream of [`RecordBatch`] objects using the
156/// provided deserializer.
157///
158/// Returns a boxed stream of `Result<RecordBatch, ArrowError>`. The stream yields [`RecordBatch`]
159/// objects as they are produced by the deserializer, or an [`ArrowError`] if an error
160/// occurs while polling the input or deserializing.
161pub fn deserialize_stream<'a>(
162    mut input: impl Stream<Item = Result<Bytes>> + Unpin + Send + 'a,
163    mut deserializer: impl BatchDeserializer<Bytes> + 'a,
164) -> BoxStream<'a, Result<RecordBatch, ArrowError>> {
165    futures::stream::poll_fn(move |cx| {
166        loop {
167            match ready!(input.poll_next_unpin(cx)).transpose()? {
168                Some(b) => _ = deserializer.digest(b),
169                None => deserializer.finish(),
170            }
171
172            return match deserializer.next()? {
173                DeserializerOutput::RecordBatch(rb) => Poll::Ready(Some(Ok(rb))),
174                DeserializerOutput::InputExhausted => Poll::Ready(None),
175                DeserializerOutput::RequiresMoreData => continue,
176            };
177        }
178    })
179    .boxed()
180}