LCOV - code coverage report
Current view: top level - proxy/src/context - parquet.rs (source / functions) Coverage Total Hit
Test: 12c2fc96834f59604b8ade5b9add28f1dce41ec6.info Lines: 81.2 % 536 435
Test Date: 2024-07-03 15:33:13 Functions: 52.9 % 157 83

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

Generated by: LCOV version 2.1-beta