LCOV - code coverage report
Current view: top level - proxy/src/context - parquet.rs (source / functions) Coverage Total Hit
Test: 2b0730d767f560e20b6748f57465922aa8bb805e.info Lines: 78.8 % 510 402
Test Date: 2024-09-25 14:04:07 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 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::{RequestMonitoringInner, LOG_CHAN};
      27              : 
      28            6 : #[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            3 :     #[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            3 :     #[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            3 :     #[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            3 :     #[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(crate) const FAILED_UPLOAD_WARN_THRESHOLD: u32 = 3;
      66              : pub(crate) 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      3180085 : #[derive(parquet_derive::ParquetRecordWriter)]
      76              : pub(crate) 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<&RequestMonitoringInner> for RequestData {
     122            0 :     fn from(value: &RequestMonitoringInner) -> 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 = GenericRemoteStorage::from_config(&remote_storage_config)
     185            0 :         .await
     186            0 :         .context("remote storage init")?;
     187              : 
     188            0 :     let properties = WriterProperties::builder()
     189            0 :         .set_data_page_size_limit(config.parquet_upload_page_size)
     190            0 :         .set_compression(config.parquet_upload_compression);
     191            0 : 
     192            0 :     let parquet_config = ParquetConfig {
     193            0 :         propeties: Arc::new(properties.build()),
     194            0 :         rows_per_group: config.parquet_upload_row_group_size,
     195            0 :         file_size: config.parquet_upload_size,
     196            0 :         max_duration: config.parquet_upload_maximum_duration,
     197            0 : 
     198            0 :         #[cfg(any(test, feature = "testing"))]
     199            0 :         test_remote_failures: 0,
     200            0 :     };
     201              : 
     202              :     // TODO(anna): consider moving this to a separate function.
     203            0 :     if let Some(disconnect_events_storage_config) =
     204            0 :         config.parquet_upload_disconnect_events_remote_storage
     205              :     {
     206            0 :         let (tx_disconnect, mut rx_disconnect) = mpsc::unbounded_channel();
     207            0 :         LOG_CHAN_DISCONNECT.set(tx_disconnect.downgrade()).unwrap();
     208            0 : 
     209            0 :         // setup row stream that will close on cancellation
     210            0 :         tokio::spawn(async move {
     211            0 :             cancellation_token.cancelled().await;
     212              :             // dropping this sender will cause the channel to close only once
     213              :             // all the remaining inflight requests have been completed.
     214            0 :             drop(tx_disconnect);
     215            0 :         });
     216            0 :         let rx_disconnect = futures::stream::poll_fn(move |cx| rx_disconnect.poll_recv(cx));
     217            0 :         let rx_disconnect = rx_disconnect.map(RequestData::from);
     218              : 
     219            0 :         let storage_disconnect =
     220            0 :             GenericRemoteStorage::from_config(&disconnect_events_storage_config)
     221            0 :                 .await
     222            0 :                 .context("remote storage for disconnect events init")?;
     223            0 :         let parquet_config_disconnect = parquet_config.clone();
     224            0 :         tokio::try_join!(
     225            0 :             worker_inner(storage, rx, parquet_config),
     226            0 :             worker_inner(storage_disconnect, rx_disconnect, parquet_config_disconnect)
     227            0 :         )
     228            0 :         .map(|_| ())
     229              :     } else {
     230            0 :         worker_inner(storage, rx, parquet_config).await
     231              :     }
     232            0 : }
     233              : 
     234              : #[derive(Clone, Debug)]
     235              : struct ParquetConfig {
     236              :     propeties: WriterPropertiesPtr,
     237              :     rows_per_group: usize,
     238              :     file_size: i64,
     239              : 
     240              :     max_duration: tokio::time::Duration,
     241              : 
     242              :     #[cfg(any(test, feature = "testing"))]
     243              :     test_remote_failures: u64,
     244              : }
     245              : 
     246            4 : async fn worker_inner(
     247            4 :     storage: GenericRemoteStorage,
     248            4 :     rx: impl Stream<Item = RequestData>,
     249            4 :     config: ParquetConfig,
     250            4 : ) -> anyhow::Result<()> {
     251              :     #[cfg(any(test, feature = "testing"))]
     252            4 :     let storage = if config.test_remote_failures > 0 {
     253            2 :         GenericRemoteStorage::unreliable_wrapper(storage, config.test_remote_failures)
     254              :     } else {
     255            2 :         storage
     256              :     };
     257              : 
     258            4 :     let mut rx = std::pin::pin!(rx);
     259            4 : 
     260            4 :     let mut rows = Vec::with_capacity(config.rows_per_group);
     261              : 
     262            4 :     let schema = rows.as_slice().schema()?;
     263            4 :     let buffer = BytesMut::new();
     264            4 :     let w = buffer.writer();
     265            4 :     let mut w = SerializedFileWriter::new(w, schema.clone(), config.propeties.clone())?;
     266              : 
     267            4 :     let mut last_upload = time::Instant::now();
     268            4 : 
     269            4 :     let mut len = 0;
     270       159004 :     while let Some(row) = rx.next().await {
     271       159000 :         rows.push(row);
     272       159000 :         let force = last_upload.elapsed() > config.max_duration;
     273       159000 :         if rows.len() == config.rows_per_group || force {
     274              :             let rg_meta;
     275           80 :             (rows, w, rg_meta) = flush_rows(rows, w).await?;
     276           80 :             len += rg_meta.compressed_size();
     277       158920 :         }
     278       159000 :         if len > config.file_size || force {
     279           23 :             last_upload = time::Instant::now();
     280           96 :             let file = upload_parquet(w, len, &storage).await?;
     281           23 :             w = SerializedFileWriter::new(file, schema.clone(), config.propeties.clone())?;
     282           23 :             len = 0;
     283       158977 :         }
     284              :     }
     285              : 
     286            4 :     if !rows.is_empty() {
     287              :         let rg_meta;
     288            1 :         (_, w, rg_meta) = flush_rows(rows, w).await?;
     289            1 :         len += rg_meta.compressed_size();
     290            3 :     }
     291              : 
     292            4 :     if !w.flushed_row_groups().is_empty() {
     293           12 :         let _rtchk: Writer<BytesMut> = upload_parquet(w, len, &storage).await?;
     294            1 :     }
     295              : 
     296            4 :     Ok(())
     297            4 : }
     298              : 
     299           81 : async fn flush_rows<W>(
     300           81 :     rows: Vec<RequestData>,
     301           81 :     mut w: SerializedFileWriter<W>,
     302           81 : ) -> anyhow::Result<(
     303           81 :     Vec<RequestData>,
     304           81 :     SerializedFileWriter<W>,
     305           81 :     RowGroupMetaDataPtr,
     306           81 : )>
     307           81 : where
     308           81 :     W: std::io::Write + Send + 'static,
     309           81 : {
     310           81 :     let span = Span::current();
     311           81 :     let (mut rows, w, rg_meta) = tokio::task::spawn_blocking(move || {
     312           81 :         let _enter = span.enter();
     313              : 
     314           81 :         let mut rg = w.next_row_group()?;
     315           81 :         rows.as_slice().write_to_row_group(&mut rg)?;
     316           81 :         let rg_meta = rg.close()?;
     317              : 
     318           81 :         let size = rg_meta.compressed_size();
     319           81 :         let compression = rg_meta.compressed_size() as f64 / rg_meta.total_byte_size() as f64;
     320           81 : 
     321           81 :         debug!(size, compression, "flushed row group to parquet file");
     322              : 
     323           81 :         Ok::<_, parquet::errors::ParquetError>((rows, w, rg_meta))
     324           81 :     })
     325           81 :     .await
     326           81 :     .unwrap()?;
     327              : 
     328           81 :     rows.clear();
     329           81 :     Ok((rows, w, rg_meta))
     330           81 : }
     331              : 
     332           26 : async fn upload_parquet(
     333           26 :     mut w: SerializedFileWriter<Writer<BytesMut>>,
     334           26 :     len: i64,
     335           26 :     storage: &GenericRemoteStorage,
     336           26 : ) -> anyhow::Result<Writer<BytesMut>> {
     337           26 :     let len_uncompressed = w
     338           26 :         .flushed_row_groups()
     339           26 :         .iter()
     340           81 :         .map(|rg| rg.total_byte_size())
     341           26 :         .sum::<i64>();
     342              : 
     343              :     // I don't know how compute intensive this is, although it probably isn't much... better be safe than sorry.
     344              :     // finish method only available on the fork: https://github.com/apache/arrow-rs/issues/5253
     345           26 :     let (mut buffer, metadata) =
     346           26 :         tokio::task::spawn_blocking(move || -> parquet::errors::Result<_> {
     347           26 :             let metadata = w.finish()?;
     348           26 :             let buffer = std::mem::take(w.inner_mut().get_mut());
     349           26 :             Ok((buffer, metadata))
     350           26 :         })
     351           26 :         .await
     352           26 :         .unwrap()?;
     353              : 
     354           26 :     let data = buffer.split().freeze();
     355           26 : 
     356           26 :     let compression = len as f64 / len_uncompressed as f64;
     357           26 :     let size = data.len();
     358           26 :     let now = chrono::Utc::now();
     359           26 :     let id = uuid::Uuid::new_v7(uuid::Timestamp::from_unix(
     360           26 :         uuid::NoContext,
     361           26 :         // we won't be running this in 1970. this cast is ok
     362           26 :         now.timestamp() as u64,
     363           26 :         now.timestamp_subsec_nanos(),
     364           26 :     ));
     365           26 : 
     366           26 :     info!(
     367              :         %id,
     368              :         rows = metadata.num_rows,
     369            0 :         size, compression, "uploading request parquet file"
     370              :     );
     371              : 
     372           26 :     let year = now.year();
     373           26 :     let month = now.month();
     374           26 :     let day = now.day();
     375           26 :     let hour = now.hour();
     376              :     // segment files by time for S3 performance
     377           26 :     let path = RemotePath::from_string(&format!(
     378           26 :         "{year:04}/{month:02}/{day:02}/{hour:02}/requests_{id}.parquet"
     379           26 :     ))?;
     380           26 :     let cancel = CancellationToken::new();
     381           26 :     let maybe_err = backoff::retry(
     382           38 :         || async {
     383           38 :             let stream = futures::stream::once(futures::future::ready(Ok(data.clone())));
     384           38 :             storage
     385           38 :                 .upload(stream, data.len(), &path, None, &cancel)
     386           82 :                 .await
     387           76 :         },
     388           26 :         TimeoutOrCancel::caused_by_cancel,
     389           26 :         FAILED_UPLOAD_WARN_THRESHOLD,
     390           26 :         FAILED_UPLOAD_MAX_RETRIES,
     391           26 :         "request_data_upload",
     392           26 :         // we don't want cancellation to interrupt here, so we make a dummy cancel token
     393           26 :         &cancel,
     394           26 :     )
     395           82 :     .await
     396           26 :     .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
     397           26 :     .and_then(|x| x)
     398           26 :     .context("request_data_upload")
     399           26 :     .err();
     400              : 
     401           26 :     if let Some(err) = maybe_err {
     402            0 :         tracing::warn!(%id, %err, "failed to upload request data");
     403           26 :     }
     404              : 
     405           26 :     Ok(buffer.writer())
     406           26 : }
     407              : 
     408              : #[cfg(test)]
     409              : mod tests {
     410              :     use std::{net::Ipv4Addr, num::NonZeroUsize, sync::Arc};
     411              : 
     412              :     use camino::Utf8Path;
     413              :     use clap::Parser;
     414              :     use futures::{Stream, StreamExt};
     415              :     use itertools::Itertools;
     416              :     use parquet::{
     417              :         basic::{Compression, ZstdLevel},
     418              :         file::{
     419              :             properties::{WriterProperties, DEFAULT_PAGE_SIZE},
     420              :             reader::FileReader,
     421              :             serialized_reader::SerializedFileReader,
     422              :         },
     423              :     };
     424              :     use rand::{rngs::StdRng, Rng, SeedableRng};
     425              :     use remote_storage::{
     426              :         GenericRemoteStorage, RemoteStorageConfig, RemoteStorageKind, S3Config,
     427              :         DEFAULT_MAX_KEYS_PER_LIST_RESPONSE, DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT,
     428              :     };
     429              :     use tokio::{sync::mpsc, time};
     430              :     use walkdir::WalkDir;
     431              : 
     432              :     use super::{worker_inner, ParquetConfig, ParquetUploadArgs, RequestData};
     433              : 
     434            2 :     #[derive(Parser)]
     435              :     struct ProxyCliArgs {
     436              :         #[clap(flatten)]
     437              :         parquet_upload: ParquetUploadArgs,
     438              :     }
     439              : 
     440              :     #[test]
     441            1 :     fn default_parser() {
     442            1 :         let ProxyCliArgs { parquet_upload } = ProxyCliArgs::parse_from(["proxy"]);
     443            1 :         assert_eq!(parquet_upload.parquet_upload_remote_storage, None);
     444            1 :         assert_eq!(parquet_upload.parquet_upload_row_group_size, 8192);
     445            1 :         assert_eq!(parquet_upload.parquet_upload_page_size, DEFAULT_PAGE_SIZE);
     446            1 :         assert_eq!(parquet_upload.parquet_upload_size, 100_000_000);
     447            1 :         assert_eq!(
     448            1 :             parquet_upload.parquet_upload_maximum_duration,
     449            1 :             time::Duration::from_secs(20 * 60)
     450            1 :         );
     451            1 :         assert_eq!(
     452            1 :             parquet_upload.parquet_upload_compression,
     453            1 :             Compression::UNCOMPRESSED
     454            1 :         );
     455            1 :     }
     456              : 
     457              :     #[test]
     458            1 :     fn full_parser() {
     459            1 :         let ProxyCliArgs { parquet_upload } = ProxyCliArgs::parse_from([
     460            1 :             "proxy",
     461            1 :             "--parquet-upload-remote-storage",
     462            1 :             "{bucket_name='default',prefix_in_bucket='proxy/',bucket_region='us-east-1',endpoint='http://minio:9000'}",
     463            1 :             "--parquet-upload-row-group-size",
     464            1 :             "100",
     465            1 :             "--parquet-upload-page-size",
     466            1 :             "10000",
     467            1 :             "--parquet-upload-size",
     468            1 :             "10000000",
     469            1 :             "--parquet-upload-maximum-duration",
     470            1 :             "10m",
     471            1 :             "--parquet-upload-compression",
     472            1 :             "zstd(5)",
     473            1 :         ]);
     474            1 :         assert_eq!(
     475            1 :             parquet_upload.parquet_upload_remote_storage,
     476            1 :             Some(RemoteStorageConfig {
     477            1 :                 storage: RemoteStorageKind::AwsS3(S3Config {
     478            1 :                     bucket_name: "default".into(),
     479            1 :                     bucket_region: "us-east-1".into(),
     480            1 :                     prefix_in_bucket: Some("proxy/".into()),
     481            1 :                     endpoint: Some("http://minio:9000".into()),
     482            1 :                     concurrency_limit: NonZeroUsize::new(
     483            1 :                         DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT
     484            1 :                     )
     485            1 :                     .unwrap(),
     486            1 :                     max_keys_per_list_response: DEFAULT_MAX_KEYS_PER_LIST_RESPONSE,
     487            1 :                     upload_storage_class: None,
     488            1 :                 }),
     489            1 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
     490            1 :             })
     491            1 :         );
     492            1 :         assert_eq!(parquet_upload.parquet_upload_row_group_size, 100);
     493            1 :         assert_eq!(parquet_upload.parquet_upload_page_size, 10000);
     494            1 :         assert_eq!(parquet_upload.parquet_upload_size, 10_000_000);
     495            1 :         assert_eq!(
     496            1 :             parquet_upload.parquet_upload_maximum_duration,
     497            1 :             time::Duration::from_secs(10 * 60)
     498            1 :         );
     499            1 :         assert_eq!(
     500            1 :             parquet_upload.parquet_upload_compression,
     501            1 :             Compression::ZSTD(ZstdLevel::try_new(5).unwrap())
     502            1 :         );
     503            1 :     }
     504              : 
     505       159000 :     fn generate_request_data(rng: &mut impl Rng) -> RequestData {
     506       159000 :         RequestData {
     507       159000 :             session_id: uuid::Builder::from_random_bytes(rng.gen()).into_uuid(),
     508       159000 :             peer_addr: Ipv4Addr::from(rng.gen::<[u8; 4]>()).to_string(),
     509       159000 :             timestamp: chrono::DateTime::from_timestamp_millis(
     510       159000 :                 rng.gen_range(1703862754..1803862754),
     511       159000 :             )
     512       159000 :             .unwrap()
     513       159000 :             .naive_utc(),
     514       159000 :             application_name: Some("test".to_owned()),
     515       159000 :             username: Some(hex::encode(rng.gen::<[u8; 4]>())),
     516       159000 :             endpoint_id: Some(hex::encode(rng.gen::<[u8; 16]>())),
     517       159000 :             database: Some(hex::encode(rng.gen::<[u8; 16]>())),
     518       159000 :             project: Some(hex::encode(rng.gen::<[u8; 16]>())),
     519       159000 :             branch: Some(hex::encode(rng.gen::<[u8; 16]>())),
     520       159000 :             pg_options: None,
     521       159000 :             auth_method: None,
     522       159000 :             protocol: ["tcp", "ws", "http"][rng.gen_range(0..3)],
     523       159000 :             region: "us-east-1",
     524       159000 :             error: None,
     525       159000 :             success: rng.gen(),
     526       159000 :             cold_start_info: "no",
     527       159000 :             duration_us: rng.gen_range(0..30_000_000),
     528       159000 :             disconnect_timestamp: None,
     529       159000 :         }
     530       159000 :     }
     531              : 
     532            6 :     fn random_stream(len: usize) -> impl Stream<Item = RequestData> + Unpin {
     533            6 :         let mut rng = StdRng::from_seed([0x39; 32]);
     534            6 :         futures::stream::iter(
     535       159000 :             std::iter::repeat_with(move || generate_request_data(&mut rng)).take(len),
     536            6 :         )
     537            6 :     }
     538              : 
     539            4 :     async fn run_test(
     540            4 :         tmpdir: &Utf8Path,
     541            4 :         config: ParquetConfig,
     542            4 :         rx: impl Stream<Item = RequestData>,
     543            4 :     ) -> Vec<(u64, usize, i64)> {
     544            4 :         let remote_storage_config = RemoteStorageConfig {
     545            4 :             storage: RemoteStorageKind::LocalFs {
     546            4 :                 local_path: tmpdir.to_path_buf(),
     547            4 :             },
     548            4 :             timeout: std::time::Duration::from_secs(120),
     549            4 :         };
     550            4 :         let storage = GenericRemoteStorage::from_config(&remote_storage_config)
     551            0 :             .await
     552            4 :             .unwrap();
     553            4 : 
     554          259 :         worker_inner(storage, rx, config).await.unwrap();
     555            4 : 
     556            4 :         let mut files = WalkDir::new(tmpdir.as_std_path())
     557            4 :             .into_iter()
     558           46 :             .filter_map(|entry| entry.ok())
     559           46 :             .filter(|entry| entry.file_type().is_file())
     560           26 :             .map(|entry| entry.path().to_path_buf())
     561            4 :             .collect_vec();
     562            4 :         files.sort();
     563            4 : 
     564            4 :         files
     565            4 :             .into_iter()
     566           26 :             .map(|path| std::fs::File::open(tmpdir.as_std_path().join(path)).unwrap())
     567           26 :             .map(|file| {
     568           26 :                 (
     569           26 :                     file.metadata().unwrap(),
     570           26 :                     SerializedFileReader::new(file).unwrap().metadata().clone(),
     571           26 :                 )
     572           26 :             })
     573           26 :             .map(|(file_meta, parquet_meta)| {
     574           26 :                 (
     575           26 :                     file_meta.len(),
     576           26 :                     parquet_meta.num_row_groups(),
     577           26 :                     parquet_meta.file_metadata().num_rows(),
     578           26 :                 )
     579           26 :             })
     580            4 :             .collect()
     581            4 :     }
     582              : 
     583              :     #[tokio::test]
     584            1 :     async fn verify_parquet_no_compression() {
     585            1 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     586            1 : 
     587            1 :         let config = ParquetConfig {
     588            1 :             propeties: Arc::new(WriterProperties::new()),
     589            1 :             rows_per_group: 2_000,
     590            1 :             file_size: 1_000_000,
     591            1 :             max_duration: time::Duration::from_secs(20 * 60),
     592            1 :             test_remote_failures: 0,
     593            1 :         };
     594            1 : 
     595            1 :         let rx = random_stream(50_000);
     596           62 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     597            1 : 
     598            1 :         assert_eq!(
     599            1 :             file_stats,
     600            1 :             [
     601            1 :                 (1312632, 3, 6000),
     602            1 :                 (1312621, 3, 6000),
     603            1 :                 (1312680, 3, 6000),
     604            1 :                 (1312637, 3, 6000),
     605            1 :                 (1312773, 3, 6000),
     606            1 :                 (1312610, 3, 6000),
     607            1 :                 (1312404, 3, 6000),
     608            1 :                 (1312639, 3, 6000),
     609            1 :                 (437848, 1, 2000)
     610            1 :             ]
     611            1 :         );
     612            1 : 
     613            1 :         tmpdir.close().unwrap();
     614            1 :     }
     615              : 
     616              :     #[tokio::test]
     617            1 :     async fn verify_parquet_strong_compression() {
     618            1 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     619            1 : 
     620            1 :         let config = ParquetConfig {
     621            1 :             propeties: Arc::new(
     622            1 :                 WriterProperties::builder()
     623            1 :                     .set_compression(parquet::basic::Compression::ZSTD(
     624            1 :                         ZstdLevel::try_new(10).unwrap(),
     625            1 :                     ))
     626            1 :                     .build(),
     627            1 :             ),
     628            1 :             rows_per_group: 2_000,
     629            1 :             file_size: 1_000_000,
     630            1 :             max_duration: time::Duration::from_secs(20 * 60),
     631            1 :             test_remote_failures: 0,
     632            1 :         };
     633            1 : 
     634            1 :         let rx = random_stream(50_000);
     635           46 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     636            1 : 
     637            1 :         // with strong compression, the files are smaller
     638            1 :         assert_eq!(
     639            1 :             file_stats,
     640            1 :             [
     641            1 :                 (1203465, 5, 10000),
     642            1 :                 (1203189, 5, 10000),
     643            1 :                 (1203490, 5, 10000),
     644            1 :                 (1203475, 5, 10000),
     645            1 :                 (1203729, 5, 10000)
     646            1 :             ]
     647            1 :         );
     648            1 : 
     649            1 :         tmpdir.close().unwrap();
     650            1 :     }
     651              : 
     652              :     #[tokio::test]
     653            1 :     async fn verify_parquet_unreliable_upload() {
     654            1 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     655            1 : 
     656            1 :         let config = ParquetConfig {
     657            1 :             propeties: Arc::new(WriterProperties::new()),
     658            1 :             rows_per_group: 2_000,
     659            1 :             file_size: 1_000_000,
     660            1 :             max_duration: time::Duration::from_secs(20 * 60),
     661            1 :             test_remote_failures: 2,
     662            1 :         };
     663            1 : 
     664            1 :         let rx = random_stream(50_000);
     665           62 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     666            1 : 
     667            1 :         assert_eq!(
     668            1 :             file_stats,
     669            1 :             [
     670            1 :                 (1312632, 3, 6000),
     671            1 :                 (1312621, 3, 6000),
     672            1 :                 (1312680, 3, 6000),
     673            1 :                 (1312637, 3, 6000),
     674            1 :                 (1312773, 3, 6000),
     675            1 :                 (1312610, 3, 6000),
     676            1 :                 (1312404, 3, 6000),
     677            1 :                 (1312639, 3, 6000),
     678            1 :                 (437848, 1, 2000)
     679            1 :             ]
     680            1 :         );
     681            1 : 
     682            1 :         tmpdir.close().unwrap();
     683            1 :     }
     684              : 
     685              :     #[tokio::test(start_paused = true)]
     686            1 :     async fn verify_parquet_regular_upload() {
     687            1 :         let tmpdir = camino_tempfile::tempdir().unwrap();
     688            1 : 
     689            1 :         let config = ParquetConfig {
     690            1 :             propeties: Arc::new(WriterProperties::new()),
     691            1 :             rows_per_group: 2_000,
     692            1 :             file_size: 1_000_000,
     693            1 :             max_duration: time::Duration::from_secs(60),
     694            1 :             test_remote_failures: 2,
     695            1 :         };
     696            1 : 
     697            1 :         let (tx, mut rx) = mpsc::unbounded_channel();
     698            1 : 
     699            1 :         tokio::spawn(async move {
     700            4 :             for _ in 0..3 {
     701            3 :                 let mut s = random_stream(3000);
     702         9003 :                 while let Some(r) = s.next().await {
     703         9000 :                     tx.send(r).unwrap();
     704         9000 :                 }
     705            3 :                 time::sleep(time::Duration::from_secs(70)).await;
     706            1 :             }
     707            1 :         });
     708            1 : 
     709         9071 :         let rx = futures::stream::poll_fn(move |cx| rx.poll_recv(cx));
     710           89 :         let file_stats = run_test(tmpdir.path(), config, rx).await;
     711            1 : 
     712            1 :         // files are smaller than the size threshold, but they took too long to fill so were flushed early
     713            1 :         assert_eq!(
     714            1 :             file_stats,
     715            1 :             [(657696, 2, 3001), (657410, 2, 3000), (657206, 2, 2999)]
     716            1 :         );
     717            1 : 
     718            1 :         tmpdir.close().unwrap();
     719            1 :     }
     720              : }
        

Generated by: LCOV version 2.1-beta