From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits)) (No client certificate requested) by lists.proxmox.com (Postfix) with ESMTPS id B4A0770E6E for ; Tue, 6 Apr 2021 11:04:24 +0200 (CEST) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id AAA7B2B6A0 for ; Tue, 6 Apr 2021 11:03:54 +0200 (CEST) Received: from proxmox-new.maurer-it.com (proxmox-new.maurer-it.com [212.186.127.180]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits)) (No client certificate requested) by firstgate.proxmox.com (Proxmox) with ESMTPS id 6732B2B62C for ; Tue, 6 Apr 2021 11:03:49 +0200 (CEST) Received: from proxmox-new.maurer-it.com (localhost.localdomain [127.0.0.1]) by proxmox-new.maurer-it.com (Proxmox) with ESMTP id 3324241F1F for ; Tue, 6 Apr 2021 11:03:49 +0200 (CEST) From: Dominik Csapak To: pbs-devel@lists.proxmox.com Date: Tue, 6 Apr 2021 11:03:45 +0200 Message-Id: <20210406090347.27579-6-d.csapak@proxmox.com> X-Mailer: git-send-email 2.20.1 In-Reply-To: <20210406090347.27579-1-d.csapak@proxmox.com> References: <20210406090347.27579-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.169 Adjusted score from AWL reputation of From: address KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Subject: [pbs-devel] [PATCH proxmox-backup v3 5/7] server/rest: compress static files X-BeenThere: pbs-devel@lists.proxmox.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Proxmox Backup Server development discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Tue, 06 Apr 2021 09:04:24 -0000 compress them on the fly and refactor the size limit for chunking files Signed-off-by: Dominik Csapak --- src/server/rest.rs | 84 +++++++++++++++++++++++++++++++++------------- 1 file changed, 61 insertions(+), 23 deletions(-) diff --git a/src/server/rest.rs b/src/server/rest.rs index 61513e4b..07460125 100644 --- a/src/server/rest.rs +++ b/src/server/rest.rs @@ -40,6 +40,7 @@ use crate::auth_helpers::*; use crate::config::cached_user_info::CachedUserInfo; use crate::tools; use crate::tools::compression::{CompressionMethod, DeflateEncoder, Level}; +use crate::tools::AsyncReaderStream; use crate::tools::FileLogger; extern "C" { @@ -51,6 +52,7 @@ pub struct RestServer { } const MAX_URI_QUERY_LENGTH: usize = 3072; +const CHUNK_SIZE_LIMIT: u64 = 32 * 1024; impl RestServer { pub fn new(api_config: ApiConfig) -> Self { @@ -544,9 +546,11 @@ fn extension_to_content_type(filename: &Path) -> (&'static str, bool) { ("application/octet-stream", false) } -async fn simple_static_file_download(filename: PathBuf) -> Result, Error> { - let (content_type, _nocomp) = extension_to_content_type(&filename); - +async fn simple_static_file_download( + filename: PathBuf, + content_type: &'static str, + compression: Option, +) -> Result, Error> { use tokio::io::AsyncReadExt; let mut file = File::open(filename) @@ -554,46 +558,79 @@ async fn simple_static_file_download(filename: PathBuf) -> Result .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; let mut data: Vec = Vec::new(); - file.read_to_end(&mut data) - .await - .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?; - let mut response = Response::new(data.into()); + let mut response = match compression { + Some(CompressionMethod::Deflate) => { + let mut enc = DeflateEncoder::with_quality(data, Level::Fastest); + enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize).await?; + let mut response = Response::new(enc.into_inner().into()); + response.headers_mut().insert( + header::CONTENT_ENCODING, + CompressionMethod::Deflate.content_encoding(), + ); + response + } + None => { + file.read_to_end(&mut data) + .await + .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?; + Response::new(data.into()) + } + }; + response.headers_mut().insert( header::CONTENT_TYPE, header::HeaderValue::from_static(content_type), ); + Ok(response) } -async fn chuncked_static_file_download(filename: PathBuf) -> Result, Error> { - let (content_type, _nocomp) = extension_to_content_type(&filename); +async fn chuncked_static_file_download( + filename: PathBuf, + content_type: &'static str, + compression: Option, +) -> Result, Error> { + let mut resp = Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type); let file = File::open(filename) .await .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; - let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) - .map_ok(|bytes| bytes.freeze()); - let body = Body::wrap_stream(payload); + let body = match compression { + Some(CompressionMethod::Deflate) => { + resp = resp.header( + header::CONTENT_ENCODING, + CompressionMethod::Deflate.content_encoding(), + ); + Body::wrap_stream(DeflateEncoder::with_quality( + AsyncReaderStream::new(file), + Level::Fastest, + )) + } + None => Body::wrap_stream(AsyncReaderStream::new(file)), + }; - // FIXME: set other headers ? - Ok(Response::builder() - .status(StatusCode::OK) - .header(header::CONTENT_TYPE, content_type) - .body(body) - .unwrap()) + Ok(resp.body(body).unwrap()) } -async fn handle_static_file_download(filename: PathBuf) -> Result, Error> { +async fn handle_static_file_download( + filename: PathBuf, + compression: Option, +) -> Result, Error> { let metadata = tokio::fs::metadata(filename.clone()) .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err)) .await?; - if metadata.len() < 1024 * 32 { - simple_static_file_download(filename).await + let (content_type, nocomp) = extension_to_content_type(&filename); + let compression = if nocomp { None } else { compression }; + + if metadata.len() < CHUNK_SIZE_LIMIT { + simple_static_file_download(filename, content_type, compression).await } else { - chuncked_static_file_download(filename).await + chuncked_static_file_download(filename, content_type, compression).await } } @@ -764,7 +801,8 @@ async fn handle_request( } } else { let filename = api.find_alias(&components); - return handle_static_file_download(filename).await; + let compression = extract_compression_method(&parts.headers); + return handle_static_file_download(filename, compression).await; } } -- 2.20.1