Skip to main content

mz_storage_operators/
oneshot_source.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! "Oneshot" sources are a one-time ingestion of data from an external system, unlike traditional
11//! sources, they __do not__ run continuously. Oneshot sources are generally used for `COPY FROM`
12//! SQL statements.
13//!
14//! The implementation of reading and parsing data is behind the [`OneshotSource`] and
15//! [`OneshotFormat`] traits, respectively. Users looking to add new sources or formats, should
16//! only need to add new implementations for these traits.
17//!
18//! * [`OneshotSource`] is an interface for listing and reading from an external system, e.g. an
19//!   HTTP server.
20//! * [`OneshotFormat`] is an interface for how to parallelize and parse data, e.g. CSV.
21//!
22//! Given a [`OneshotSource`] and a [`OneshotFormat`] we build a dataflow structured like the
23//! following:
24//!
25//! ```text
26//!             ┏━━━━━━━━━━━━━━━┓
27//!             ┃    Discover   ┃
28//!             ┃    objects    ┃
29//!             ┗━━━━━━━┯━━━━━━━┛
30//!           ┌───< Distribute >───┐
31//!           │                    │
32//!     ┏━━━━━v━━━━┓         ┏━━━━━v━━━━┓
33//!     ┃  Split   ┃   ...   ┃  Split   ┃
34//!     ┃  Work 1  ┃         ┃  Work n  ┃
35//!     ┗━━━━━┯━━━━┛         ┗━━━━━┯━━━━┛
36//!           │                    │
37//!           ├───< Distribute >───┤
38//!           │                    │
39//!     ┏━━━━━v━━━━┓         ┏━━━━━v━━━━┓
40//!     ┃  Fetch   ┃   ...   ┃  Fetch   ┃
41//!     ┃  Work 1  ┃         ┃  Work n  ┃
42//!     ┗━━━━━┯━━━━┛         ┗━━━━━┯━━━━┛
43//!           │                    │
44//!           ├───< Distribute >───┤
45//!           │                    │
46//!     ┏━━━━━v━━━━┓         ┏━━━━━v━━━━┓
47//!     ┃  Decode  ┃   ...   ┃  Decode  ┃
48//!     ┃  Chunk 1 ┃         ┃  Chunk n ┃
49//!     ┗━━━━━┯━━━━┛         ┗━━━━━┯━━━━┛
50//!           │                    │
51//!           │                    │
52//!     ┏━━━━━v━━━━┓         ┏━━━━━v━━━━┓
53//!     ┃  Stage   ┃   ...   ┃  Stage   ┃
54//!     ┃  Batch 1 ┃         ┃  Batch n ┃
55//!     ┗━━━━━┯━━━━┛         ┗━━━━━┯━━━━┛
56//!           │                    │
57//!           └─────────┬──────────┘
58//!               ┏━━━━━v━━━━┓
59//!               ┃  Result  ┃
60//!               ┃ Callback ┃
61//!               ┗━━━━━━━━━━┛
62//! ```
63//!
64
65use std::fmt;
66use std::sync::Arc;
67
68use aws_sdk_s3::error::DisplayErrorContext;
69use bytes::Bytes;
70use differential_dataflow::Hashable;
71use futures::stream::BoxStream;
72use futures::{StreamExt, TryStreamExt};
73use mz_expr::SafeMfpPlan;
74use mz_ore::cast::CastFrom;
75use mz_ore::error::ErrorExt;
76use mz_persist_client::Diagnostics;
77use mz_persist_client::batch::ProtoBatch;
78use mz_persist_client::cache::PersistClientCache;
79use mz_persist_types::Codec;
80use mz_persist_types::codec_impls::UnitSchema;
81use mz_repr::{DatumVec, GlobalId, Row, RowArena, Timestamp};
82use mz_storage_types::StorageDiff;
83use mz_storage_types::connections::ConnectionContext;
84use mz_storage_types::controller::CollectionMetadata;
85use mz_storage_types::oneshot_sources::{
86    ContentFilter, ContentFormat, ContentSource, OneshotIngestionRequest,
87};
88use mz_storage_types::sources::SourceData;
89use mz_timely_util::builder_async::{
90    Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
91};
92use mz_timely_util::pact::Distribute;
93use serde::de::DeserializeOwned;
94use serde::{Deserialize, Serialize};
95use std::collections::{BTreeSet, LinkedList};
96use std::fmt::{Debug, Display};
97use std::future::Future;
98use timely::container::CapacityContainerBuilder;
99use timely::dataflow::channels::pact::Pipeline;
100use timely::dataflow::{Scope, StreamVec};
101use timely::progress::Antichain;
102use tracing::info;
103
104use crate::oneshot_source::aws_source::{AwsS3Source, S3Checksum, S3Object};
105use crate::oneshot_source::csv::{CsvDecoder, CsvRecord, CsvWorkRequest};
106use crate::oneshot_source::http_source::{
107    HttpChecksum, HttpObject, HttpOneshotSource, build_http_client,
108};
109use crate::oneshot_source::parquet::{ParquetFormat, ParquetRowGroup, ParquetWorkRequest};
110
111pub mod csv;
112pub mod parquet;
113
114pub mod aws_source;
115pub mod http_source;
116
117mod util;
118
119/// Render a dataflow to do a "oneshot" ingestion.
120///
121/// Roughly the operators we render do the following:
122///
123/// 1. Discover objects with a [`OneshotSource`].
124/// 2. Split objects into separate units of work based on the [`OneshotFormat`].
125/// 3. Fetch individual units of work (aka fetch byte blobs) with the
126///    [`OneshotFormat`] and [`OneshotSource`].
127/// 4. Decode the fetched byte blobs into [`Row`]s.
128/// 5. Stage the [`Row`]s into Persist returning [`ProtoBatch`]es.
129///
130/// TODO(cf3): Benchmark combining operators 3, 4, and 5. Currently we keep them
131/// separate for the [`CsvDecoder`]. CSV decoding is hard to do in parallel so we
132/// currently have a single worker Fetch an entire file, and then distributes
133/// chunks for parallel Decoding. We should benchmark if this is actually faster
134/// than just a single worker both fetching and decoding.
135///
136pub fn render<'scope, F>(
137    scope: Scope<'scope, Timestamp>,
138    persist_clients: Arc<PersistClientCache>,
139    connection_context: ConnectionContext,
140    collection_id: GlobalId,
141    collection_meta: CollectionMetadata,
142    request: OneshotIngestionRequest,
143    enforce_external_addresses: bool,
144    worker_callback: F,
145) -> Vec<PressOnDropButton>
146where
147    F: FnOnce(Result<Option<ProtoBatch>, String>) -> () + 'static,
148{
149    let OneshotIngestionRequest {
150        source,
151        format,
152        filter,
153        shape,
154    } = request;
155
156    let source = match source {
157        ContentSource::Http { url } => {
158            let client = match build_http_client(enforce_external_addresses) {
159                Ok(client) => client,
160                Err(err) => {
161                    worker_callback(Err(format!(
162                        "failed to build HTTP client for COPY FROM: {err}"
163                    )));
164                    return Vec::new();
165                }
166            };
167            let source = HttpOneshotSource::new(client, url);
168            SourceKind::Http(source)
169        }
170        ContentSource::AwsS3 {
171            connection,
172            connection_id,
173            uri,
174        } => {
175            // Checksum validation does not work with GCS when using ranges, which happens with parquet.
176            // So, we disable checksum if both the endpoint is overridden to a non-AWS endpoint and the format is Parquet.
177            let use_checksum = !(connection.endpoint.is_some()
178                && !connection.endpoint.as_ref().unwrap().contains("amazonaws"))
179                || format != ContentFormat::Parquet;
180            if !use_checksum {
181                tracing::info!(
182                    "disabling checksum validation for S3 source because endpoint: {:?} is overridden and format is Parquet",
183                    connection.endpoint
184                );
185            }
186            let source = AwsS3Source::new(
187                connection,
188                connection_id,
189                connection_context,
190                uri,
191                use_checksum,
192                enforce_external_addresses,
193            );
194            SourceKind::AwsS3(source)
195        }
196    };
197    tracing::info!(?source, "created oneshot source");
198
199    let format = match format {
200        ContentFormat::Csv(params) => {
201            let format = CsvDecoder::new(params, &shape.source_desc);
202            FormatKind::Csv(format)
203        }
204        ContentFormat::Parquet => {
205            let format = ParquetFormat::new(shape.source_desc);
206            FormatKind::Parquet(format)
207        }
208    };
209
210    // Discover what objects are available to copy.
211    let (objects_stream, discover_token) =
212        render_discover_objects(scope.clone(), collection_id, source.clone(), filter);
213    // Split the objects into individual units of work.
214    let (work_stream, split_token) = render_split_work(
215        scope.clone(),
216        collection_id,
217        objects_stream,
218        source.clone(),
219        format.clone(),
220    );
221    // Fetch each unit of work, returning chunks of records.
222    let (records_stream, fetch_token) = render_fetch_work(
223        scope.clone(),
224        collection_id,
225        source.clone(),
226        format.clone(),
227        work_stream,
228    );
229    // Parse chunks of records into Rows.
230    let (rows_stream, decode_token) = render_decode_chunk(
231        scope.clone(),
232        format.clone(),
233        records_stream,
234        shape.source_mfp,
235    );
236    // Stage the Rows in Persist.
237    let (batch_stream, batch_token) = render_stage_batches_operator(
238        scope.clone(),
239        collection_id,
240        &collection_meta,
241        persist_clients,
242        rows_stream,
243    );
244
245    // Collect all results together and notify the upstream of whether or not we succeeded.
246    render_completion_operator(scope, batch_stream, worker_callback);
247
248    let tokens = vec![
249        discover_token,
250        split_token,
251        fetch_token,
252        decode_token,
253        batch_token,
254    ];
255
256    tokens
257}
258
259/// Render an operator that using a [`OneshotSource`] will discover what objects are available
260/// for fetching.
261pub fn render_discover_objects<'scope, S>(
262    scope: Scope<'scope, Timestamp>,
263    collection_id: GlobalId,
264    source: S,
265    filter: ContentFilter,
266) -> (
267    StreamVec<'scope, Timestamp, Result<(S::Object, S::Checksum), StorageErrorX>>,
268    PressOnDropButton,
269)
270where
271    S: OneshotSource + 'static,
272{
273    // Only a single worker is responsible for discovering objects.
274    let worker_id = scope.index();
275    let num_workers = scope.peers();
276    let active_worker_id = usize::cast_from((collection_id, "discover").hashed()) % num_workers;
277    let is_active_worker = worker_id == active_worker_id;
278
279    let mut builder = AsyncOperatorBuilder::new("CopyFrom-discover".to_string(), scope.clone());
280
281    let (start_handle, start_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
282
283    let shutdown = builder.build(move |caps| async move {
284        let [start_cap] = caps.try_into().unwrap();
285
286        if !is_active_worker {
287            return;
288        }
289
290        let filter = match ObjectFilter::try_new(filter) {
291            Ok(filter) => filter,
292            Err(err) => {
293                tracing::warn!(?err, "failed to create filter");
294                start_handle.give(&start_cap, Err(StorageErrorXKind::generic(err).into()));
295                return;
296            }
297        };
298
299        let work = source.list().await.context("list");
300        match work {
301            Ok(objects) => {
302                let (include, exclude): (Vec<_>, Vec<_>) = objects
303                    .into_iter()
304                    .partition(|(o, _checksum)| filter.filter::<S>(o));
305                tracing::info!(
306                    %worker_id,
307                    include_count = include.len(),
308                    exclude_count = exclude.len(),
309                    "listed objects"
310                );
311                tracing::trace!(%worker_id, ?include, ?exclude, "listed objects");
312                if include.is_empty() {
313                    let err = StorageErrorXKind::NoMatchingFiles.with_context("discover");
314                    start_handle.give(&start_cap, Err(err));
315                    return;
316                }
317                include
318                    .into_iter()
319                    .for_each(|object| start_handle.give(&start_cap, Ok(object)))
320            }
321            Err(err) => {
322                tracing::warn!(?err, "failed to list oneshot source");
323                start_handle.give(&start_cap, Err(err))
324            }
325        }
326    });
327
328    (start_stream, shutdown.press_on_drop())
329}
330
331/// Render an operator that given a stream of [`OneshotSource::Object`]s will split them into units
332/// of work based on the provided [`OneshotFormat`].
333pub fn render_split_work<'scope, T, S, F>(
334    scope: Scope<'scope, T>,
335    collection_id: GlobalId,
336    objects: StreamVec<'scope, T, Result<(S::Object, S::Checksum), StorageErrorX>>,
337    source: S,
338    format: F,
339) -> (
340    StreamVec<'scope, T, Result<F::WorkRequest<S>, StorageErrorX>>,
341    PressOnDropButton,
342)
343where
344    T: timely::progress::Timestamp,
345    S: OneshotSource + Send + Sync + 'static,
346    F: OneshotFormat + Send + Sync + 'static,
347{
348    let worker_id = scope.index();
349    let mut builder = AsyncOperatorBuilder::new("CopyFrom-split_work".to_string(), scope.clone());
350
351    let (request_handle, request_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
352    let mut objects_handle = builder.new_input_for(objects, Distribute, &request_handle);
353
354    let shutdown = builder.build(move |caps| async move {
355        let [_objects_cap] = caps.try_into().unwrap();
356
357        info!(%collection_id, %worker_id, "CopyFrom Split Work");
358
359        while let Some(event) = objects_handle.next().await {
360            let (capability, maybe_objects) = match event {
361                AsyncEvent::Data(cap, req) => (cap, req),
362                AsyncEvent::Progress(_) => continue,
363            };
364
365            // Nest the `split_work(...)` method in an async-block so we can use the `?`
366            // without returning from the entire operator, and so we can add context.
367            let result = async {
368                let mut requests = Vec::new();
369
370                for maybe_object in maybe_objects {
371                    // Return early if the upstream Discover step failed.
372                    let (object, checksum) = maybe_object?;
373
374                    let format_ = format.clone();
375                    let source_ = source.clone();
376                    let work_requests = mz_ore::task::spawn(|| "split-work", async move {
377                        info!(%worker_id, object = %object.name(), "splitting object");
378                        format_.split_work(source_.clone(), object, checksum).await
379                    })
380                    .await?;
381
382                    requests.extend(work_requests);
383                }
384
385                Ok::<_, StorageErrorX>(requests)
386            }
387            .await
388            .context("split");
389
390            match result {
391                Ok(requests) => requests
392                    .into_iter()
393                    .for_each(|req| request_handle.give(&capability, Ok(req))),
394                Err(err) => request_handle.give(&capability, Err(err)),
395            }
396        }
397    });
398
399    (request_stream, shutdown.press_on_drop())
400}
401
402/// Render an operator that given a stream [`OneshotFormat::WorkRequest`]s will fetch chunks of the
403/// remote [`OneshotSource::Object`] and return a stream of [`OneshotFormat::RecordChunk`]s that
404/// can be decoded into [`Row`]s.
405pub fn render_fetch_work<'scope, T, S, F>(
406    scope: Scope<'scope, T>,
407    collection_id: GlobalId,
408    source: S,
409    format: F,
410    work_requests: StreamVec<'scope, T, Result<F::WorkRequest<S>, StorageErrorX>>,
411) -> (
412    StreamVec<'scope, T, Result<F::RecordChunk, StorageErrorX>>,
413    PressOnDropButton,
414)
415where
416    T: timely::progress::Timestamp,
417    S: OneshotSource + Sync + 'static,
418    F: OneshotFormat + Sync + 'static,
419{
420    let worker_id = scope.index();
421    let mut builder = AsyncOperatorBuilder::new("CopyFrom-fetch_work".to_string(), scope.clone());
422
423    let (record_handle, record_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
424    let mut work_requests_handle = builder.new_input_for(work_requests, Distribute, &record_handle);
425
426    let shutdown = builder.build(move |caps| async move {
427        let [_work_cap] = caps.try_into().unwrap();
428
429        info!(%collection_id, %worker_id, "CopyFrom Fetch Work");
430
431        while let Some(event) = work_requests_handle.next().await {
432            let (capability, maybe_requests) = match event {
433                AsyncEvent::Data(cap, req) => (cap, req),
434                AsyncEvent::Progress(_) => continue,
435            };
436
437            // Wrap our work in a block to capture `?`.
438            let result = async {
439                // Process each stream of work, one at a time.
440                for maybe_request in maybe_requests {
441                    let request = maybe_request?;
442
443                    let mut work_stream = format.fetch_work(&source, request);
444                    while let Some(result) = work_stream.next().await {
445                        // Returns early and stop consuming from the stream if we hit an error.
446                        let record_chunk = result.context("fetch worker")?;
447
448                        // Note: We want to give record chunks as we receive them, because a work
449                        // request may be for an entire file.
450                        //
451                        // TODO(cf3): Investigate if some small batching here would help perf.
452                        record_handle.give(&capability, Ok(record_chunk));
453                    }
454                }
455
456                Ok::<_, StorageErrorX>(())
457            }
458            .await
459            .context("fetch work");
460
461            if let Err(err) = result {
462                tracing::warn!(?err, "failed to fetch");
463                record_handle.give(&capability, Err(err))
464            }
465        }
466    });
467
468    (record_stream, shutdown.press_on_drop())
469}
470
471/// Render an operator that given a stream of [`OneshotFormat::RecordChunk`]s will decode these
472/// chunks into a stream of [`Row`]s.
473pub fn render_decode_chunk<'scope, T, F>(
474    scope: Scope<'scope, T>,
475    format: F,
476    record_chunks: StreamVec<'scope, T, Result<F::RecordChunk, StorageErrorX>>,
477    mfp: SafeMfpPlan,
478) -> (
479    StreamVec<'scope, T, Result<Row, StorageErrorX>>,
480    PressOnDropButton,
481)
482where
483    T: timely::progress::Timestamp,
484    F: OneshotFormat + 'static,
485{
486    let mut builder = AsyncOperatorBuilder::new("CopyFrom-decode_chunk".to_string(), scope.clone());
487
488    let (row_handle, row_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
489    let mut record_chunk_handle = builder.new_input_for(record_chunks, Distribute, &row_handle);
490
491    let shutdown = builder.build(move |caps| async move {
492        let [_row_cap] = caps.try_into().unwrap();
493
494        let mut datum_vec = DatumVec::default();
495        let mut row_buf = Row::default();
496
497        while let Some(event) = record_chunk_handle.next().await {
498            let (capability, maybe_chunks) = match event {
499                AsyncEvent::Data(cap, data) => (cap, data),
500                AsyncEvent::Progress(_) => continue,
501            };
502
503            let result = async {
504                let mut rows = Vec::new();
505                for maybe_chunk in maybe_chunks {
506                    let chunk = maybe_chunk?;
507                    format.decode_chunk(chunk, &mut rows)?;
508                }
509                Ok::<_, StorageErrorX>(rows)
510            }
511            .await
512            .context("decode chunk");
513
514            match result {
515                Ok(rows) => {
516                    // Scoped to this chunk so the arena's retained capacity does not outlive it,
517                    // and cleared per row below so it only ever holds one row's MFP temporaries
518                    // rather than accumulating the whole source.
519                    let mut row_arena = RowArena::new();
520                    // For each row of source data, we pass it through an MFP to re-arrange column
521                    // orders and/or fill in default values for missing columns.
522                    for row in rows {
523                        row_arena.clear();
524                        let mut datums = datum_vec.borrow_with(&row);
525                        let result = mfp
526                            .evaluate_into(&mut *datums, &row_arena, &mut row_buf)
527                            .map(|row| row.cloned());
528
529                        match result {
530                            Ok(Some(row)) => row_handle.give(&capability, Ok(row)),
531                            Ok(None) => {
532                                // We only expect the provided MFP to map rows from the source data
533                                // and project default values.
534                                mz_ore::soft_panic_or_log!("oneshot source MFP filtered out data!");
535                            }
536                            Err(e) => {
537                                let err = StorageErrorXKind::MfpEvalError(e.to_string().into())
538                                    .with_context("decode");
539                                row_handle.give(&capability, Err(err))
540                            }
541                        }
542                    }
543                }
544                Err(err) => row_handle.give(&capability, Err(err)),
545            }
546        }
547    });
548
549    (row_stream, shutdown.press_on_drop())
550}
551
552/// Render an operator that given a stream of [`Row`]s will stage them in Persist and return a
553/// stream of [`ProtoBatch`]es that can later be linked into a shard.
554pub fn render_stage_batches_operator<'scope, T>(
555    scope: Scope<'scope, T>,
556    collection_id: GlobalId,
557    collection_meta: &CollectionMetadata,
558    persist_clients: Arc<PersistClientCache>,
559    rows_stream: StreamVec<'scope, T, Result<Row, StorageErrorX>>,
560) -> (
561    StreamVec<'scope, T, Result<ProtoBatch, StorageErrorX>>,
562    PressOnDropButton,
563)
564where
565    T: timely::progress::Timestamp,
566{
567    let persist_location = collection_meta.persist_location.clone();
568    let shard_id = collection_meta.data_shard;
569    let collection_desc = Arc::new(collection_meta.relation_desc.clone());
570
571    let mut builder =
572        AsyncOperatorBuilder::new("CopyFrom-stage_batches".to_string(), scope.clone());
573
574    let (proto_batch_handle, proto_batch_stream) =
575        builder.new_output::<CapacityContainerBuilder<_>>();
576    let mut rows_handle = builder.new_input_for(rows_stream, Pipeline, &proto_batch_handle);
577
578    let shutdown = builder.build(move |caps| async move {
579        let [proto_batch_cap] = caps.try_into().unwrap();
580
581        // Open a Persist handle that we can use to stage a batch.
582        let persist_client = persist_clients
583            .open(persist_location)
584            .await
585            .expect("failed to open Persist client");
586        let persist_diagnostics = Diagnostics {
587            shard_name: collection_id.to_string(),
588            handle_purpose: "CopyFrom::stage_batches".to_string(),
589        };
590        let write_handle = persist_client
591            .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
592                shard_id,
593                Arc::clone(&collection_desc),
594                Arc::new(UnitSchema),
595                persist_diagnostics,
596            )
597            .await
598            .expect("could not open Persist shard");
599
600        // Create a batch using the minimum timestamp since these batches will
601        // get sent back to `environmentd` and their timestamps re-written
602        // before being finally appended.
603        let lower = mz_repr::Timestamp::MIN;
604        let upper = Antichain::from_elem(lower.step_forward());
605
606        let mut batch_builder = write_handle.rewritable_builder(Antichain::from_elem(lower));
607
608        while let Some(event) = rows_handle.next().await {
609            let AsyncEvent::Data(_, row_batch) = event else {
610                continue;
611            };
612
613            // Pull Rows off our stream and stage them into a Batch.
614            for maybe_row in row_batch {
615                let maybe_row = maybe_row.and_then(|row| {
616                    Row::validate(&row, &*collection_desc).map_err(|e| {
617                        StorageErrorXKind::invalid_record_batch(e).with_context("stage_batches")
618                    })?;
619                    Ok(row)
620                });
621                match maybe_row {
622                    // Happy path, add the Row to our batch!
623                    Ok(row) => {
624                        let data = SourceData(Ok(row));
625                        batch_builder
626                            .add(&data, &(), &lower, &1)
627                            .await
628                            .expect("failed to add Row to batch");
629                    }
630                    // Sad path, something upstream hit an error.
631                    Err(err) => {
632                        // Clean up our in-progress batch so we don't leak data.
633                        let batch = batch_builder
634                            .finish(upper)
635                            .await
636                            .expect("failed to cleanup batch");
637                        batch.delete().await;
638
639                        // Pass on the error.
640                        proto_batch_handle
641                            .give(&proto_batch_cap, Err(err).context("stage batches"));
642                        return;
643                    }
644                }
645            }
646        }
647
648        let batch = batch_builder
649            .finish(upper)
650            .await
651            .expect("failed to create Batch");
652
653        // Turn our Batch into a ProtoBatch that will later be linked in to
654        // the shard.
655        //
656        // Note: By turning this into a ProtoBatch, the onus is now on us to
657        // cleanup the Batch if it's never linked into the shard.
658        //
659        // TODO(cf2): Make sure these batches get cleaned up if another
660        // worker encounters an error.
661        let proto_batch = batch.into_transmittable_batch();
662        proto_batch_handle.give(&proto_batch_cap, Ok(proto_batch));
663    });
664
665    (proto_batch_stream, shutdown.press_on_drop())
666}
667
668/// Render an operator that given a stream of [`ProtoBatch`]es will call our `worker_callback` to
669/// report the results upstream.
670pub fn render_completion_operator<'scope, T, F>(
671    scope: Scope<'scope, T>,
672    results_stream: StreamVec<'scope, T, Result<ProtoBatch, StorageErrorX>>,
673    worker_callback: F,
674) where
675    T: timely::progress::Timestamp,
676    F: FnOnce(Result<Option<ProtoBatch>, String>) -> () + 'static,
677{
678    let mut builder = AsyncOperatorBuilder::new("CopyFrom-completion".to_string(), scope.clone());
679    let mut results_input = builder.new_disconnected_input(results_stream, Pipeline);
680
681    builder.build(move |_| async move {
682        let result = async move {
683            let mut maybe_payload: Option<ProtoBatch> = None;
684
685            while let Some(event) = results_input.next().await {
686                if let AsyncEvent::Data(_cap, results) = event {
687                    let [result] = results
688                        .try_into()
689                        .expect("only 1 event on the result stream");
690
691                    // TODO(cf2): Lift this restriction.
692                    if maybe_payload.is_some() {
693                        panic!("expected only one batch!");
694                    }
695
696                    maybe_payload = Some(result.map_err(|e| e.to_string())?);
697                }
698            }
699
700            Ok(maybe_payload)
701        }
702        .await;
703
704        // Report to the caller of our final status.
705        worker_callback(result);
706    });
707}
708
709/// An object that will be fetched from a [`OneshotSource`].
710pub trait OneshotObject {
711    /// Name of the object, including any extensions.
712    fn name(&self) -> &str;
713
714    /// Path of the object within the remote source.
715    fn path(&self) -> &str;
716
717    /// Size of this object in bytes.
718    fn size(&self) -> usize;
719
720    /// Encodings of the _entire_ object, if any.
721    ///
722    /// Note: The object may internally use compression, e.g. a Parquet file
723    /// could compress its column chunks, but if the Parquet file itself is not
724    /// compressed then this would return `None`.
725    fn encodings(&self) -> &[Encoding];
726}
727
728/// Encoding of a [`OneshotObject`].
729#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
730pub enum Encoding {
731    Bzip2,
732    Gzip,
733    Xz,
734    Zstd,
735}
736
737/// Defines a remote system that we can fetch data from for a "one time" ingestion.
738pub trait OneshotSource: Clone + Send + Unpin {
739    /// An individual unit within the source, e.g. a file.
740    type Object: OneshotObject
741        + Debug
742        + Clone
743        + Send
744        + Unpin
745        + Serialize
746        + DeserializeOwned
747        + 'static;
748    /// Checksum for a [`Self::Object`].
749    type Checksum: Debug + Clone + Send + Unpin + Serialize + DeserializeOwned + 'static;
750
751    /// Returns all of the objects for this source.
752    fn list<'a>(
753        &'a self,
754    ) -> impl Future<Output = Result<Vec<(Self::Object, Self::Checksum)>, StorageErrorX>> + Send;
755
756    /// Resturns a stream of the data for a specific object.
757    fn get<'s>(
758        &'s self,
759        object: Self::Object,
760        checksum: Self::Checksum,
761        range: Option<std::ops::RangeInclusive<usize>>,
762    ) -> BoxStream<'s, Result<Bytes, StorageErrorX>>;
763}
764
765/// An enum wrapper around [`OneshotSource`]s.
766///
767/// An alternative to this wrapper would be to use `Box<dyn OneshotSource>`, but that requires
768/// making the trait object safe and it's easier to just wrap it in an enum. Also, this wrapper
769/// provides a convenient place to add [`StorageErrorXContext::context`] for all of our source
770/// types.
771#[derive(Clone, Debug)]
772pub(crate) enum SourceKind {
773    Http(HttpOneshotSource),
774    AwsS3(AwsS3Source),
775}
776
777impl OneshotSource for SourceKind {
778    type Object = ObjectKind;
779    type Checksum = ChecksumKind;
780
781    async fn list<'a>(&'a self) -> Result<Vec<(Self::Object, Self::Checksum)>, StorageErrorX> {
782        match self {
783            SourceKind::Http(http) => {
784                let objects = http.list().await.context("http")?;
785                let objects = objects
786                    .into_iter()
787                    .map(|(object, checksum)| {
788                        (ObjectKind::Http(object), ChecksumKind::Http(checksum))
789                    })
790                    .collect();
791                Ok(objects)
792            }
793            SourceKind::AwsS3(s3) => {
794                let objects = s3.list().await.context("s3")?;
795                let objects = objects
796                    .into_iter()
797                    .map(|(object, checksum)| {
798                        (ObjectKind::AwsS3(object), ChecksumKind::AwsS3(checksum))
799                    })
800                    .collect();
801                Ok(objects)
802            }
803        }
804    }
805
806    fn get<'s>(
807        &'s self,
808        object: Self::Object,
809        checksum: Self::Checksum,
810        range: Option<std::ops::RangeInclusive<usize>>,
811    ) -> BoxStream<'s, Result<Bytes, StorageErrorX>> {
812        match (self, object, checksum) {
813            (SourceKind::Http(http), ObjectKind::Http(object), ChecksumKind::Http(checksum)) => {
814                http.get(object, checksum, range)
815                    .map(|result| result.context("http"))
816                    .boxed()
817            }
818            (SourceKind::AwsS3(s3), ObjectKind::AwsS3(object), ChecksumKind::AwsS3(checksum)) => s3
819                .get(object, checksum, range)
820                .map(|result| result.context("aws_s3"))
821                .boxed(),
822            (SourceKind::AwsS3(_) | SourceKind::Http(_), _, _) => {
823                unreachable!("programming error! wrong source, object, and checksum kind");
824            }
825        }
826    }
827}
828
829/// Enum wrapper for [`OneshotSource::Object`], see [`SourceKind`] for more details.
830#[derive(Debug, Clone, Serialize, Deserialize)]
831pub(crate) enum ObjectKind {
832    Http(HttpObject),
833    AwsS3(S3Object),
834}
835
836impl OneshotObject for ObjectKind {
837    fn name(&self) -> &str {
838        match self {
839            ObjectKind::Http(object) => object.name(),
840            ObjectKind::AwsS3(object) => object.name(),
841        }
842    }
843
844    fn path(&self) -> &str {
845        match self {
846            ObjectKind::Http(object) => object.path(),
847            ObjectKind::AwsS3(object) => object.path(),
848        }
849    }
850
851    fn size(&self) -> usize {
852        match self {
853            ObjectKind::Http(object) => object.size(),
854            ObjectKind::AwsS3(object) => object.size(),
855        }
856    }
857
858    fn encodings(&self) -> &[Encoding] {
859        match self {
860            ObjectKind::Http(object) => object.encodings(),
861            ObjectKind::AwsS3(object) => object.encodings(),
862        }
863    }
864}
865
866/// Enum wrapper for [`OneshotSource::Checksum`], see [`SourceKind`] for more details.
867#[derive(Debug, Clone, Serialize, Deserialize)]
868pub(crate) enum ChecksumKind {
869    Http(HttpChecksum),
870    AwsS3(S3Checksum),
871}
872
873/// Defines a format that we fetch for a "one time" ingestion.
874pub trait OneshotFormat: Clone {
875    /// A single unit of work for decoding this format, e.g. a single Parquet RowGroup.
876    type WorkRequest<S>: Debug + Clone + Send + Serialize + DeserializeOwned + 'static
877    where
878        S: OneshotSource;
879    /// A chunk of records in this format that can be decoded into Rows.
880    type RecordChunk: Debug + Clone + Send + Serialize + DeserializeOwned + 'static;
881
882    /// Given an upstream object, defines how we should parse this object in parallel.
883    ///
884    /// Note: It's totally fine to not process an object in parallel, and just return a single
885    /// [`Self::WorkRequest`] here.
886    fn split_work<S: OneshotSource + Send>(
887        &self,
888        source: S,
889        object: S::Object,
890        checksum: S::Checksum,
891    ) -> impl Future<Output = Result<Vec<Self::WorkRequest<S>>, StorageErrorX>> + Send;
892
893    /// Given a work request, fetch data from the [`OneshotSource`] and return it in a format that
894    /// can later be decoded.
895    fn fetch_work<'a, S: OneshotSource + Sync + 'static>(
896        &'a self,
897        source: &'a S,
898        request: Self::WorkRequest<S>,
899    ) -> BoxStream<'a, Result<Self::RecordChunk, StorageErrorX>>;
900
901    /// Decode a chunk of records into [`Row`]s.
902    fn decode_chunk(
903        &self,
904        chunk: Self::RecordChunk,
905        rows: &mut Vec<Row>,
906    ) -> Result<usize, StorageErrorX>;
907}
908
909/// An enum wrapper around [`OneshotFormat`]s.
910///
911/// An alternative to this wrapper would be to use `Box<dyn OneshotFormat>`, but that requires
912/// making the trait object safe and it's easier to just wrap it in an enum. Also, this wrapper
913/// provides a convenient place to add [`StorageErrorXContext::context`] for all of our format
914/// types.
915#[derive(Clone, Debug)]
916pub(crate) enum FormatKind {
917    Csv(CsvDecoder),
918    Parquet(ParquetFormat),
919}
920
921impl OneshotFormat for FormatKind {
922    type WorkRequest<S>
923        = RequestKind<S::Object, S::Checksum>
924    where
925        S: OneshotSource;
926    type RecordChunk = RecordChunkKind;
927
928    async fn split_work<S: OneshotSource + Send>(
929        &self,
930        source: S,
931        object: S::Object,
932        checksum: S::Checksum,
933    ) -> Result<Vec<Self::WorkRequest<S>>, StorageErrorX> {
934        match self {
935            FormatKind::Csv(csv) => {
936                let work = csv
937                    .split_work(source, object, checksum)
938                    .await
939                    .context("csv")?
940                    .into_iter()
941                    .map(RequestKind::Csv)
942                    .collect();
943                Ok(work)
944            }
945            FormatKind::Parquet(parquet) => {
946                let work = parquet
947                    .split_work(source, object, checksum)
948                    .await
949                    .context("parquet")?
950                    .into_iter()
951                    .map(RequestKind::Parquet)
952                    .collect();
953                Ok(work)
954            }
955        }
956    }
957
958    fn fetch_work<'a, S: OneshotSource + Sync + 'static>(
959        &'a self,
960        source: &'a S,
961        request: Self::WorkRequest<S>,
962    ) -> BoxStream<'a, Result<Self::RecordChunk, StorageErrorX>> {
963        match (self, request) {
964            (FormatKind::Csv(csv), RequestKind::Csv(request)) => csv
965                .fetch_work(source, request)
966                .map_ok(RecordChunkKind::Csv)
967                .map(|result| result.context("csv"))
968                .boxed(),
969            (FormatKind::Parquet(parquet), RequestKind::Parquet(request)) => parquet
970                .fetch_work(source, request)
971                .map_ok(RecordChunkKind::Parquet)
972                .map(|result| result.context("parquet"))
973                .boxed(),
974            (FormatKind::Parquet(_), RequestKind::Csv(_))
975            | (FormatKind::Csv(_), RequestKind::Parquet(_)) => {
976                unreachable!("programming error, {self:?}")
977            }
978        }
979    }
980
981    fn decode_chunk(
982        &self,
983        chunk: Self::RecordChunk,
984        rows: &mut Vec<Row>,
985    ) -> Result<usize, StorageErrorX> {
986        match (self, chunk) {
987            (FormatKind::Csv(csv), RecordChunkKind::Csv(chunk)) => {
988                csv.decode_chunk(chunk, rows).context("csv")
989            }
990            (FormatKind::Parquet(parquet), RecordChunkKind::Parquet(chunk)) => {
991                parquet.decode_chunk(chunk, rows).context("parquet")
992            }
993            (FormatKind::Parquet(_), RecordChunkKind::Csv(_))
994            | (FormatKind::Csv(_), RecordChunkKind::Parquet(_)) => {
995                unreachable!("programming error, {self:?}")
996            }
997        }
998    }
999}
1000
1001#[derive(Clone, Debug, Serialize, Deserialize)]
1002pub(crate) enum RequestKind<O, C> {
1003    Csv(CsvWorkRequest<O, C>),
1004    Parquet(ParquetWorkRequest<O, C>),
1005}
1006
1007#[derive(Clone, Debug, Serialize, Deserialize)]
1008pub(crate) enum RecordChunkKind {
1009    Csv(CsvRecord),
1010    Parquet(ParquetRowGroup),
1011}
1012
1013pub(crate) enum ObjectFilter {
1014    None,
1015    Files(BTreeSet<Box<str>>),
1016    Pattern(glob::Pattern),
1017}
1018
1019impl ObjectFilter {
1020    pub fn try_new(filter: ContentFilter) -> Result<Self, anyhow::Error> {
1021        match filter {
1022            ContentFilter::None => Ok(ObjectFilter::None),
1023            ContentFilter::Files(files) => {
1024                let files = files.into_iter().map(|f| f.into()).collect();
1025                Ok(ObjectFilter::Files(files))
1026            }
1027            ContentFilter::Pattern(pattern) => {
1028                let pattern = glob::Pattern::new(&pattern)?;
1029                Ok(ObjectFilter::Pattern(pattern))
1030            }
1031        }
1032    }
1033
1034    /// Returns if the object should be included.
1035    pub fn filter<S: OneshotSource>(&self, object: &S::Object) -> bool {
1036        match self {
1037            ObjectFilter::None => true,
1038            ObjectFilter::Files(files) => files.contains(object.path()),
1039            ObjectFilter::Pattern(pattern) => pattern.matches(object.path()),
1040        }
1041    }
1042}
1043
1044/// Experimental Error Type.
1045///
1046/// The goal of this type is to combine concepts from both `thiserror` and
1047/// `anyhow`. Having "stongly typed" errors from `thiserror` is useful for
1048/// determining what action to take and tracking the context of an error like
1049/// `anyhow` is useful for determining where an error came from.
1050#[derive(Debug, Clone, Deserialize, Serialize)]
1051pub struct StorageErrorX {
1052    kind: StorageErrorXKind,
1053    context: LinkedList<String>,
1054}
1055
1056impl fmt::Display for StorageErrorX {
1057    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1058        writeln!(f, "error: {}", self.kind)?;
1059        writeln!(f, "causes: {:?}", self.context)?;
1060        Ok(())
1061    }
1062}
1063
1064/// Experimental Error Type, see [`StorageErrorX`].
1065#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
1066pub enum StorageErrorXKind {
1067    #[error("csv decoding error: {0}")]
1068    CsvDecoding(Arc<str>),
1069    #[error("parquet error: {0}")]
1070    ParquetError(Arc<str>),
1071    #[error("reqwest error: {0}")]
1072    Reqwest(Arc<str>),
1073    #[error("aws s3 request error: {0}")]
1074    AwsS3Request(String),
1075    #[error("aws s3 bytestream error: {0}")]
1076    AwsS3Bytes(Arc<str>),
1077    #[error("invalid reqwest header: {0}")]
1078    InvalidHeader(Arc<str>),
1079    #[error("failed to decode Row from a record batch: {0}")]
1080    InvalidRecordBatch(Arc<str>),
1081    #[error("programming error: {0}")]
1082    ProgrammingError(Arc<str>),
1083    #[error("failed to get the size of an object")]
1084    MissingSize,
1085    #[error("object is missing the required '{0}' field")]
1086    MissingField(Arc<str>),
1087    #[error("failed while evaluating the provided mfp: '{0}'")]
1088    MfpEvalError(Arc<str>),
1089    #[error("no matching files found at the given url")]
1090    NoMatchingFiles,
1091    #[error("server returned HTTP {0}; Redirects are not supported, use the final URL directly.")]
1092    Redirect(u16),
1093    #[error("server returned HTTP {0}")]
1094    HttpStatus(u16),
1095    #[error("something went wrong: {0}")]
1096    Generic(String),
1097}
1098
1099impl From<csv_async::Error> for StorageErrorXKind {
1100    fn from(err: csv_async::Error) -> Self {
1101        StorageErrorXKind::CsvDecoding(err.to_string().into())
1102    }
1103}
1104
1105impl From<reqwest::Error> for StorageErrorXKind {
1106    fn from(err: reqwest::Error) -> Self {
1107        // Walk the source chain so that inner causes (like the custom DNS
1108        // resolver's "Address resolved to a private IP" rejection) are
1109        // visible. reqwest's top-level Display only says "error sending
1110        // request for url ..." and hides the underlying cause.
1111        StorageErrorXKind::Reqwest(err.to_string_with_causes().into())
1112    }
1113}
1114
1115impl From<reqwest::header::ToStrError> for StorageErrorXKind {
1116    fn from(err: reqwest::header::ToStrError) -> Self {
1117        StorageErrorXKind::InvalidHeader(err.to_string().into())
1118    }
1119}
1120
1121impl From<aws_smithy_types::byte_stream::error::Error> for StorageErrorXKind {
1122    fn from(err: aws_smithy_types::byte_stream::error::Error) -> Self {
1123        StorageErrorXKind::AwsS3Bytes(DisplayErrorContext(err).to_string().into())
1124    }
1125}
1126
1127impl From<::parquet::errors::ParquetError> for StorageErrorXKind {
1128    fn from(err: ::parquet::errors::ParquetError) -> Self {
1129        StorageErrorXKind::ParquetError(err.to_string().into())
1130    }
1131}
1132
1133impl StorageErrorXKind {
1134    pub fn with_context<C: Display>(self, context: C) -> StorageErrorX {
1135        StorageErrorX {
1136            kind: self,
1137            context: LinkedList::from([context.to_string()]),
1138        }
1139    }
1140
1141    pub fn invalid_record_batch<S: Into<Arc<str>>>(error: S) -> StorageErrorXKind {
1142        StorageErrorXKind::InvalidRecordBatch(error.into())
1143    }
1144
1145    pub fn generic<C: Display>(error: C) -> StorageErrorXKind {
1146        StorageErrorXKind::Generic(error.to_string())
1147    }
1148
1149    pub fn programming_error<S: Into<Arc<str>>>(error: S) -> StorageErrorXKind {
1150        StorageErrorXKind::ProgrammingError(error.into())
1151    }
1152}
1153
1154impl<E> From<E> for StorageErrorX
1155where
1156    E: Into<StorageErrorXKind>,
1157{
1158    fn from(err: E) -> Self {
1159        StorageErrorX {
1160            kind: err.into(),
1161            context: LinkedList::new(),
1162        }
1163    }
1164}
1165
1166trait StorageErrorXContext<T> {
1167    fn context<C>(self, context: C) -> Result<T, StorageErrorX>
1168    where
1169        C: Display;
1170}
1171
1172impl<T, E> StorageErrorXContext<T> for Result<T, E>
1173where
1174    E: Into<StorageErrorXKind>,
1175{
1176    fn context<C>(self, context: C) -> Result<T, StorageErrorX>
1177    where
1178        C: Display,
1179    {
1180        match self {
1181            Ok(val) => Ok(val),
1182            Err(kind) => Err(StorageErrorX {
1183                kind: kind.into(),
1184                context: LinkedList::from([context.to_string()]),
1185            }),
1186        }
1187    }
1188}
1189
1190impl<T> StorageErrorXContext<T> for Result<T, StorageErrorX> {
1191    fn context<C>(self, context: C) -> Result<T, StorageErrorX>
1192    where
1193        C: Display,
1194    {
1195        match self {
1196            Ok(val) => Ok(val),
1197            Err(mut e) => {
1198                e.context.push_back(context.to_string());
1199                Err(e)
1200            }
1201        }
1202    }
1203}