From: Dominik Csapak <d.csapak@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [PATCH proxmox-backup v2 2/3] tools: add AsyncChannelWriter
Date: Tue, 20 Oct 2020 16:45:01 +0200 [thread overview]
Message-ID: <20201020144502.13725-2-d.csapak@proxmox.com> (raw)
In-Reply-To: <20201020144502.13725-1-d.csapak@proxmox.com>
similar to StdChannelWriter, but implements AsyncWrite and sends
to a tokio::sync::mpsc::Sender
Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
---
new in v2
src/tools.rs | 4 ++
src/tools/async_channel_writer.rs | 107 ++++++++++++++++++++++++++++++
2 files changed, 111 insertions(+)
create mode 100644 src/tools/async_channel_writer.rs
diff --git a/src/tools.rs b/src/tools.rs
index 5a9f020a..22d6c344 100644
--- a/src/tools.rs
+++ b/src/tools.rs
@@ -44,6 +44,10 @@ pub use parallel_handler::*;
mod wrapped_reader_stream;
pub use wrapped_reader_stream::*;
+mod async_channel_writer;
+pub use async_channel_writer::*;
+
+
mod std_channel_writer;
pub use std_channel_writer::*;
diff --git a/src/tools/async_channel_writer.rs b/src/tools/async_channel_writer.rs
new file mode 100644
index 00000000..fcd360ce
--- /dev/null
+++ b/src/tools/async_channel_writer.rs
@@ -0,0 +1,107 @@
+use std::future::Future;
+use std::io;
+use std::pin::Pin;
+use std::task::{Context, Poll};
+
+use anyhow::{Error, Result};
+use futures::{future::FutureExt, ready};
+use tokio::io::AsyncWrite;
+use tokio::sync::mpsc::Sender;
+
+use proxmox::io_format_err;
+use proxmox::sys::error::io_err_other;
+
+/// Wrapper around tokio::sync::mpsc::Sender, which implements Write
+pub struct AsyncChannelWriter {
+ sender: Option<Sender<Result<Vec<u8>, Error>>>,
+ buf: Vec<u8>,
+ buf_size: usize,
+ state: WriterState,
+}
+
+type SendResult = io::Result<Sender<Result<Vec<u8>>>>;
+
+enum WriterState {
+ Ready,
+ Sending(Pin<Box<dyn Future<Output = SendResult> + Send + 'static>>),
+}
+
+impl AsyncChannelWriter {
+ pub fn new(sender: Sender<Result<Vec<u8>, Error>>, buf_size: usize) -> Self {
+ Self {
+ sender: Some(sender),
+ buf: Vec::with_capacity(buf_size),
+ buf_size,
+ state: WriterState::Ready,
+ }
+ }
+
+ fn poll_write_impl(
+ &mut self,
+ cx: &mut Context,
+ buf: &[u8],
+ flush: bool,
+ ) -> Poll<io::Result<usize>> {
+ loop {
+ match &mut self.state {
+ WriterState::Ready => {
+ if flush {
+ if self.buf.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+ } else {
+ let free_size = self.buf_size - self.buf.len();
+ if free_size > buf.len() || self.buf.is_empty() {
+ let count = free_size.min(buf.len());
+ self.buf.extend_from_slice(&buf[..count]);
+ return Poll::Ready(Ok(count));
+ }
+ }
+
+ let mut sender = match self.sender.take() {
+ Some(sender) => sender,
+ None => return Poll::Ready(Err(io_err_other("no sender"))),
+ };
+
+ let data = self.buf.to_vec();
+ let future = async move {
+ sender
+ .send(Ok(data))
+ .await
+ .map(move |_| sender)
+ .map_err(|err| io_format_err!("could not send: {}", err))
+ };
+
+ self.buf.clear();
+ self.state = WriterState::Sending(future.boxed());
+ }
+ WriterState::Sending(ref mut future) => match ready!(future.as_mut().poll(cx)) {
+ Ok(sender) => {
+ self.sender = Some(sender);
+ self.state = WriterState::Ready;
+ }
+ Err(err) => return Poll::Ready(Err(err)),
+ },
+ }
+ }
+ }
+}
+
+impl AsyncWrite for AsyncChannelWriter {
+ fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
+ let this = self.get_mut();
+ this.poll_write_impl(cx, buf, false)
+ }
+
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
+ let this = self.get_mut();
+ match ready!(this.poll_write_impl(cx, &[], true)) {
+ Ok(_) => Poll::Ready(Ok(())),
+ Err(err) => Poll::Ready(Err(err)),
+ }
+ }
+
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
+ self.poll_flush(cx)
+ }
+}
--
2.20.1
next prev parent reply other threads:[~2020-10-20 14:45 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
2020-10-20 14:45 [pbs-devel] [PATCH proxmox-backup v2 1/3] tools: add zip module Dominik Csapak
2020-10-20 14:45 ` Dominik Csapak [this message]
2020-10-20 14:45 ` [pbs-devel] [PATCH proxmox-backup v2 3/3] api2/admin/datastore/pxar_file_download: download directory as zip Dominik Csapak
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20201020144502.13725-2-d.csapak@proxmox.com \
--to=d.csapak@proxmox.com \
--cc=pbs-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox