Skip to main content

datafusion_datasource/
file_compression_type.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//! File Compression type abstraction
6
7use std::str::FromStr;
8
9use datafusion_common::error::{DataFusionError, Result};
10
11use datafusion_common::GetExt;
12use datafusion_common::parsers::CompressionTypeVariant::{self, *};
13
14#[cfg(feature = "compression")]
15use async_compression::tokio::bufread::{
16    BzDecoder as AsyncBzDecoder, BzEncoder as AsyncBzEncoder,
17    GzipDecoder as AsyncGzDecoder, GzipEncoder as AsyncGzEncoder,
18    XzDecoder as AsyncXzDecoder, XzEncoder as AsyncXzEncoder,
19    ZstdDecoder as AsyncZstdDecoer, ZstdEncoder as AsyncZstdEncoder,
20};
21
22#[cfg(feature = "compression")]
23use async_compression::tokio::write::{BzEncoder, GzipEncoder, XzEncoder, ZstdEncoder};
24use bytes::Bytes;
25#[cfg(feature = "compression")]
26use bzip2::read::MultiBzDecoder;
27#[cfg(feature = "compression")]
28use flate2::read::MultiGzDecoder;
29use futures::StreamExt;
30#[cfg(feature = "compression")]
31use futures::TryStreamExt;
32use futures::stream::BoxStream;
33#[cfg(feature = "compression")]
34use liblzma::read::XzDecoder;
35use tokio::io::AsyncWrite;
36#[cfg(feature = "compression")]
37use tokio_util::io::{ReaderStream, StreamReader};
38#[cfg(feature = "compression")]
39use zstd::Decoder as ZstdDecoder;
40
41/// Readable file compression type
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct FileCompressionType {
44    variant: CompressionTypeVariant,
45}
46
47impl GetExt for FileCompressionType {
48    fn get_ext(&self) -> String {
49        match self.variant {
50            GZIP => ".gz".to_owned(),
51            BZIP2 => ".bz2".to_owned(),
52            XZ => ".xz".to_owned(),
53            ZSTD => ".zst".to_owned(),
54            UNCOMPRESSED => "".to_owned(),
55        }
56    }
57}
58
59impl From<CompressionTypeVariant> for FileCompressionType {
60    fn from(t: CompressionTypeVariant) -> Self {
61        Self { variant: t }
62    }
63}
64
65impl From<FileCompressionType> for CompressionTypeVariant {
66    fn from(t: FileCompressionType) -> Self {
67        t.variant
68    }
69}
70
71impl FromStr for FileCompressionType {
72    type Err = DataFusionError;
73
74    fn from_str(s: &str) -> Result<Self> {
75        let variant = CompressionTypeVariant::from_str(s).map_err(|_| {
76            DataFusionError::NotImplemented(format!("Unknown FileCompressionType: {s}"))
77        })?;
78        Ok(Self { variant })
79    }
80}
81
82/// `FileCompressionType` implementation
83impl FileCompressionType {
84    /// Gzip-ed file
85    pub const GZIP: Self = Self { variant: GZIP };
86
87    /// Bzip2-ed file
88    pub const BZIP2: Self = Self { variant: BZIP2 };
89
90    /// Xz-ed file (liblzma)
91    pub const XZ: Self = Self { variant: XZ };
92
93    /// Zstd-ed file
94    pub const ZSTD: Self = Self { variant: ZSTD };
95
96    /// Uncompressed file
97    pub const UNCOMPRESSED: Self = Self {
98        variant: UNCOMPRESSED,
99    };
100
101    /// Read only access to self.variant
102    pub fn get_variant(&self) -> &CompressionTypeVariant {
103        &self.variant
104    }
105
106    /// The file is compressed or not
107    pub const fn is_compressed(&self) -> bool {
108        self.variant.is_compressed()
109    }
110
111    /// Given a `Stream`, create a `Stream` which data are compressed with `FileCompressionType`.
112    pub fn convert_to_compress_stream<'a>(
113        &self,
114        s: BoxStream<'a, Result<Bytes>>,
115    ) -> Result<BoxStream<'a, Result<Bytes>>> {
116        Ok(match self.variant {
117            #[cfg(feature = "compression")]
118            GZIP => ReaderStream::new(AsyncGzEncoder::new(StreamReader::new(s)))
119                .map_err(DataFusionError::from)
120                .boxed(),
121            #[cfg(feature = "compression")]
122            BZIP2 => ReaderStream::new(AsyncBzEncoder::new(StreamReader::new(s)))
123                .map_err(DataFusionError::from)
124                .boxed(),
125            #[cfg(feature = "compression")]
126            XZ => ReaderStream::new(AsyncXzEncoder::new(StreamReader::new(s)))
127                .map_err(DataFusionError::from)
128                .boxed(),
129            #[cfg(feature = "compression")]
130            ZSTD => ReaderStream::new(AsyncZstdEncoder::new(StreamReader::new(s)))
131                .map_err(DataFusionError::from)
132                .boxed(),
133            #[cfg(not(feature = "compression"))]
134            GZIP | BZIP2 | XZ | ZSTD => {
135                return Err(DataFusionError::NotImplemented(
136                    "Compression feature is not enabled".to_owned(),
137                ));
138            }
139            UNCOMPRESSED => s.boxed(),
140        })
141    }
142
143    /// Wrap the given `BufWriter` so that it performs compressed writes
144    /// according to this `FileCompressionType` using the default compression level.
145    pub fn convert_async_writer(
146        &self,
147        w: impl AsyncWrite + Send + Unpin + 'static,
148    ) -> Result<Box<dyn AsyncWrite + Send + Unpin>> {
149        self.convert_async_writer_with_level(w, None)
150    }
151
152    /// Wrap the given `BufWriter` so that it performs compressed writes
153    /// according to this `FileCompressionType`.
154    ///
155    /// If `compression_level` is `Some`, the encoder will use the specified
156    /// compression level. If `None`, the default level for each algorithm is used.
157    pub fn convert_async_writer_with_level(
158        &self,
159        w: impl AsyncWrite + Send + Unpin + 'static,
160        compression_level: Option<u32>,
161    ) -> Result<Box<dyn AsyncWrite + Send + Unpin>> {
162        #[cfg(feature = "compression")]
163        use async_compression::Level;
164
165        Ok(match self.variant {
166            #[cfg(feature = "compression")]
167            GZIP => match compression_level {
168                Some(level) => {
169                    Box::new(GzipEncoder::with_quality(w, Level::Precise(level as i32)))
170                }
171                None => Box::new(GzipEncoder::new(w)),
172            },
173            #[cfg(feature = "compression")]
174            BZIP2 => match compression_level {
175                Some(level) => {
176                    Box::new(BzEncoder::with_quality(w, Level::Precise(level as i32)))
177                }
178                None => Box::new(BzEncoder::new(w)),
179            },
180            #[cfg(feature = "compression")]
181            XZ => match compression_level {
182                Some(level) => {
183                    Box::new(XzEncoder::with_quality(w, Level::Precise(level as i32)))
184                }
185                None => Box::new(XzEncoder::new(w)),
186            },
187            #[cfg(feature = "compression")]
188            ZSTD => match compression_level {
189                Some(level) => {
190                    Box::new(ZstdEncoder::with_quality(w, Level::Precise(level as i32)))
191                }
192                None => Box::new(ZstdEncoder::new(w)),
193            },
194            #[cfg(not(feature = "compression"))]
195            GZIP | BZIP2 | XZ | ZSTD => {
196                // compression_level is not used when compression feature is disabled
197                let _ = compression_level;
198                return Err(DataFusionError::NotImplemented(
199                    "Compression feature is not enabled".to_owned(),
200                ));
201            }
202            UNCOMPRESSED => Box::new(w),
203        })
204    }
205
206    /// Given a `Stream`, create a `Stream` which data are decompressed with `FileCompressionType`.
207    pub fn convert_stream<'a>(
208        &self,
209        s: BoxStream<'a, Result<Bytes>>,
210    ) -> Result<BoxStream<'a, Result<Bytes>>> {
211        Ok(match self.variant {
212            #[cfg(feature = "compression")]
213            GZIP => {
214                let mut decoder = AsyncGzDecoder::new(StreamReader::new(s));
215                decoder.multiple_members(true);
216
217                ReaderStream::new(decoder)
218                    .map_err(DataFusionError::from)
219                    .boxed()
220            }
221            #[cfg(feature = "compression")]
222            BZIP2 => ReaderStream::new(AsyncBzDecoder::new(StreamReader::new(s)))
223                .map_err(DataFusionError::from)
224                .boxed(),
225            #[cfg(feature = "compression")]
226            XZ => ReaderStream::new(AsyncXzDecoder::new(StreamReader::new(s)))
227                .map_err(DataFusionError::from)
228                .boxed(),
229            #[cfg(feature = "compression")]
230            ZSTD => ReaderStream::new(AsyncZstdDecoer::new(StreamReader::new(s)))
231                .map_err(DataFusionError::from)
232                .boxed(),
233            #[cfg(not(feature = "compression"))]
234            GZIP | BZIP2 | XZ | ZSTD => {
235                return Err(DataFusionError::NotImplemented(
236                    "Compression feature is not enabled".to_owned(),
237                ));
238            }
239            UNCOMPRESSED => s.boxed(),
240        })
241    }
242
243    /// Given a `Read`, create a `Read` which data are decompressed with `FileCompressionType`.
244    pub fn convert_read<T: std::io::Read + Send + 'static>(
245        &self,
246        r: T,
247    ) -> Result<Box<dyn std::io::Read + Send>> {
248        Ok(match self.variant {
249            #[cfg(feature = "compression")]
250            GZIP => Box::new(MultiGzDecoder::new(r)),
251            #[cfg(feature = "compression")]
252            BZIP2 => Box::new(MultiBzDecoder::new(r)),
253            #[cfg(feature = "compression")]
254            XZ => Box::new(XzDecoder::new_multi_decoder(r)),
255            #[cfg(feature = "compression")]
256            ZSTD => match ZstdDecoder::new(r) {
257                Ok(decoder) => Box::new(decoder),
258                Err(e) => return Err(DataFusionError::External(Box::new(e))),
259            },
260            #[cfg(not(feature = "compression"))]
261            GZIP | BZIP2 | XZ | ZSTD => {
262                return Err(DataFusionError::NotImplemented(
263                    "Compression feature is not enabled".to_owned(),
264                ));
265            }
266            UNCOMPRESSED => Box::new(r),
267        })
268    }
269}
270
271/// Trait for extending the functionality of the `FileType` enum.
272pub trait FileTypeExt {
273    /// Given a `FileCompressionType`, return the `FileType`'s extension with compression suffix
274    fn get_ext_with_compression(&self, c: FileCompressionType) -> Result<String>;
275}
276
277#[cfg(test)]
278mod tests {
279    use std::str::FromStr;
280
281    use super::FileCompressionType;
282    use datafusion_common::error::DataFusionError;
283
284    use bytes::Bytes;
285    use futures::StreamExt;
286
287    #[test]
288    fn from_str() {
289        for (ext, compression_type) in [
290            ("gz", FileCompressionType::GZIP),
291            ("GZ", FileCompressionType::GZIP),
292            ("gzip", FileCompressionType::GZIP),
293            ("GZIP", FileCompressionType::GZIP),
294            ("xz", FileCompressionType::XZ),
295            ("XZ", FileCompressionType::XZ),
296            ("bz2", FileCompressionType::BZIP2),
297            ("BZ2", FileCompressionType::BZIP2),
298            ("bzip2", FileCompressionType::BZIP2),
299            ("BZIP2", FileCompressionType::BZIP2),
300            ("zst", FileCompressionType::ZSTD),
301            ("ZST", FileCompressionType::ZSTD),
302            ("zstd", FileCompressionType::ZSTD),
303            ("ZSTD", FileCompressionType::ZSTD),
304            ("", FileCompressionType::UNCOMPRESSED),
305        ] {
306            assert_eq!(
307                FileCompressionType::from_str(ext).unwrap(),
308                compression_type
309            );
310        }
311
312        assert!(matches!(
313            FileCompressionType::from_str("Unknown"),
314            Err(DataFusionError::NotImplemented(_))
315        ));
316    }
317
318    #[tokio::test]
319    async fn test_bgzip_stream_decoding() -> Result<(), DataFusionError> {
320        // As described in https://samtools.github.io/hts-specs/SAMv1.pdf ("The BGZF compression format")
321
322        // Ignore rust formatting so the byte array is easier to read
323        #[rustfmt::skip]
324        let data = [
325            // Block header
326            0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
327            0x02, 0x00,
328            // Block 0, literal: 42
329            0x1e, 0x00, 0x33, 0x31, 0xe2, 0x02, 0x00, 0x31, 0x29, 0x86, 0xd1, 0x03, 0x00, 0x00, 0x00,
330            // Block header
331            0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
332            0x02, 0x00,
333            // Block 1, literal: 42
334            0x1e, 0x00, 0x33, 0x31, 0xe2, 0x02, 0x00, 0x31, 0x29, 0x86, 0xd1, 0x03, 0x00, 0x00, 0x00,
335            // EOF
336            0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43,
337            0x02, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
338        ];
339
340        // Create a byte stream
341        let stream = futures::stream::iter(vec![Ok::<Bytes, DataFusionError>(
342            Bytes::from(data.to_vec()),
343        )]);
344        let converted_stream =
345            FileCompressionType::GZIP.convert_stream(stream.boxed())?;
346
347        let vec = converted_stream
348            .map(|r| r.unwrap())
349            .collect::<Vec<Bytes>>()
350            .await;
351
352        let string_value = String::from_utf8_lossy(&vec[0]);
353
354        assert_eq!(string_value, "42\n42\n");
355
356        Ok(())
357    }
358}