1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! Harmonious distributed data processing & analysis in Rust.
//!
//! <p style="font-family: 'Fira Sans',sans-serif;padding:0.3em 0"><strong>
//! <a href="https://crates.io/crates/amadeus">📦&nbsp;&nbsp;Crates.io</a>&nbsp;&nbsp;│&nbsp;&nbsp;<a href="https://github.com/constellation-rs/amadeus">📑&nbsp;&nbsp;GitHub</a>&nbsp;&nbsp;│&nbsp;&nbsp;<a href="https://constellation.zulipchat.com/#narrow/stream/213231-amadeus">💬&nbsp;&nbsp;Chat</a>
//! </strong></p>
//!
//! This is a support crate of [Amadeus](https://github.com/constellation-rs/amadeus) and is not intended to be used directly. These types are re-exposed in [`amadeus::source`](https://docs.rs/amadeus/0.3/amadeus/source/index.html).

#![doc(html_root_url = "https://docs.rs/amadeus-parquet/0.4.2")]
#![cfg_attr(nightly, feature(bufreader_seek_relative))]
#![cfg_attr(nightly, feature(read_initializer))]
#![cfg_attr(nightly, feature(specialization))]
#![cfg_attr(nightly, feature(type_alias_impl_trait))]
#![cfg_attr(nightly, feature(test))]
#![warn(
	// missing_copy_implementations,
	// missing_debug_implementations,
	// missing_docs,
	// trivial_numeric_casts,
	unused_import_braces,
	unused_qualifications,
	unused_results,
	// unreachable_pub,
	// clippy::pedantic,
)]
#![allow(
	clippy::module_name_repetitions,
	clippy::similar_names,
	clippy::if_not_else,
	clippy::must_use_candidate,
	clippy::missing_errors_doc,
	dead_code,
	clippy::all,
	incomplete_features
)]
// #![deny(unsafe_code)]

#[cfg(nightly)]
extern crate test;

#[cfg(nightly)]
mod internal;

#[cfg(nightly)]
mod wrap {
	use super::internal;
	use async_trait::async_trait;
	use educe::Educe;
	use futures::{pin_mut, stream, AsyncReadExt, FutureExt, StreamExt};
	use internal::{
		errors::ParquetError as InternalParquetError, file::reader::{FileReader, ParquetReader, SerializedFileReader}
	};
	use serde::{Deserialize, Serialize};
	use serde_closure::*;
	use std::{
		error, fmt::{self, Debug, Display}, io::Cursor, marker::PhantomData, ops::FnMut
	};

	use amadeus_core::{
		file::{Directory, File, Page, Partition, PathBuf}, into_par_stream::IntoDistributedStream, par_stream::DistributedStream, util::{DistParStream, ResultExpandIter}, Source
	};

	pub use internal::record::ParquetData;

	#[doc(hidden)]
	pub mod derive {
		pub use super::{
			internal::{
				basic::Repetition, column::reader::ColumnReader, errors::{ParquetError, Result as ParquetResult}, record::{DisplaySchemaGroup, Reader, Schema as ParquetSchema}, schema::types::{ColumnPath, Type}
			}, ParquetData
		};
	}

	#[derive(Educe)]
	#[educe(Clone, Debug)]
	pub struct Parquet<File, Row>
	where
		File: amadeus_core::file::File,
		Row: ParquetData,
	{
		partitions: Vec<File::Partition>,
		marker: PhantomData<fn() -> Row>,
	}
	impl<F, Row> Parquet<F, Row>
	where
		F: File,
		Row: ParquetData + 'static,
	{
		pub async fn new(file: F) -> Result<Self, <Self as Source>::Error> {
			Ok(Self {
				partitions: file.partitions().await.map_err(ParquetError::File)?,
				marker: PhantomData,
			})
		}
	}
	impl<F, Row> Source for Parquet<F, Row>
	where
		F: File,
		Row: ParquetData + 'static,
	{
		type Item = Row;
		#[allow(clippy::type_complexity)]
		type Error = ParquetError<
			<F as File>::Error,
			<<F as File>::Partition as Partition>::Error,
			<<<F as File>::Partition as Partition>::Page as Page>::Error,
		>;

		type ParStream =
			impl amadeus_core::par_stream::ParallelStream<Item = Result<Self::Item, Self::Error>>;
		type DistStream = impl DistributedStream<Item = Result<Self::Item, Self::Error>>;

		fn par_stream(self) -> Self::ParStream {
			DistParStream::new(self.dist_stream())
		}
		#[allow(clippy::let_and_return)]
		fn dist_stream(self) -> Self::DistStream {
			self.partitions
				.into_dist_stream()
				.flat_map(FnMut!(|partition: F::Partition| async move {
					Ok(stream::iter(
						partition
							.pages()
							.await
							.map_err(ParquetError::Partition)?
							.into_iter(),
					)
					.flat_map(|page| {
						async move {
							let mut buf = Vec::with_capacity(10 * 1024 * 1024);
							let reader = Page::reader(page);
							pin_mut!(reader);
							let buf = PassError::new(
								reader.read_to_end(&mut buf).await.map(|_| Cursor::new(buf)),
							);
							Ok(stream::iter(
								SerializedFileReader::new(buf)?.get_row_iter::<Row>(None)?,
							))
						}
						.map(ResultExpandIter::new)
						.flatten_stream()
					})
					.map(|row: Result<Result<Row, _>, Self::Error>| Ok(row??)))
				}
				.map(ResultExpandIter::new)
				.flatten_stream()
				.map(|row: Result<Result<Row, Self::Error>, Self::Error>| Ok(row??))))
		}
	}

	// impl<P> ParquetReader for amadeus_core::file::Reader<P>
	// where
	// 	P: Page,
	// {
	// 	fn len(&self) -> u64 {
	// 		self.len()
	// 	}
	// }

	#[derive(Serialize, Deserialize)]
	pub struct ParquetDirectory<D> {
		directory: D,
	}
	impl<D> ParquetDirectory<D> {
		pub fn new(directory: D) -> Self {
			Self { directory }
		}
	}
	#[async_trait(?Send)]
	impl<D> File for ParquetDirectory<D>
	where
		D: Directory,
		D::Partition: Debug,
	{
		type Partition = D::Partition;
		type Error = D::Error;

		async fn partitions(self) -> Result<Vec<Self::Partition>, Self::Error> {
			self.partitions_filter(|_| true).await
		}
	}
	#[async_trait(?Send)]
	impl<D> Directory for ParquetDirectory<D>
	where
		D: Directory,
		D::Partition: Debug,
	{
		async fn partitions_filter<F>(
			self, mut f: F,
		) -> Result<Vec<<Self as File>::Partition>, <Self as File>::Error>
		where
			F: FnMut(&PathBuf) -> bool,
		{
			// "Logic" interpreted from https://github.com/apache/arrow/blob/927cfeff875e557e28649891ea20ca38cb9d1536/python/pyarrow/parquet.py#L705-L829
			// and https://github.com/apache/spark/blob/5a7403623d0525c23ab8ae575e9d1383e3e10635/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/InMemoryFileIndex.scala#L348-L359
			// and https://github.com/apache/spark/blob/5a7403623d0525c23ab8ae575e9d1383e3e10635/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetPartitionDiscoverySuite.scala
			self.directory
				.partitions_filter(|path| {
					let skip;
					if !path.is_file() {
						let dir_name = path.last().unwrap().to_string_lossy();

						skip = dir_name.starts_with('.') // Hidden files
							|| (dir_name.starts_with('_') && !dir_name.contains('=')) // ARROW-1079: Filter out "private" directories starting with underscore;
					} else {
						let file_name = path.file_name().unwrap().to_string_lossy();
						let extension = file_name.rfind('.').map(|offset| &file_name[offset + 1..]);
						skip = file_name.starts_with('.') // Hidden files
								|| file_name == "_metadata" || file_name == "_common_metadata" // Summary metadata
								|| file_name == "_SUCCESS" // Spark success marker
								|| extension == Some("_COPYING_") // File copy in progress; TODO: Should we error on this?
								|| extension == Some("crc") // Checksums
								|| file_name.ends_with("_$folder$"); // This is created by Apache tools on S3
					}
					!skip && f(path)
				})
				.await
		}
	}

	mod misc_serde {
		use super::internal;
		use internal::errors::ParquetError;
		use serde::{Deserialize, Deserializer, Serialize, Serializer};

		pub struct Serde<T>(T);

		impl Serialize for Serde<&ParquetError> {
			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
			where
				S: Serializer,
			{
				<(usize, &str)>::serialize(
					&match self.0 {
						ParquetError::General(message) => (0, message),
						ParquetError::EOF(message) => (1, message),
						_ => unimplemented!(),
					},
					serializer,
				)
			}
		}
		impl<'de> Deserialize<'de> for Serde<ParquetError> {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: Deserializer<'de>,
			{
				<(usize, String)>::deserialize(deserializer)
					.map(|(kind, message)| match kind {
						1 => ParquetError::EOF(message),
						_ => ParquetError::General(message),
					})
					.map(Self)
			}
		}

		pub fn serialize<T, S>(t: &T, serializer: S) -> Result<S::Ok, S::Error>
		where
			for<'a> Serde<&'a T>: Serialize,
			S: Serializer,
		{
			Serde(t).serialize(serializer)
		}
		pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
		where
			Serde<T>: Deserialize<'de>,
			D: Deserializer<'de>,
		{
			Serde::<T>::deserialize(deserializer).map(|x| x.0)
		}
	}

	#[derive(Serialize, Deserialize, Debug)]
	pub enum ParquetError<A, B, C> {
		File(A),
		Partition(B),
		Page(C),
		Parquet(#[serde(with = "misc_serde")] InternalParquetError),
	}
	impl<A, B, C> PartialEq for ParquetError<A, B, C>
	where
		A: PartialEq,
		B: PartialEq,
		C: PartialEq,
	{
		fn eq(&self, other: &Self) -> bool {
			match (self, other) {
				(Self::File(a), Self::File(b)) => a == b,
				(Self::Partition(a), Self::Partition(b)) => a == b,
				(Self::Page(a), Self::Page(b)) => a == b,
				(Self::Parquet(a), Self::Parquet(b)) => a == b,
				_ => false,
			}
		}
	}
	impl<A, B, C> error::Error for ParquetError<A, B, C>
	where
		A: error::Error,
		B: error::Error,
		C: error::Error,
	{
	}
	impl<A, B, C> Display for ParquetError<A, B, C>
	where
		A: Display,
		B: Display,
		C: Display,
	{
		fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
			match self {
				Self::File(err) => Display::fmt(err, f),
				Self::Partition(err) => Display::fmt(err, f),
				Self::Page(err) => Display::fmt(err, f),
				Self::Parquet(err) => Display::fmt(err, f),
			}
		}
	}
	impl<A, B, C> From<InternalParquetError> for ParquetError<A, B, C> {
		fn from(err: InternalParquetError) -> Self {
			Self::Parquet(err)
		}
	}

	use std::io;

	impl ParquetReader for PassError<Cursor<Vec<u8>>> {
		fn len(&self) -> u64 {
			self.0.as_ref().unwrap().get_ref().len() as u64
		}
	}

	struct PassError<R>(Result<R, Option<io::Error>>);
	impl<R> PassError<R> {
		fn new(r: Result<R, io::Error>) -> Self {
			Self(r.map_err(Some))
		}
	}
	impl<R> io::Read for PassError<R>
	where
		R: io::Read,
	{
		fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
			match &mut self.0 {
				Ok(r) => r.read(buf),
				Err(r) => Err(r.take().unwrap()),
			}
		}
	}
	impl<R> io::Seek for PassError<R>
	where
		R: io::Seek,
	{
		fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
			match &mut self.0 {
				Ok(r) => r.seek(pos),
				Err(r) => Err(r.take().unwrap()),
			}
		}
	}
}
#[cfg(nightly)]
pub use wrap::*;