alamb commented on a change in pull request #950: URL: https://github.com/apache/arrow-datafusion/pull/950#discussion_r697681701
########## File path: datafusion/src/datasource/object_store/mod.rs ########## @@ -0,0 +1,130 @@ +// 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. + +//! Object Store abstracts access to an underlying file/object storage. + +pub mod local; + +use std::collections::HashMap; +use std::fmt::Debug; +use std::pin::Pin; +use std::sync::{Arc, RwLock}; + +use async_trait::async_trait; +use futures::{AsyncRead, Stream}; + +use local::LocalFileSystem; + +use crate::error::{DataFusionError, Result}; +use crate::logical_plan::Expr; +use chrono::Utc; + +/// Object Reader for one file in a object store +#[async_trait] +pub trait ObjectReader { + /// Get reader for a part [start, start + length] in the file asynchronously + async fn get_reader(&self, start: u64, length: usize) -> Result<Arc<dyn AsyncRead>>; + + /// Get length for the file + fn length(&self) -> u64; +} + +/// File meta we got from object store +pub struct FileMeta { + /// Path of the file + pub path: String, + /// Last time the file was modified in UTC + pub last_modified: Option<chrono::DateTime<Utc>>, + /// File size in total + pub size: u64, +} + +/// Stream of files get listed from object store +pub type FileMetaStream = + Pin<Box<dyn Stream<Item = Result<FileMeta>> + Send + Sync + 'static>>; + +/// A ObjectStore abstracts access to an underlying file/object storage. +/// It maps strings (e.g. URLs, filesystem paths, etc) to sources of bytes +#[async_trait] +pub trait ObjectStore: Sync + Send + Debug { + /// Returns all the files in path `prefix` asynchronously, implementations could + /// choose to use the pushed down filters for list filtering. + async fn list(&self, prefix: &str, filters: &[Expr]) -> Result<FileMetaStream>; Review comment: ```suggestion /// Returns all the files in path `prefix` asynchronously, with optional filters. /// /// `filters` are optional expressions that may have been pushed down /// during scans as an optional optimization that can be used to reduce /// returned results. Implementations of /// ObjectStore are *not* required to do anything with optional_filters. async fn list(&self, prefix: &str, optional_filters: Option<&[Expr]>) -> Result<FileMetaStream>; ``` ########## File path: datafusion/src/datasource/object_store/local.rs ########## @@ -0,0 +1,127 @@ +// 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. + +//! Object store that represents the Local File System. + +use std::fs::Metadata; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::{stream, AsyncRead, StreamExt}; + +use crate::datasource::object_store::{ + FileMeta, FileMetaStream, ObjectReader, ObjectStore, +}; +use crate::error::DataFusionError; +use crate::error::Result; +use crate::logical_plan::Expr; + +#[derive(Debug)] +/// Local File System as Object Store. +pub struct LocalFileSystem; + +#[async_trait] +impl ObjectStore for LocalFileSystem { + async fn list(&self, prefix: &str, _filters: &[Expr]) -> Result<FileMetaStream> { + list_all(prefix.to_owned()).await + } + + fn get_reader(&self, file: FileMeta) -> Result<Arc<dyn ObjectReader>> { + Ok(Arc::new(LocalFileReader::new(file)?)) + } +} + +struct LocalFileReader { + file: FileMeta, +} + +impl LocalFileReader { + fn new(file: FileMeta) -> Result<Self> { + Ok(Self { file }) + } +} + +#[async_trait] +impl ObjectReader for LocalFileReader { + async fn get_reader( + &self, + _start: u64, + _length: usize, + ) -> Result<Arc<dyn AsyncRead>> { + todo!() + } + + fn length(&self) -> u64 { + self.file.size + } +} + +async fn list_all(prefix: String) -> Result<FileMetaStream> { + fn get_meta(path: String, metadata: Metadata) -> FileMeta { + FileMeta { + path, + last_modified: metadata.modified().map(chrono::DateTime::from).ok(), + size: metadata.len(), + } + } + + async fn find_files_in_dir( + path: String, + to_visit: &mut Vec<String>, + ) -> Result<Vec<FileMeta>> { + let mut dir = tokio::fs::read_dir(path).await?; + let mut files = Vec::new(); + + while let Some(child) = dir.next_entry().await? { + if let Some(child_path) = child.path().to_str() { + let metadata = child.metadata().await?; + if metadata.is_dir() { + to_visit.push(child_path.to_string()); + } else { + files.push(get_meta(child_path.to_owned(), metadata)) + } + } else { + return Err(DataFusionError::Plan("Invalid path".to_string())); + } + } + Ok(files) + } + + let prefix_meta = tokio::fs::metadata(&prefix).await?; + let prefix = prefix.to_owned(); + if prefix_meta.is_file() { + Ok(Box::pin(stream::once(async move { + Ok(get_meta(prefix, prefix_meta)) + }))) + } else { + let result = stream::unfold(vec![prefix], move |mut to_visit| async move { + match to_visit.pop() { + None => None, + Some(path) => { + let file_stream = match find_files_in_dir(path, &mut to_visit).await { + Ok(files) => stream::iter(files).map(Ok).left_stream(), + Err(e) => stream::once(async { Err(e) }).right_stream(), + }; + + Some((file_stream, to_visit)) + } + } + }) + .flatten(); + Ok(Box::pin(result)) + } +} Review comment: At some point tests for the code in `local.rs` might be cool. ########## File path: datafusion/src/datasource/object_store/local.rs ########## @@ -0,0 +1,127 @@ +// 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. + +//! Object store that represents the Local File System. + +use std::fs::Metadata; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::{stream, AsyncRead, StreamExt}; + +use crate::datasource::object_store::{ + FileMeta, FileMetaStream, ObjectReader, ObjectStore, +}; +use crate::error::DataFusionError; +use crate::error::Result; +use crate::logical_plan::Expr; + +#[derive(Debug)] +/// Local File System as Object Store. +pub struct LocalFileSystem; + +#[async_trait] +impl ObjectStore for LocalFileSystem { + async fn list(&self, prefix: &str, _filters: &[Expr]) -> Result<FileMetaStream> { + list_all(prefix.to_owned()).await + } + + fn get_reader(&self, file: FileMeta) -> Result<Arc<dyn ObjectReader>> { + Ok(Arc::new(LocalFileReader::new(file)?)) + } +} + +struct LocalFileReader { + file: FileMeta, +} + +impl LocalFileReader { + fn new(file: FileMeta) -> Result<Self> { + Ok(Self { file }) + } +} + +#[async_trait] +impl ObjectReader for LocalFileReader { + async fn get_reader( Review comment: I don't understand this comment -- `ObjectStore::get_reader` is already `async` isn't it? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
