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