forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_stream.rs
370 lines (332 loc) · 12.1 KB
/
file_stream.rs
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
363
364
365
366
367
368
369
370
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! A generic stream over file format readers that can be used by
//! any file format that read its files from start to end.
//!
//! Note: Most traits here need to be marked `Sync + Send` to be
//! compliant with the `SendableRecordBatchStream` trait.
use std::collections::VecDeque;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use arrow::datatypes::SchemaRef;
use arrow::{error::Result as ArrowResult, record_batch::RecordBatch};
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use futures::{ready, FutureExt, Stream, StreamExt};
use object_store::ObjectStore;
use datafusion_common::ScalarValue;
use crate::datasource::listing::PartitionedFile;
use crate::error::Result;
use crate::execution::context::TaskContext;
use crate::physical_plan::file_format::{
FileMeta, FileScanConfig, PartitionColumnProjector,
};
use crate::physical_plan::metrics::BaselineMetrics;
use crate::physical_plan::RecordBatchStream;
/// A fallible future that resolves to a stream of [`RecordBatch`]
pub type FileOpenFuture =
BoxFuture<'static, Result<BoxStream<'static, ArrowResult<RecordBatch>>>>;
pub trait FileOpener: Unpin {
fn open(
&self,
store: Arc<dyn ObjectStore>,
file_meta: FileMeta,
) -> Result<FileOpenFuture>;
}
/// A stream that iterates record batch by record batch, file over file.
pub struct FileStream<F: FileOpener> {
/// An iterator over input files.
file_iter: VecDeque<PartitionedFile>,
/// The stream schema (file schema including partition columns and after
/// projection).
projected_schema: SchemaRef,
/// The remaining number of records to parse, None if no limit
remain: Option<usize>,
/// A closure that takes a reader and an optional remaining number of lines
/// (before reaching the limit) and returns a batch iterator. If the file reader
/// is not capable of limiting the number of records in the last batch, the file
/// stream will take care of truncating it.
file_reader: F,
/// The partition column projector
pc_projector: PartitionColumnProjector,
/// the store from which to source the files.
object_store: Arc<dyn ObjectStore>,
/// The stream state
state: FileStreamState,
/// runtime metrics recording
baseline_metrics: BaselineMetrics,
}
enum FileStreamState {
/// The idle state, no file is currently being read
Idle,
/// Currently performing asynchronous IO to obtain a stream of RecordBatch
/// for a given parquet file
Open {
/// A [`FileOpenFuture`] returned by [`FormatReader::open`]
future: FileOpenFuture,
/// The partition values for this file
partition_values: Vec<ScalarValue>,
},
/// Scanning the [`BoxStream`] returned by the completion of a [`FileOpenFuture`]
/// returned by [`FormatReader::open`]
Scan {
/// Partitioning column values for the current batch_iter
partition_values: Vec<ScalarValue>,
/// The reader instance
reader: BoxStream<'static, ArrowResult<RecordBatch>>,
},
/// Encountered an error
Error,
/// Reached the row limit
Limit,
}
impl<F: FileOpener> FileStream<F> {
pub fn new(
config: &FileScanConfig,
partition: usize,
context: Arc<TaskContext>,
file_reader: F,
baseline_metrics: BaselineMetrics,
) -> Result<Self> {
let (projected_schema, _) = config.project();
let pc_projector = PartitionColumnProjector::new(
projected_schema.clone(),
&config.table_partition_cols,
);
let files = config.file_groups[partition].clone();
let object_store = context
.runtime_env()
.object_store(&config.object_store_url)?;
Ok(Self {
file_iter: files.into(),
projected_schema,
remain: config.limit,
file_reader,
pc_projector,
object_store,
state: FileStreamState::Idle,
baseline_metrics,
})
}
fn poll_inner(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<ArrowResult<RecordBatch>>> {
loop {
match &mut self.state {
FileStreamState::Idle => {
let part_file = match self.file_iter.pop_front() {
Some(file) => file,
None => return Poll::Ready(None),
};
let file_meta = FileMeta {
object_meta: part_file.object_meta,
range: part_file.range,
extensions: part_file.extensions,
};
match self.file_reader.open(self.object_store.clone(), file_meta) {
Ok(future) => {
self.state = FileStreamState::Open {
future,
partition_values: part_file.partition_values,
}
}
Err(e) => {
self.state = FileStreamState::Error;
return Poll::Ready(Some(Err(e.into())));
}
}
}
FileStreamState::Open {
future,
partition_values,
} => match ready!(future.poll_unpin(cx)) {
Ok(reader) => {
self.state = FileStreamState::Scan {
partition_values: std::mem::take(partition_values),
reader,
};
}
Err(e) => {
self.state = FileStreamState::Error;
return Poll::Ready(Some(Err(e.into())));
}
},
FileStreamState::Scan {
reader,
partition_values,
} => match ready!(reader.poll_next_unpin(cx)) {
Some(result) => {
let result = result
.and_then(|b| self.pc_projector.project(b, partition_values))
.map(|batch| match &mut self.remain {
Some(remain) => {
if *remain > batch.num_rows() {
*remain -= batch.num_rows();
batch
} else {
let batch = batch.slice(0, *remain);
self.state = FileStreamState::Limit;
*remain = 0;
batch
}
}
None => batch,
});
if result.is_err() {
self.state = FileStreamState::Error
}
return Poll::Ready(Some(result));
}
None => self.state = FileStreamState::Idle,
},
FileStreamState::Error | FileStreamState::Limit => {
return Poll::Ready(None)
}
}
}
}
}
impl<F: FileOpener> Stream for FileStream<F> {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let cloned_time = self.baseline_metrics.elapsed_compute().clone();
let timer = cloned_time.timer();
let result = self.poll_inner(cx);
timer.done();
self.baseline_metrics.record_poll(result)
}
}
impl<F: FileOpener> RecordBatchStream for FileStream<F> {
fn schema(&self) -> SchemaRef {
self.projected_schema.clone()
}
}
#[cfg(test)]
mod tests {
use futures::StreamExt;
use super::*;
use crate::datasource::object_store::ObjectStoreUrl;
use crate::physical_plan::metrics::ExecutionPlanMetricsSet;
use crate::prelude::SessionContext;
use crate::{
error::Result,
test::{make_partition, object_store::register_test_store},
};
struct TestOpener {
records: Vec<RecordBatch>,
}
impl FileOpener for TestOpener {
fn open(
&self,
_store: Arc<dyn ObjectStore>,
_file_meta: FileMeta,
) -> Result<FileOpenFuture> {
let iterator = self.records.clone().into_iter().map(Ok);
let stream = futures::stream::iter(iterator).boxed();
Ok(futures::future::ready(Ok(stream)).boxed())
}
}
/// helper that creates a stream of 2 files with the same pair of batches in each ([0,1,2] and [0,1])
async fn create_and_collect(limit: Option<usize>) -> Vec<RecordBatch> {
let records = vec![make_partition(3), make_partition(2)];
let file_schema = records[0].schema();
let reader = TestOpener { records };
let ctx = SessionContext::new();
register_test_store(&ctx, &[("mock_file1", 10), ("mock_file2", 20)]);
let config = FileScanConfig {
object_store_url: ObjectStoreUrl::parse("test:///").unwrap(),
file_schema,
file_groups: vec![vec![
PartitionedFile::new("mock_file1".to_owned(), 10),
PartitionedFile::new("mock_file2".to_owned(), 20),
]],
statistics: Default::default(),
projection: None,
limit,
table_partition_cols: vec![],
};
let metrics = BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
let file_stream =
FileStream::new(&config, 0, ctx.task_ctx(), reader, metrics).unwrap();
file_stream
.map(|b| b.expect("No error expected in stream"))
.collect::<Vec<_>>()
.await
}
#[tokio::test]
async fn without_limit() -> Result<()> {
let batches = create_and_collect(None).await;
#[rustfmt::skip]
crate::assert_batches_eq!(&[
"+---+",
"| i |",
"+---+",
"| 0 |",
"| 1 |",
"| 2 |",
"| 0 |",
"| 1 |",
"| 0 |",
"| 1 |",
"| 2 |",
"| 0 |",
"| 1 |",
"+---+",
], &batches);
Ok(())
}
#[tokio::test]
async fn with_limit_between_files() -> Result<()> {
let batches = create_and_collect(Some(5)).await;
#[rustfmt::skip]
crate::assert_batches_eq!(&[
"+---+",
"| i |",
"+---+",
"| 0 |",
"| 1 |",
"| 2 |",
"| 0 |",
"| 1 |",
"+---+",
], &batches);
Ok(())
}
#[tokio::test]
async fn with_limit_at_middle_of_batch() -> Result<()> {
let batches = create_and_collect(Some(6)).await;
#[rustfmt::skip]
crate::assert_batches_eq!(&[
"+---+",
"| i |",
"+---+",
"| 0 |",
"| 1 |",
"| 2 |",
"| 0 |",
"| 1 |",
"| 0 |",
"+---+",
], &batches);
Ok(())
}
}