LCOV - code coverage report
Current view: top level - proxy/src/context - parquet.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 82.7 % 513 424
Test Date: 2024-05-10 13:18:37 Functions: 52.3 % 155 81

            Line data    Source code
       1              : use std::{sync::Arc, time::SystemTime};
       2              : 
       3              : use anyhow::Context;
       4              : use bytes::{buf::Writer, BufMut, BytesMut};
       5              : use chrono::{Datelike, Timelike};
       6              : use futures::{Stream, StreamExt};
       7              : use parquet::{
       8              :     basic::Compression,
       9              :     file::{
      10              :         metadata::RowGroupMetaDataPtr,
      11              :         properties::{WriterProperties, WriterPropertiesPtr, DEFAULT_PAGE_SIZE},
      12              :         writer::SerializedFileWriter,
      13              :     },
      14              :     record::RecordWriter,
      15              : };
      16              : use remote_storage::{GenericRemoteStorage, RemotePath, TimeoutOrCancel};
      17              : use tokio::{sync::mpsc, time};
      18              : use tokio_util::sync::CancellationToken;
      19              : use tracing::{debug, info, Span};
      20              : use utils::backoff;
      21              : 
      22              : use crate::{
      23              :     config::{remote_storage_from_toml, OptRemoteStorageConfig},
      24              :     context::LOG_CHAN_DISCONNECT,
      25              : };
      26              : 
      27              : use super::{RequestMonitoring, LOG_CHAN};
      28              : 
      29           12 : #[derive(clap::Args, Clone, Debug)]
      30              : pub struct ParquetUploadArgs {
      31              :     /// Storage location to upload the parquet files to.
      32              :     /// Encoded as toml (same format as pageservers), eg
      33              :     /// `{bucket_name='the-bucket',bucket_region='us-east-1',prefix_in_bucket='proxy',endpoint='http://minio:9000'}`
      34              :     #[clap(long, default_value = "{}", value_parser = remote_storage_from_toml)]
      35            0 :     parquet_upload_remote_storage: OptRemoteStorageConfig,
      36              : 
      37              :     #[clap(long, default_value = "{}", value_parser = remote_storage_from_toml)]
      38            0 :     parquet_upload_disconnect_events_remote_storage: OptRemoteStorageConfig,
      39              : 
      40              :     /// How many rows to include in a row group
      41            6 :     #[clap(long, default_value_t = 8192)]
      42            0 :     parquet_upload_row_group_size: usize,
      43              : 
      44              :     /// How large each column page should be in bytes
      45            6 :     #[clap(long, default_value_t = DEFAULT_PAGE_SIZE)]
      46            0 :     parquet_upload_page_size: usize,
      47              : 
      48              :     /// How large the total parquet file should be in bytes
      49            6 :     #[clap(long, default_value_t = 100_000_000)]
      50            0 :     parquet_upload_size: i64,
      51              : 
      52              :     /// How long to wait before forcing a file upload
      53              :     #[clap(long, default_value = "20m", value_parser = humantime::parse_duration)]
      54            0 :     parquet_upload_maximum_duration: tokio::time::Duration,
      55              : 
      56              :     /// What level of compression to use
      57            6 :     #[clap(long, default_value_t = Compression::UNCOMPRESSED)]
      58            0 :     parquet_upload_compression: Compression,
      59              : }
      60              : 
      61              : // Occasional network issues and such can cause remote operations to fail, and
      62              : // that's expected. If a upload fails, we log it at info-level, and retry.
      63              : // But after FAILED_UPLOAD_WARN_THRESHOLD retries, we start to log it at WARN
      64              : // level instead, as repeated failures can mean a more serious problem. If it
      65              : // fails more than FAILED_UPLOAD_RETRIES times, we give up
      66              : pub const FAILED_UPLOAD_WARN_THRESHOLD: u32 = 3;
      67              : pub const FAILED_UPLOAD_MAX_RETRIES: u32 = 10;
      68              : 
      69              : // the parquet crate leaves a lot to be desired...
      70              : // what follows is an attempt to write parquet files with minimal allocs.
      71              : // complication: parquet is a columnar format, while we want to write in as rows.
      72              : // design:
      73              : // * we batch up to 1024 rows, then flush them into a 'row group'
      74              : // * after each rowgroup write, we check the length of the file and upload to s3 if large enough
      75              : 
      76      7524222 : #[derive(parquet_derive::ParquetRecordWriter)]
      77              : pub struct RequestData {
      78              :     region: &'static str,
      79              :     protocol: &'static str,
      80              :     /// Must be UTC. The derive macro doesn't like the timezones
      81              :     timestamp: chrono::NaiveDateTime,
      82              :     session_id: uuid::Uuid,
      83              :     peer_addr: String,
      84              :     username: Option<String>,
      85              :     application_name: Option<String>,
      86              :     endpoint_id: Option<String>,
      87              :     database: Option<String>,
      88              :     project: Option<String>,
      89              :     branch: Option<String>,
      90              :     auth_method: Option<&'static str>,
      91              :     error: Option<&'static str>,
      92              :     /// Success is counted if we form a HTTP response with sql rows inside
      93              :     /// Or if we make it to proxy_pass
      94              :     success: bool,
      95              :     /// Indicates if the cplane started the new compute node for this request.
      96              :     cold_start_info: &'static str,
      97              :     /// Tracks time from session start (HTTP request/libpq TCP handshake)
      98              :     /// Through to success/failure
      99              :     duration_us: u64,
     100              :     /// If the session was successful after the disconnect, will be created one more event with filled `disconnect_timestamp`.
     101              :     disconnect_timestamp: Option<chrono::NaiveDateTime>,
     102              : }
     103              : 
     104              : impl From<&RequestMonitoring> for RequestData {
     105            0 :     fn from(value: &RequestMonitoring) -> Self {
     106            0 :         Self {
     107            0 :             session_id: value.session_id,
     108            0 :             peer_addr: value.peer_addr.to_string(),
     109            0 :             timestamp: value.first_packet.naive_utc(),
     110            0 :             username: value.user.as_deref().map(String::from),
     111            0 :             application_name: value.application.as_deref().map(String::from),
     112            0 :             endpoint_id: value.endpoint_id.as_deref().map(String::from),
     113            0 :             database: value.dbname.as_deref().map(String::from),
     114            0 :             project: value.project.as_deref().map(String::from),
     115            0 :             branch: value.branch.as_deref().map(String::from),
     116            0 :             auth_method: value.auth_method.as_ref().map(|x| match x {
     117            0 :                 super::AuthMethod::Web => "web",
     118            0 :                 super::AuthMethod::ScramSha256 => "scram_sha_256",
     119            0 :                 super::AuthMethod::ScramSha256Plus => "scram_sha_256_plus",
     120            0 :                 super::AuthMethod::Cleartext => "cleartext",
     121            0 :             }),
     122            0 :             protocol: value.protocol.as_str(),
     123            0 :             region: value.region,
     124            0 :             error: value.error_kind.as_ref().map(|e| e.to_metric_label()),
     125            0 :             success: value.success,
     126            0 :             cold_start_info: value.cold_start_info.as_str(),
     127            0 :             duration_us: SystemTime::from(value.first_packet)
     128            0 :                 .elapsed()
     129            0 :                 .unwrap_or_default()
     130            0 :                 .as_micros() as u64, // 584 millenia... good enough
     131            0 :             disconnect_timestamp: value.disconnect_timestamp.map(|x| x.naive_utc()),
     132            0 :         }
     133            0 :     }
     134              : }
     135              : 
     136              : /// Parquet request context worker
     137              : ///
     138              : /// It listened on a channel for all completed requests, extracts the data and writes it into a parquet file,
     139              : /// then uploads a completed batch to S3
     140            0 : pub async fn worker(
     141            0 :     cancellation_token: CancellationToken,
     142            0 :     config: ParquetUploadArgs,
     143            0 : ) -> anyhow::Result<()> {
     144            0 :     let Some(remote_storage_config) = config.parquet_upload_remote_storage else {
     145            0 :         tracing::warn!("parquet request upload: no s3 bucket configured");
     146            0 :         return Ok(());
     147              :     };
     148              : 
     149            0 :     let (tx, mut rx) = mpsc::unbounded_channel();
     150            0 :     LOG_CHAN.set(tx.downgrade()).unwrap();
     151            0 : 
     152            0 :     // setup row stream that will close on cancellation
     153            0 :     let cancellation_token2 = cancellation_token.clone();
     154            0 :     tokio::spawn(async move {
     155            0 :         cancellation_token2.cancelled().await;
     156              :         // dropping this sender will cause the channel to close only once
     157              :         // all the remaining inflight requests have been completed.
     158            0 :         drop(tx);
     159            0 :     });
     160            0 :     let rx = futures::stream::poll_fn(move |cx| rx.poll_recv(cx));
     161            0 :     let rx = rx.map(RequestData::from);
     162              : 
     163            0 :     let storage =
     164            0 :         GenericRemoteStorage::from_config(&remote_storage_config).context("remote storage init")?;
     165              : 
     166            0 :     let properties = WriterProperties::builder()
     167            0 :         .set_data_page_size_limit(config.parquet_upload_page_size)
     168            0 :         .set_compression(config.parquet_upload_compression);
     169            0 : 
     170            0 :     let parquet_config = ParquetConfig {
     171            0 :         propeties: Arc::new(properties.build()),
     172            0 :         rows_per_group: config.parquet_upload_row_group_size,
     173            0 :         file_size: config.parquet_upload_size,
     174            0 :         max_duration: config.parquet_upload_maximum_duration,
     175            0 : 
     176            0 :         #[cfg(any(test, feature = "testing"))]
     177            0 :         test_remote_failures: 0,
     178            0 :     };
     179              : 
     180              :     // TODO(anna): consider moving this to a separate function.
     181            0 :     if let Some(disconnect_events_storage_config) =
     182            0 :         config.parquet_upload_disconnect_events_remote_storage
     183              :     {
     184            0 :         let (tx_disconnect, mut rx_disconnect) = mpsc::unbounded_channel();
     185            0 :         LOG_CHAN_DISCONNECT.set(tx_disconnect.downgrade()).unwrap();
     186            0 : 
     187            0 :         // setup row stream that will close on cancellation
     188            0 :         tokio::spawn(async move {
     189            0 :             cancellation_token.cancelled().await;
     190              :             // dropping this sender will cause the channel to close only once
     191              :             // all the remaining inflight requests have been completed.
     192            0 :             drop(tx_disconnect);
     193            0 :         });
     194            0 :         let rx_disconnect = futures::stream::poll_fn(move |cx| rx_disconnect.poll_recv(cx));
     195            0 :         let rx_disconnect = rx_disconnect.map(RequestData::from);
     196              : 
     197            0 :         let storage_disconnect =
     198            0 :             GenericRemoteStorage::from_config(&disconnect_events_storage_config)
     199            0 :                 .context("remote storage for disconnect events init")?;
     200            0 :         let parquet_config_disconnect = parquet_config.clone();
     201              :         tokio::try_join!(
     202              :             worker_inner(storage, rx, parquet_config),
     203              :             worker_inner(storage_disconnect, rx_disconnect, parquet_config_disconnect)
     204              :         )
     205            0 :         .map(|_| ())
     206              :     } else {
     207            0 :         worker_inner(storage, rx, parquet_config).await
     208              :     }
     209            0 : }
     210              : 
     211              : #[derive(Clone, Debug)]
     212              : struct ParquetConfig {
     213              :     propeties: WriterPropertiesPtr,
     214              :     rows_per_group: usize,
     215              :     file_size: i64,
     216              : 
     217              :     max_duration: tokio::time::Duration,
     218              : 
     219              :     #[cfg(any(test, feature = "testing"))]
     220              :     test_remote_failures: u64,
     221              : }
     222              : 
     223           10 : async fn worker_inner(
     224           10 :     storage: GenericRemoteStorage,
     225           10 :     rx: impl Stream<Item = RequestData>,
     226           10 :     config: ParquetConfig,
     227           10 : ) -> anyhow::Result<()> {
     228              :     #[cfg(any(test, feature = "testing"))]
     229           10 :     let storage = if config.test_remote_failures > 0 {
     230            4 :         GenericRemoteStorage::unreliable_wrapper(storage, config.test_remote_failures)
     231              :     } else {
     232            6 :         storage
     233              :     };
     234              : 
     235           10 :     let mut rx = std::pin::pin!(rx);
     236           10 : 
     237           10 :     let mut rows = Vec::with_capacity(config.rows_per_group);
     238              : 
     239           10 :     let schema = rows.as_slice().schema()?;
     240           10 :     let buffer = BytesMut::new();
     241           10 :     let w = buffer.writer();
     242           10 :     let mut w = SerializedFileWriter::new(w, schema.clone(), config.propeties.clone())?;
     243              : 
     244           10 :     let mut last_upload = time::Instant::now();
     245           10 : 
     246           10 :     let mut len = 0;
     247       418010 :     while let Some(row) = rx.next().await {
     248       418000 :         rows.push(row);
     249       418000 :         let force = last_upload.elapsed() > config.max_duration;
     250       418000 :         if rows.len() == config.rows_per_group || force {
     251          210 :             let rg_meta;
     252          210 :             (rows, w, rg_meta) = flush_rows(rows, w).await?;
     253          210 :             len += rg_meta.compressed_size();
     254       417790 :         }
     255       418000 :         if len > config.file_size || force {
     256           56 :             last_upload = time::Instant::now();
     257          234 :             let file = upload_parquet(w, len, &storage).await?;
     258           56 :             w = SerializedFileWriter::new(file, schema.clone(), config.propeties.clone())?;
     259           56 :             len = 0;
     260       417944 :         }
     261              :     }
     262              : 
     263           10 :     if !rows.is_empty() {
     264            2 :         let rg_meta;
     265            2 :         (_, w, rg_meta) = flush_rows(rows, w).await?;
     266            2 :         len += rg_meta.compressed_size();
     267            8 :     }
     268              : 
     269           10 :     if !w.flushed_row_groups().is_empty() {
     270           24 :         let _: Writer<BytesMut> = upload_parquet(w, len, &storage).await?;
     271            4 :     }
     272              : 
     273           10 :     Ok(())
     274           10 : }
     275              : 
     276          212 : async fn flush_rows<W>(
     277          212 :     rows: Vec<RequestData>,
     278          212 :     mut w: SerializedFileWriter<W>,
     279          212 : ) -> anyhow::Result<(
     280          212 :     Vec<RequestData>,
     281          212 :     SerializedFileWriter<W>,
     282          212 :     RowGroupMetaDataPtr,
     283          212 : )>
     284          212 : where
     285          212 :     W: std::io::Write + Send + 'static,
     286          212 : {
     287          212 :     let span = Span::current();
     288          212 :     let (mut rows, w, rg_meta) = tokio::task::spawn_blocking(move || {
     289          212 :         let _enter = span.enter();
     290              : 
     291          212 :         let mut rg = w.next_row_group()?;
     292          212 :         rows.as_slice().write_to_row_group(&mut rg)?;
     293          212 :         let rg_meta = rg.close()?;
     294              : 
     295          212 :         let size = rg_meta.compressed_size();
     296          212 :         let compression = rg_meta.compressed_size() as f64 / rg_meta.total_byte_size() as f64;
     297          212 : 
     298          212 :         debug!(size, compression, "flushed row group to parquet file");
     299              : 
     300          212 :         Ok::<_, parquet::errors::ParquetError>((rows, w, rg_meta))
     301          212 :     })
     302          212 :     .await
     303          212 :     .unwrap()?;
     304              : 
     305          212 :     rows.clear();
     306          212 :     Ok((rows, w, rg_meta))
     307          212 : }
     308              : 
     309           62 : async fn upload_parquet(
     310           62 :     w: SerializedFileWriter<Writer<BytesMut>>,
     311           62 :     len: i64,
     312           62 :     storage: &GenericRemoteStorage,
     313           62 : ) -> anyhow::Result<Writer<BytesMut>> {
     314           62 :     let len_uncompressed = w
     315           62 :         .flushed_row_groups()
     316           62 :         .iter()
     317          212 :         .map(|rg| rg.total_byte_size())
     318           62 :         .sum::<i64>();
     319              : 
     320              :     // I don't know how compute intensive this is, although it probably isn't much... better be safe than sorry.
     321              :     // finish method only available on the fork: https://github.com/apache/arrow-rs/issues/5253
     322           62 :     let (writer, metadata) = tokio::task::spawn_blocking(move || w.finish())
     323           62 :         .await
     324           62 :         .unwrap()?;
     325              : 
     326           62 :     let mut buffer = writer.into_inner();
     327           62 :     let data = buffer.split().freeze();
     328           62 : 
     329           62 :     let compression = len as f64 / len_uncompressed as f64;
     330           62 :     let size = data.len();
     331           62 :     let now = chrono::Utc::now();
     332           62 :     let id = uuid::Uuid::new_v7(uuid::Timestamp::from_unix(
     333           62 :         uuid::NoContext,
     334           62 :         // we won't be running this in 1970. this cast is ok
     335           62 :         now.timestamp() as u64,
     336           62 :         now.timestamp_subsec_nanos(),
     337           62 :     ));
     338           62 : 
     339           62 :     info!(
     340              :         %id,
     341              :         rows = metadata.num_rows,
     342            0 :         size, compression, "uploading request parquet file"
     343              :     );
     344              : 
     345           62 :     let year = now.year();
     346           62 :     let month = now.month();
     347           62 :     let day = now.day();
     348           62 :     let hour = now.hour();
     349              :     // segment files by time for S3 performance
     350           62 :     let path = RemotePath::from_string(&format!(
     351           62 :         "{year:04}/{month:02}/{day:02}/{hour:02}/requests_{id}.parquet"
     352           62 :     ))?;
     353           62 :     let cancel = CancellationToken::new();
     354           62 :     backoff::retry(
     355           86 :         || async {
     356           86 :             let stream = futures::stream::once(futures::future::ready(Ok(data.clone())));
     357           86 :             storage
     358           86 :                 .upload(stream, data.len(), &path, None, &cancel)
     359          196 :                 .await
     360           86 :         },
     361           62 :         TimeoutOrCancel::caused_by_cancel,
     362           62 :         FAILED_UPLOAD_WARN_THRESHOLD,
     363           62 :         FAILED_UPLOAD_MAX_RETRIES,
     364           62 :         "request_data_upload",
     365           62 :         // we don't want cancellation to interrupt here, so we make a dummy cancel token
     366           62 :         &cancel,
     367           62 :     )
     368          196 :     .await
     369           62 :     .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
     370           62 :     .and_then(|x| x)
     371           62 :     .context("request_data_upload")?;
     372              : 
     373           62 :     Ok(buffer.writer())
     374           62 : }
     375              : 
     376              : #[cfg(test)]
     377              : mod tests {
     378              :     use std::{net::Ipv4Addr, num::NonZeroUsize, sync::Arc};
     379              : 
     380              :     use camino::Utf8Path;
     381              :     use clap::Parser;
     382              :     use futures::{Stream, StreamExt};
     383              :     use itertools::Itertools;
     384              :     use parquet::{
     385              :         basic::{Compression, ZstdLevel},
     386              :         file::{
     387              :             properties::{WriterProperties, DEFAULT_PAGE_SIZE},
     388              :             reader::FileReader,
     389              :             serialized_reader::SerializedFileReader,
     390              :         },
     391              :     };
     392              :     use rand::{rngs::StdRng, Rng, SeedableRng};
     393              :     use remote_storage::{
     394              :         GenericRemoteStorage, RemoteStorageConfig, RemoteStorageKind, S3Config,
     395              :         DEFAULT_MAX_KEYS_PER_LIST_RESPONSE, DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT,
     396              :     };
     397              :     use tokio::{sync::mpsc, time};
     398              :     use walkdir::WalkDir;
     399              : 
     400              :     use super::{worker_inner, ParquetConfig, ParquetUploadArgs, RequestData};
     401              : 
     402            4 :     #[derive(Parser)]
     403              :     struct ProxyCliArgs {
     404              :         #[clap(flatten)]
     405              :         parquet_upload: ParquetUploadArgs,
     406              :     }
     407              : 
     408              :     #[test]
     409            2 :     fn default_parser() {
     410            2 :         let ProxyCliArgs { parquet_upload } = ProxyCliArgs::parse_from(["proxy"]);
     411            2 :         assert_eq!(parquet_upload.parquet_upload_remote_storage, None);
     412            2 :         assert_eq!(parquet_upload.parquet_upload_row_group_size, 8192);
     413            2 :         assert_eq!(parquet_upload.parquet_upload_page_size, DEFAULT_PAGE_SIZE);
     414            2 :         assert_eq!(parquet_upload.parquet_upload_size, 100_000_000);
     415            2 :         assert_eq!(
     416            2 :             parquet_upload.parquet_upload_maximum_duration,
     417            2 :             time::Duration::from_secs(20 * 60)
     418            2 :         );
     419            2 :         assert_eq!(
     420            2 :             parquet_upload.parquet_upload_compression,
     421            2 :             Compression::UNCOMPRESSED
     422            2 :         );
     423            2 :     }
     424              : 
     425              :     #[test]
     426            2 :     fn full_parser() {
     427            2 :         let ProxyCliArgs { parquet_upload } = ProxyCliArgs::parse_from([
     428            2 :             "proxy",
     429            2 :             "--parquet-upload-remote-storage",
     430            2 :             "{bucket_name='default',prefix_in_bucket='proxy/',bucket_region='us-east-1',endpoint='http://minio:9000'}",
     431            2 :             "--parquet-upload-row-group-size",
     432            2 :             "100",
     433            2 :             "--parquet-upload-page-size",
     434            2 :             "10000",
     435            2 :             "--parquet-upload-size",
     436            2 :             "10000000",
     437            2 :             "--parquet-upload-maximum-duration",
     438            2 :             "10m",
     439            2 :             "--parquet-upload-compression",
     440            2 :             "zstd(5)",
     441            2 :         ]);
     442            2 :         assert_eq!(
     443            2 :             parquet_upload.parquet_upload_remote_storage,
     444            2 :             Some(RemoteStorageConfig {
     445            2 :                 storage: RemoteStorageKind::AwsS3(S3Config {
     446            2 :                     bucket_name: "default".into(),
     447            2 :                     bucket_region: "us-east-1".into(),
     448            2 :                     prefix_in_bucket: Some("proxy/".into()),
     449            2 :                     endpoint: Some("http://minio:9000".into()),
     450            2 :                     concurrency_limit: NonZeroUsize::new(
     451            2 :                         DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT
     452            2 :                     )
     453            2 :                     .unwrap(),
     454            2 :                     max_keys_per_list_response: DEFAULT_MAX_KEYS_PER_LIST_RESPONSE,
     455            2 :                     upload_storage_class: None,
     456            2 :                 }),
     457            2 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
     458            2 :             })
     459            2 :         );
     460            2 :         assert_eq!(parquet_upload.parquet_upload_row_group_size, 100);
     461            2 :         assert_eq!(parquet_upload.parquet_upload_page_size, 10000);
     462            2 :         assert_eq!(parquet_upload.parquet_upload_size, 10_000_000);
     463            2 :         assert_eq!(
     464            2 :             parquet_upload.parquet_upload_maximum_duration,
     465            2 :             time::Duration::from_secs(10 * 60)
     466            2 :         );
     467            2 :         assert_eq!(
     468            2 :             parquet_upload.parquet_upload_compression,
     469            2 :             Compression::ZSTD(ZstdLevel::try_new(5).unwrap())
     470            2 :         );
     471            2 :     }
     472              : 
     473       418000 :     fn generate_request_data(rng: &mut impl Rng) -> RequestData {
     474       418000 :         RequestData {
     475       418000 :             session_id: uuid::Builder::from_random_bytes(rng.gen()).into_uuid(),
     476       418000 :             peer_addr: Ipv4Addr::from(rng.gen::<[u8; 4]>()).to_string(),
     477       418000 :             timestamp: chrono::NaiveDateTime::from_timestamp_millis(
     478       418000 :                 rng.gen_range(1703862754..1803862754),
     479       418000 :             )
     480       418000 :             .unwrap(),
     481       418000 :             application_name: Some("test".to_owned()),
     482       418000 :             username: Some(hex::encode(rng.gen::<[u8; 4]>())),
     483       418000 :             endpoint_id: Some(hex::encode(rng.gen::<[u8; 16]>())),
     484       418000 :             database: Some(hex::encode(rng.gen::<[u8; 16]>())),
     485       418000 :             project: Some(hex::encode(rng.gen::<[u8; 16]>())),
     486       418000 :             branch: Some(hex::encode(rng.gen::<[u8; 16]>())),
     487       418000 :             auth_method: None,
     488       418000 :             protocol: ["tcp", "ws", "http"][rng.gen_range(0..3)],
     489       418000 :             region: "us-east-1",
     490       418000 :             error: None,
     491       418000 :             success: rng.gen(),
     492       418000 :             cold_start_info: "no",
     493       418000 :             duration_us: rng.gen_range(0..30_000_000),
     494       418000 :             disconnect_timestamp: None,
     495       418000 :         }
     496       418000 :     }
     497              : 
     498           14 :     fn random_stream(len: usize) -> impl Stream<Item = RequestData> + Unpin {
     499           14 :         let mut rng = StdRng::from_seed([0x39; 32]);
     500           14 :         futures::stream::iter(
     501       418000 :             std::iter::repeat_with(move || generate_request_data(&mut rng)).take(len),
     502           14 :         )
     503           14 :     }
     504              : 
     505           10 :     async fn run_test(
     506           10 :         tmpdir: &Utf8Path,
     507           10 :         config: ParquetConfig,
     508           10 :         rx: impl Stream<Item = RequestData>,
     509           10 :     ) -> Vec<(u64, usize, i64)> {
     510           10 :         let remote_storage_config = RemoteStorageConfig {
     511           10 :             storage: RemoteStorageKind::LocalFs(tmpdir.to_path_buf()),
     512           10 :             timeout: std::time::Duration::from_secs(120),
     513           10 :         };
     514           10 :         let storage = GenericRemoteStorage::from_config(&remote_storage_config).unwrap();
     515           10 : 
     516          610 :         worker_inner(storage, rx, config).await.unwrap();
     517           10 : 
     518           10 :         let mut files = WalkDir::new(tmpdir.as_std_path())
     519           10 :             .into_iter()
     520          112 :             .filter_map(|entry| entry.ok())
     521          112 :             .filter(|entry| entry.file_type().is_file())
     522           62 :             .map(|entry| entry.path().to_path_buf())
     523           10 :             .collect_vec();
     524           10 :         files.sort();
     525           10 : 
     526           10 :         files
     527           10 :             .into_iter()
     528           62 :             .map(|path| std::fs::File::open(tmpdir.as_std_path().join(path)).unwrap())
     529           62 :             .map(|file| {
     530           62 :                 (
     531           62 :                     file.metadata().unwrap(),
     532           62 :                     SerializedFileReader::new(file).unwrap().metadata().clone(),
     533           62 :                 )
     534           62 :             })
     535           62 :             .map(|(file_meta, parquet_meta)| {
     536           62 :                 (
     537           62 :                     file_meta.len(),
     538           62 :                     parquet_meta.num_row_groups(),
     539           62 :                     parquet_meta.file_metadata().num_rows(),
     540           62 :                 )
     541           62 :             })
     542           10 :             .collect()
     543           10 :     }
     544              : 
     545              :     #[tokio::test]
     546            2 :     async fn verify_parquet_no_compression() {
     547            2 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     548            2 : 
     549            2 :         let config = ParquetConfig {
     550            2 :             propeties: Arc::new(WriterProperties::new()),
     551            2 :             rows_per_group: 2_000,
     552            2 :             file_size: 1_000_000,
     553            2 :             max_duration: time::Duration::from_secs(20 * 60),
     554            2 :             test_remote_failures: 0,
     555            2 :         };
     556            2 : 
     557            2 :         let rx = random_stream(50_000);
     558          124 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     559            2 : 
     560            2 :         assert_eq!(
     561            2 :             file_stats,
     562            2 :             [
     563            2 :                 (1315008, 3, 6000),
     564            2 :                 (1315001, 3, 6000),
     565            2 :                 (1315061, 3, 6000),
     566            2 :                 (1315018, 3, 6000),
     567            2 :                 (1315148, 3, 6000),
     568            2 :                 (1314990, 3, 6000),
     569            2 :                 (1314782, 3, 6000),
     570            2 :                 (1315018, 3, 6000),
     571            2 :                 (438575, 1, 2000)
     572            2 :             ]
     573            2 :         );
     574            2 : 
     575            2 :         tmpdir.close().unwrap();
     576            2 :     }
     577              : 
     578              :     #[tokio::test]
     579            2 :     async fn verify_parquet_min_compression() {
     580            2 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     581            2 : 
     582            2 :         let config = ParquetConfig {
     583            2 :             propeties: Arc::new(
     584            2 :                 WriterProperties::builder()
     585            2 :                     .set_compression(parquet::basic::Compression::ZSTD(ZstdLevel::default()))
     586            2 :                     .build(),
     587            2 :             ),
     588            2 :             rows_per_group: 2_000,
     589            2 :             file_size: 1_000_000,
     590            2 :             max_duration: time::Duration::from_secs(20 * 60),
     591            2 :             test_remote_failures: 0,
     592            2 :         };
     593            2 : 
     594            2 :         let rx = random_stream(50_000);
     595           92 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     596            2 : 
     597            2 :         // with compression, there are fewer files with more rows per file
     598            2 :         assert_eq!(
     599            2 :             file_stats,
     600            2 :             [
     601            2 :                 (1221738, 5, 10000),
     602            2 :                 (1227888, 5, 10000),
     603            2 :                 (1229682, 5, 10000),
     604            2 :                 (1229044, 5, 10000),
     605            2 :                 (1220322, 5, 10000)
     606            2 :             ]
     607            2 :         );
     608            2 : 
     609            2 :         tmpdir.close().unwrap();
     610            2 :     }
     611              : 
     612              :     #[tokio::test]
     613            2 :     async fn verify_parquet_strong_compression() {
     614            2 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     615            2 : 
     616            2 :         let config = ParquetConfig {
     617            2 :             propeties: Arc::new(
     618            2 :                 WriterProperties::builder()
     619            2 :                     .set_compression(parquet::basic::Compression::ZSTD(
     620            2 :                         ZstdLevel::try_new(10).unwrap(),
     621            2 :                     ))
     622            2 :                     .build(),
     623            2 :             ),
     624            2 :             rows_per_group: 2_000,
     625            2 :             file_size: 1_000_000,
     626            2 :             max_duration: time::Duration::from_secs(20 * 60),
     627            2 :             test_remote_failures: 0,
     628            2 :         };
     629            2 : 
     630            2 :         let rx = random_stream(50_000);
     631           92 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     632            2 : 
     633            2 :         // with strong compression, the files are smaller
     634            2 :         assert_eq!(
     635            2 :             file_stats,
     636            2 :             [
     637            2 :                 (1207385, 5, 10000),
     638            2 :                 (1207116, 5, 10000),
     639            2 :                 (1207409, 5, 10000),
     640            2 :                 (1207397, 5, 10000),
     641            2 :                 (1207652, 5, 10000)
     642            2 :             ]
     643            2 :         );
     644            2 : 
     645            2 :         tmpdir.close().unwrap();
     646            2 :     }
     647              : 
     648              :     #[tokio::test]
     649            2 :     async fn verify_parquet_unreliable_upload() {
     650            2 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     651            2 : 
     652            2 :         let config = ParquetConfig {
     653            2 :             propeties: Arc::new(WriterProperties::new()),
     654            2 :             rows_per_group: 2_000,
     655            2 :             file_size: 1_000_000,
     656            2 :             max_duration: time::Duration::from_secs(20 * 60),
     657            2 :             test_remote_failures: 2,
     658            2 :         };
     659            2 : 
     660            2 :         let rx = random_stream(50_000);
     661          124 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     662            2 : 
     663            2 :         assert_eq!(
     664            2 :             file_stats,
     665            2 :             [
     666            2 :                 (1315008, 3, 6000),
     667            2 :                 (1315001, 3, 6000),
     668            2 :                 (1315061, 3, 6000),
     669            2 :                 (1315018, 3, 6000),
     670            2 :                 (1315148, 3, 6000),
     671            2 :                 (1314990, 3, 6000),
     672            2 :                 (1314782, 3, 6000),
     673            2 :                 (1315018, 3, 6000),
     674            2 :                 (438575, 1, 2000)
     675            2 :             ]
     676            2 :         );
     677            2 : 
     678            2 :         tmpdir.close().unwrap();
     679            2 :     }
     680              : 
     681              :     #[tokio::test(start_paused = true)]
     682            2 :     async fn verify_parquet_regular_upload() {
     683            2 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     684            2 : 
     685            2 :         let config = ParquetConfig {
     686            2 :             propeties: Arc::new(WriterProperties::new()),
     687            2 :             rows_per_group: 2_000,
     688            2 :             file_size: 1_000_000,
     689            2 :             max_duration: time::Duration::from_secs(60),
     690            2 :             test_remote_failures: 2,
     691            2 :         };
     692            2 : 
     693            2 :         let (tx, mut rx) = mpsc::unbounded_channel();
     694            2 : 
     695            2 :         tokio::spawn(async move {
     696            8 :             for _ in 0..3 {
     697            6 :                 let mut s = random_stream(3000);
     698        18006 :                 while let Some(r) = s.next().await {
     699        18000 :                     tx.send(r).unwrap();
     700        18000 :                 }
     701            6 :                 time::sleep(time::Duration::from_secs(70)).await
     702            2 :             }
     703            2 :         });
     704            2 : 
     705        18142 :         let rx = futures::stream::poll_fn(move |cx| rx.poll_recv(cx));
     706          178 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     707            2 : 
     708            2 :         // files are smaller than the size threshold, but they took too long to fill so were flushed early
     709            2 :         assert_eq!(
     710            2 :             file_stats,
     711            2 :             [(659240, 2, 3001), (658954, 2, 3000), (658750, 2, 2999)]
     712            2 :         );
     713            2 : 
     714            2 :         tmpdir.close().unwrap();
     715            2 :     }
     716              : }
        

Generated by: LCOV version 2.1-beta