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