1use std::collections::HashMap;
8use std::path::PathBuf;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use async_trait::async_trait;
13use faucet_core::{FaucetError, Stream, StreamPage};
14use futures::{StreamExt, TryStreamExt, stream};
15use object_store::ObjectStore;
16use object_store::aws::AmazonS3Builder;
17use object_store::path::Path as ObjectPath;
18use parquet::arrow::ProjectionMask;
19use parquet::arrow::async_reader::{ParquetObjectReader, ParquetRecordBatchStreamBuilder};
20use serde_json::Value;
21
22use crate::config::{ParquetLocation, ParquetS3Config, ParquetSourceConfig};
23use crate::convert::record_batch_to_json;
24
25pub struct ParquetSource {
27 config: ParquetSourceConfig,
28 s3_store: Option<Arc<dyn ObjectStore>>,
31}
32
33impl ParquetSource {
34 pub async fn new(config: ParquetSourceConfig) -> Result<Self, FaucetError> {
40 if config.concurrency == 0 {
44 return Err(FaucetError::Config(
45 "parquet source: concurrency must be > 0".into(),
46 ));
47 }
48
49 let s3_store = match &config.source {
50 ParquetLocation::S3(s3) => Some(build_s3_store(s3)?),
51 _ => None,
52 };
53
54 Ok(Self { config, s3_store })
55 }
56
57 async fn resolve_files(
62 &self,
63 context: &HashMap<String, Value>,
64 ) -> Result<Vec<FileTarget>, FaucetError> {
65 match &self.config.source {
66 ParquetLocation::LocalPath { path } => {
67 let resolved = substitute(path, context);
68 Ok(vec![FileTarget::Local(PathBuf::from(resolved))])
69 }
70 ParquetLocation::Glob { pattern } => {
71 let resolved = substitute(pattern, context);
72 expand_glob(&resolved)
73 }
74 ParquetLocation::S3(s3) => self.resolve_s3_files(s3, context).await,
75 }
76 }
77
78 async fn resolve_s3_files(
79 &self,
80 s3: &ParquetS3Config,
81 context: &HashMap<String, Value>,
82 ) -> Result<Vec<FileTarget>, FaucetError> {
83 match (&s3.key, &s3.prefix) {
84 (Some(_), Some(_)) => Err(FaucetError::Config(
85 "parquet source: S3 config cannot set both `key` and `prefix`".into(),
86 )),
87 (None, None) => Err(FaucetError::Config(
88 "parquet source: S3 config requires one of `key` or `prefix`".into(),
89 )),
90 (Some(key), None) => {
91 let key = substitute(key, context);
92 Ok(vec![FileTarget::S3(ObjectPath::from(key))])
93 }
94 (None, Some(prefix)) => {
95 let prefix = substitute(prefix, context);
96 let store = self.s3_store.as_ref().ok_or_else(|| {
97 FaucetError::Source("parquet source: S3 store not initialised".into())
98 })?;
99 list_s3_prefix(store.as_ref(), &prefix).await
100 }
101 }
102 }
103
104 async fn read_file(&self, target: &FileTarget) -> Result<FileOutput, FaucetError> {
108 let display = target.display();
109 match target {
110 FileTarget::Local(path) => {
111 let file = tokio::fs::File::open(path).await.map_err(|e| {
112 FaucetError::Source(format!("failed to open parquet file '{display}': {e}"))
113 })?;
114 self.decode(file, &display).await
115 }
116 FileTarget::S3(path) => {
117 let store = self.s3_store.as_ref().ok_or_else(|| {
118 FaucetError::Source("parquet source: S3 store not initialised".into())
119 })?;
120 let reader = ParquetObjectReader::new(store.clone(), path.clone());
121 self.decode(reader, &display).await
122 }
123 }
124 }
125
126 async fn decode<R>(&self, reader: R, display: &str) -> Result<FileOutput, FaucetError>
127 where
128 R: parquet::arrow::async_reader::AsyncFileReader + Send + Unpin + 'static,
129 {
130 let (mut batches, arrow_schema) = self.build_batch_stream(reader, display).await?;
131
132 let mut rows: Vec<Value> = Vec::new();
133 while let Some(batch) = batches.next().await {
134 let batch = batch.map_err(|e| {
135 FaucetError::Source(format!("parquet decode error in '{display}': {e}"))
136 })?;
137 let batch_rows = record_batch_to_json(&batch)?;
138 rows.extend(batch_rows);
139 }
140
141 Ok(FileOutput {
142 path: display.to_string(),
143 rows,
144 arrow_schema,
145 })
146 }
147
148 async fn build_batch_stream<R>(
158 &self,
159 reader: R,
160 display: &str,
161 ) -> Result<(BatchStream, arrow::datatypes::SchemaRef), FaucetError>
162 where
163 R: parquet::arrow::async_reader::AsyncFileReader + Send + Unpin + 'static,
164 {
165 let mut builder = ParquetRecordBatchStreamBuilder::new(reader)
166 .await
167 .map_err(|e| {
168 FaucetError::Source(format!(
169 "failed to read parquet metadata for '{display}': {e}"
170 ))
171 })?;
172
173 if self.config.batch_size > 0 {
178 builder = builder.with_batch_size(self.config.batch_size);
179 }
180
181 if let Some(cols) = self.config.columns.as_deref() {
182 let parquet_schema = builder.parquet_schema();
183 validate_projection(cols, parquet_schema, display)?;
184 let mask = ProjectionMask::columns(parquet_schema, cols.iter().map(String::as_str));
185 builder = builder.with_projection(mask);
186 }
187
188 let arrow_schema = builder.schema().clone();
189
190 let stream = builder.build().map_err(|e| {
191 FaucetError::Source(format!(
192 "failed to build parquet stream for '{display}': {e}"
193 ))
194 })?;
195
196 Ok((Box::pin(stream), arrow_schema))
197 }
198
199 async fn open_target_stream(
203 &self,
204 target: &FileTarget,
205 ) -> Result<(BatchStream, arrow::datatypes::SchemaRef, String), FaucetError> {
206 let display = target.display();
207 match target {
208 FileTarget::Local(path) => {
209 let file = tokio::fs::File::open(path).await.map_err(|e| {
210 FaucetError::Source(format!("failed to open parquet file '{display}': {e}"))
211 })?;
212 let (stream, schema) = self.build_batch_stream(file, &display).await?;
213 Ok((stream, schema, display))
214 }
215 FileTarget::S3(path) => {
216 let store = self.s3_store.as_ref().ok_or_else(|| {
217 FaucetError::Source("parquet source: S3 store not initialised".into())
218 })?;
219 let reader = ParquetObjectReader::new(store.clone(), path.clone());
220 let (stream, schema) = self.build_batch_stream(reader, &display).await?;
221 Ok((stream, schema, display))
222 }
223 }
224 }
225}
226
227type BatchStream =
230 Pin<Box<dyn futures::Stream<Item = parquet::errors::Result<arrow::array::RecordBatch>> + Send>>;
231
232#[async_trait]
233impl faucet_core::Source for ParquetSource {
234 async fn fetch_with_context(
235 &self,
236 context: &HashMap<String, Value>,
237 ) -> Result<Vec<Value>, FaucetError> {
238 let targets = self.resolve_files(context).await?;
239
240 tracing::info!(files = targets.len(), "Parquet source resolved files");
241
242 if targets.is_empty() {
243 return Ok(Vec::new());
244 }
245
246 let concurrency = self.config.concurrency.max(1);
247
248 let outputs: Vec<FileOutput> = stream::iter(targets)
254 .map(|target| async move {
255 let out = self.read_file(&target).await?;
256 tracing::debug!(file = %out.path, rows = out.rows.len(), "Parquet file decoded");
257 Ok::<FileOutput, FaucetError>(out)
258 })
259 .buffered(concurrency)
260 .try_collect()
261 .await?;
262
263 if outputs.len() > 1 {
264 let first = &outputs[0];
265 for other in &outputs[1..] {
266 if first.arrow_schema != other.arrow_schema {
267 return Err(FaucetError::Source(schema_mismatch_message(first, other)));
268 }
269 }
270 }
271
272 let total: usize = outputs.iter().map(|o| o.rows.len()).sum();
273 let mut all = Vec::with_capacity(total);
274 for out in outputs {
275 all.extend(out.rows);
276 }
277
278 tracing::info!(total_records = all.len(), "Parquet source fetch complete");
279 Ok(all)
280 }
281
282 fn stream_pages<'a>(
309 &'a self,
310 context: &'a HashMap<String, Value>,
311 _batch_size: usize,
312 ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
313 Box::pin(async_stream::try_stream! {
314 let targets = self.resolve_files(context).await?;
315 tracing::info!(files = targets.len(), "Parquet source resolved files");
316
317 if targets.is_empty() {
318 return;
319 }
320
321 let mut reference: Option<(String, arrow::datatypes::SchemaRef)> = None;
330 for target in &targets {
331 let (_, arrow_schema, display) = self.open_target_stream(target).await?;
332 if let Some((first_path, first_schema)) = &reference {
333 if first_schema != &arrow_schema {
334 Err(FaucetError::Source(schema_mismatch_message_pair(
335 first_path,
336 first_schema,
337 &display,
338 &arrow_schema,
339 )))?;
340 }
341 } else {
342 reference = Some((display, arrow_schema));
343 }
344 }
345
346 let mut total_records = 0usize;
348 let mut total_pages = 0usize;
349 for target in &targets {
350 let (mut batches, _schema, display) = self.open_target_stream(target).await?;
351 while let Some(batch) = batches.next().await {
352 let batch = batch.map_err(|e| {
353 FaucetError::Source(format!(
354 "parquet decode error in '{display}': {e}"
355 ))
356 })?;
357 let rows = record_batch_to_json(&batch)?;
358 if rows.is_empty() {
359 continue;
360 }
361 total_records += rows.len();
362 total_pages += 1;
363 yield StreamPage { records: rows, bookmark: None };
364 }
365 }
366
367 tracing::info!(
368 pages = total_pages,
369 total_records,
370 batch_size = self.config.batch_size,
371 "Parquet source stream complete",
372 );
373 })
374 }
375
376 fn config_schema(&self) -> Value {
377 serde_json::to_value(faucet_core::schema_for!(ParquetSourceConfig))
378 .expect("schema serialization")
379 }
380
381 fn dataset_uri(&self) -> String {
382 use crate::config::ParquetLocation;
383 match &self.config.source {
384 ParquetLocation::LocalPath { path } => format!("file://{path}"),
385 ParquetLocation::Glob { pattern } => format!("file://{pattern}"),
386 ParquetLocation::S3(s3) => match (&s3.key, &s3.prefix) {
387 (Some(k), _) => format!("s3://{}/{}", s3.bucket, k),
388 (_, Some(p)) => format!("s3://{}/{}", s3.bucket, p),
389 _ => format!("s3://{}", s3.bucket),
390 },
391 }
392 }
393}
394
395struct FileOutput {
398 path: String,
399 rows: Vec<Value>,
400 arrow_schema: arrow::datatypes::SchemaRef,
401}
402
403#[derive(Debug, Clone)]
405enum FileTarget {
406 Local(PathBuf),
407 S3(ObjectPath),
408}
409
410impl FileTarget {
411 fn display(&self) -> String {
412 match self {
413 FileTarget::Local(p) => p.display().to_string(),
414 FileTarget::S3(p) => format!("s3://{p}"),
415 }
416 }
417}
418
419fn substitute(template: &str, context: &HashMap<String, Value>) -> String {
421 if context.is_empty() {
422 template.to_string()
423 } else {
424 faucet_core::util::substitute_context(template, context)
425 }
426}
427
428fn expand_glob(pattern: &str) -> Result<Vec<FileTarget>, FaucetError> {
430 let entries = glob::glob(pattern)
431 .map_err(|e| FaucetError::Config(format!("invalid glob '{pattern}': {e}")))?;
432
433 let mut paths = Vec::new();
434 for entry in entries {
435 let p = entry
436 .map_err(|e| FaucetError::Source(format!("glob entry error for '{pattern}': {e}")))?;
437 if p.is_file() {
438 paths.push(p);
439 }
440 }
441 paths.sort();
442 Ok(paths.into_iter().map(FileTarget::Local).collect())
443}
444
445async fn list_s3_prefix(
447 store: &dyn ObjectStore,
448 prefix: &str,
449) -> Result<Vec<FileTarget>, FaucetError> {
450 let prefix_path = if prefix.is_empty() {
451 None
452 } else {
453 Some(ObjectPath::from(prefix))
454 };
455
456 let mut listing = store.list(prefix_path.as_ref());
457 let mut keys = Vec::new();
458 while let Some(item) = listing.next().await {
459 let meta = item.map_err(|e| {
460 FaucetError::Source(format!("S3 list error for prefix '{prefix}': {e}"))
461 })?;
462 keys.push(meta.location);
463 }
464 keys.sort();
465 Ok(keys.into_iter().map(FileTarget::S3).collect())
466}
467
468fn build_s3_store(s3: &ParquetS3Config) -> Result<Arc<dyn ObjectStore>, FaucetError> {
470 if s3.bucket.trim().is_empty() {
471 return Err(FaucetError::Config(
472 "parquet source: S3 bucket must not be empty".into(),
473 ));
474 }
475
476 let mut builder = AmazonS3Builder::from_env().with_bucket_name(&s3.bucket);
477 if let Some(region) = &s3.region {
478 builder = builder.with_region(region);
479 }
480 if let Some(endpoint) = &s3.endpoint_url {
481 builder = builder.with_endpoint(endpoint);
482 if endpoint.starts_with("http://") {
483 builder = builder.with_allow_http(true);
484 }
485 }
486
487 let store = builder
488 .build()
489 .map_err(|e| FaucetError::Config(format!("failed to build S3 client: {e}")))?;
490 Ok(Arc::new(store))
491}
492
493fn validate_projection(
497 requested: &[String],
498 parquet_schema: &parquet::schema::types::SchemaDescriptor,
499 display: &str,
500) -> Result<(), FaucetError> {
501 let root = parquet_schema.root_schema();
502 let parquet::schema::types::Type::GroupType { fields, .. } = root else {
503 return Err(FaucetError::Source(format!(
504 "parquet root schema for '{display}' is not a group"
505 )));
506 };
507
508 let known: std::collections::HashSet<&str> = fields.iter().map(|f| f.name()).collect();
509
510 for name in requested {
511 if !known.contains(name.as_str()) {
512 return Err(FaucetError::Source(format!(
513 "parquet source: projected column '{name}' not found in file '{display}' \
514 (available: {})",
515 known.iter().copied().collect::<Vec<_>>().join(", ")
516 )));
517 }
518 }
519
520 Ok(())
521}
522
523fn schema_mismatch_message(first: &FileOutput, other: &FileOutput) -> String {
525 schema_mismatch_message_pair(
526 &first.path,
527 &first.arrow_schema,
528 &other.path,
529 &other.arrow_schema,
530 )
531}
532
533fn schema_mismatch_message_pair(
537 first_path: &str,
538 first_schema: &arrow::datatypes::SchemaRef,
539 other_path: &str,
540 other_schema: &arrow::datatypes::SchemaRef,
541) -> String {
542 let first_fields: Vec<String> = first_schema
543 .fields()
544 .iter()
545 .map(|f| format!("{}:{}", f.name(), f.data_type()))
546 .collect();
547 let other_fields: Vec<String> = other_schema
548 .fields()
549 .iter()
550 .map(|f| format!("{}:{}", f.name(), f.data_type()))
551 .collect();
552
553 let max_len = first_fields.len().max(other_fields.len());
555 let mut first_diff = None;
556 for i in 0..max_len {
557 let a = first_fields
558 .get(i)
559 .map(String::as_str)
560 .unwrap_or("<missing>");
561 let b = other_fields
562 .get(i)
563 .map(String::as_str)
564 .unwrap_or("<missing>");
565 if a != b {
566 first_diff = Some((i, a.to_string(), b.to_string()));
567 break;
568 }
569 }
570
571 let detail = match first_diff {
572 Some((i, a, b)) => format!(" (field #{i}: '{a}' vs '{b}')"),
573 None => String::new(),
574 };
575
576 format!("parquet source: schema mismatch between '{first_path}' and '{other_path}'{detail}")
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582 use crate::config::ParquetSourceConfig;
583 use faucet_core::Source;
584
585 #[test]
586 fn substitute_passes_through_when_context_empty() {
587 let ctx = HashMap::new();
588 assert_eq!(substitute("/tmp/{x}.parquet", &ctx), "/tmp/{x}.parquet");
589 }
590
591 #[test]
592 fn substitute_replaces_placeholders() {
593 let mut ctx = HashMap::new();
594 ctx.insert("region".to_string(), Value::String("us".into()));
595 assert_eq!(
596 substitute("data/{region}/x.parquet", &ctx),
597 "data/us/x.parquet"
598 );
599 }
600
601 #[tokio::test]
602 async fn accepts_zero_batch_size_as_sentinel() {
603 let cfg = ParquetSourceConfig::local("/tmp/x.parquet").batch_size(0);
607 let source = ParquetSource::new(cfg)
608 .await
609 .expect("batch_size=0 must be accepted as the no-batching sentinel");
610 assert_eq!(source.config.batch_size, 0);
611 }
612
613 #[tokio::test]
614 async fn rejects_zero_concurrency() {
615 let cfg = ParquetSourceConfig::local("/tmp/x.parquet").concurrency(0);
616 match ParquetSource::new(cfg).await {
617 Err(FaucetError::Config(msg)) => assert!(msg.contains("concurrency")),
618 other => panic!("expected Config error, got {:?}", other.err()),
619 }
620 }
621
622 #[tokio::test]
623 async fn rejects_s3_with_both_key_and_prefix() {
624 let mut s3 = ParquetS3Config::object("b", "k.parquet");
625 s3.prefix = Some("p/".into());
626 let cfg = ParquetSourceConfig::s3(s3);
627 let source = ParquetSource::new(cfg).await.unwrap();
628 let err = source.resolve_files(&HashMap::new()).await.unwrap_err();
629 assert!(matches!(err, FaucetError::Config(_)));
630 }
631
632 #[tokio::test]
633 async fn rejects_s3_with_neither_key_nor_prefix() {
634 let s3 = ParquetS3Config {
635 bucket: "b".into(),
636 key: None,
637 prefix: None,
638 region: None,
639 endpoint_url: None,
640 };
641 let cfg = ParquetSourceConfig::s3(s3);
642 let source = ParquetSource::new(cfg).await.unwrap();
643 let err = source.resolve_files(&HashMap::new()).await.unwrap_err();
644 assert!(matches!(err, FaucetError::Config(_)));
645 }
646
647 #[test]
648 fn empty_bucket_rejected() {
649 let s3 = ParquetS3Config::object("", "k.parquet");
650 let err = build_s3_store(&s3).unwrap_err();
651 assert!(matches!(err, FaucetError::Config(_)));
652 }
653
654 #[tokio::test]
655 async fn dataset_uri_local_path() {
656 let cfg = ParquetSourceConfig::local("/tmp/data.parquet");
657 let source = ParquetSource::new(cfg).await.unwrap();
658 assert_eq!(source.dataset_uri(), "file:///tmp/data.parquet");
659 }
660
661 #[tokio::test]
662 async fn dataset_uri_glob() {
663 let cfg = ParquetSourceConfig::glob("/tmp/data/*.parquet");
664 let source = ParquetSource::new(cfg).await.unwrap();
665 assert_eq!(source.dataset_uri(), "file:///tmp/data/*.parquet");
666 }
667
668 #[tokio::test]
669 async fn dataset_uri_s3_with_key() {
670 let s3 = ParquetS3Config::object("my-bucket", "path/to/file.parquet");
671 let cfg = ParquetSourceConfig::s3(s3);
672 let source = ParquetSource::new(cfg).await.unwrap();
673 assert_eq!(source.dataset_uri(), "s3://my-bucket/path/to/file.parquet");
674 }
675}