From mboxrd@z Thu Jan  1 00:00:00 1970
Return-Path: <m.carrara@proxmox.com>
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 6482C9D95
 for <pbs-devel@lists.proxmox.com>; Mon, 28 Aug 2023 16:43:07 +0200 (CEST)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
 by firstgate.proxmox.com (Proxmox) with ESMTP id 444F51ED50
 for <pbs-devel@lists.proxmox.com>; Mon, 28 Aug 2023 16:42:37 +0200 (CEST)
Received: from proxmox-new.maurer-it.com (proxmox-new.maurer-it.com
 [94.136.29.106])
 (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
 for <pbs-devel@lists.proxmox.com>; Mon, 28 Aug 2023 16:42:35 +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 8FB7B47231
 for <pbs-devel@lists.proxmox.com>; Mon, 28 Aug 2023 16:42:35 +0200 (CEST)
From: Max Carrara <m.carrara@proxmox.com>
To: pbs-devel@lists.proxmox.com
Date: Mon, 28 Aug 2023 16:42:04 +0200
Message-Id: <20230828144204.3591503-3-m.carrara@proxmox.com>
X-Mailer: git-send-email 2.39.2
In-Reply-To: <20230828144204.3591503-1-m.carrara@proxmox.com>
References: <20230828144204.3591503-1-m.carrara@proxmox.com>
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
X-SPAM-LEVEL: Spam detection results:  0
 AWL -0.082 Adjusted score from AWL reputation of From: address
 BAYES_00                 -1.9 Bayes spam probability is 0 to 1%
 DMARC_MISSING             0.1 Missing DMARC policy
 KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment
 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] [RFC PATCH proxmox-backup 2/2] pxar-bin: Use async
 instead of sync extractor
X-BeenThere: pbs-devel@lists.proxmox.com
X-Mailman-Version: 2.1.29
Precedence: list
List-Id: Proxmox Backup Server development discussion
 <pbs-devel.lists.proxmox.com>
List-Unsubscribe: <https://lists.proxmox.com/cgi-bin/mailman/options/pbs-devel>, 
 <mailto:pbs-devel-request@lists.proxmox.com?subject=unsubscribe>
List-Archive: <http://lists.proxmox.com/pipermail/pbs-devel/>
List-Post: <mailto:pbs-devel@lists.proxmox.com>
List-Help: <mailto:pbs-devel-request@lists.proxmox.com?subject=help>
List-Subscribe: <https://lists.proxmox.com/cgi-bin/mailman/listinfo/pbs-devel>, 
 <mailto:pbs-devel-request@lists.proxmox.com?subject=subscribe>
X-List-Received-Date: Mon, 28 Aug 2023 14:43:07 -0000

This commit serves as an example of how the new `AsyncExtractor<T>`
may be used. The extraction options are created using the new
builder patterns as well.

In this case, the sync version can almost be directly swapped in
place with the async version.

Signed-off-by: Max Carrara <m.carrara@proxmox.com>
---
 pxar-bin/src/main.rs | 91 +++++++++++++++++++++++---------------------
 1 file changed, 47 insertions(+), 44 deletions(-)

diff --git a/pxar-bin/src/main.rs b/pxar-bin/src/main.rs
index bc044035..6dc7d375 100644
--- a/pxar-bin/src/main.rs
+++ b/pxar-bin/src/main.rs
@@ -12,30 +12,12 @@ use futures::select;
 use tokio::signal::unix::{signal, SignalKind};

 use pathpatterns::{MatchEntry, MatchType, PatternFlag};
-use pbs_client::pxar::{
-    format_single_line_entry, Flags, OverwriteFlags, PxarExtractOptions, ENCODER_MAX_ENTRIES,
-};
+use pbs_client::pxar::aio;
+use pbs_client::pxar::{format_single_line_entry, Flags, OverwriteFlags, ENCODER_MAX_ENTRIES};

 use proxmox_router::cli::*;
 use proxmox_schema::api;

-fn extract_archive_from_reader<R: std::io::Read>(
-    reader: &mut R,
-    target: &str,
-    feature_flags: Flags,
-    options: PxarExtractOptions,
-) -> Result<(), Error> {
-    pbs_client::pxar::extract_archive(
-        pxar::decoder::Decoder::from_std(reader)?,
-        Path::new(target),
-        feature_flags,
-        |path| {
-            log::debug!("{:?}", path);
-        },
-        options,
-    )
-}
-
 #[api(
     input: {
         properties: {
@@ -124,7 +106,7 @@ fn extract_archive_from_reader<R: std::io::Read>(
 )]
 /// Extract an archive.
 #[allow(clippy::too_many_arguments)]
-fn extract_archive(
+async fn extract_archive(
     archive: String,
     pattern: Option<Vec<String>>,
     target: Option<String>,
@@ -193,38 +175,59 @@ fn extract_archive(

     let extract_match_default = match_list.is_empty();

+    // Use the new options builder for convenienve
+    let mut options_builder = aio::PxarExtractOptions::builder(PathBuf::from(target));
+
+    options_builder
+        .feature_flags(feature_flags)
+        .overwrite_flags(overwrite_flags)
+        .allow_existing_dirs(allow_existing_dirs)
+        .default_match(extract_match_default)
+        .push_match_list(match_list);
+
+    // The builder makes it easier to conditionally configure the extractor
     let was_ok = Arc::new(AtomicBool::new(true));
-    let on_error = if strict {
-        // by default errors are propagated up
-        None
-    } else {
+    if strict {
         let was_ok = Arc::clone(&was_ok);
-        // otherwise we want to log them but not act on them
-        Some(Box::new(move |err| {
+        // log errors but don't act upon them
+
+        let error_handler = Box::new(move |error| {
             was_ok.store(false, Ordering::Release);
-            log::error!("error: {}", err);
+            log::error!("error: {}", error);
             Ok(())
-        })
-            as Box<dyn FnMut(Error) -> Result<(), Error> + Send>)
-    };
+        });

-    let options = PxarExtractOptions {
-        match_list: &match_list,
-        allow_existing_dirs,
-        overwrite_flags,
-        extract_match_default,
-        on_error,
-    };
+        options_builder.error_handler(error_handler);
+    }
+
+    let options = options_builder.build();

     if archive == "-" {
-        let stdin = std::io::stdin();
-        let mut reader = stdin.lock();
-        extract_archive_from_reader(&mut reader, target, feature_flags, options)?;
+        let stdin = tokio::io::stdin();
+        let decoder =
+            pxar::decoder::aio::Decoder::from_tokio(tokio::io::BufReader::new(stdin)).await?;
+        let mut extractor = aio::AsyncExtractor::new(decoder, options);
+
+        while let Some(result) = extractor.next().await {
+            if let Err(error) = result {
+                bail!(
+                    "encountered unexpected error during extraction:\n{:?}",
+                    error
+                )
+            }
+        }
     } else {
         log::debug!("PXAR extract: {}", archive);
-        let file = std::fs::File::open(archive)?;
-        let mut reader = std::io::BufReader::new(file);
-        extract_archive_from_reader(&mut reader, target, feature_flags, options)?;
+
+        let mut extractor = aio::AsyncExtractor::with_file(archive, options).await?;
+        while let Some(result) = extractor.next().await {
+            if let Err(error) = result {
+                bail!(
+                    "encountered unexpected error during extraction:\n{:?}",
+                    error
+                )
+            }
+        }
     }

     if !was_ok.load(Ordering::Acquire) {
--
2.39.2