use bytes::Buf;
use fastpool::bounded;
use futures::AsyncWrite;
use futures::AsyncWriteExt;
use super::core::Manager;
use super::err::format_ftp_error;
use opendal_core::raw::*;
use opendal_core::*;
pub struct FtpWriter {
target_path: String,
tmp_path: Option<String>,
ftp_stream: bounded::Object<Manager>,
data_stream: Option<Box<dyn AsyncWrite + Sync + Send + Unpin + 'static>>,
}
unsafe impl Sync for FtpWriter {}
impl FtpWriter {
pub fn new(
ftp_stream: bounded::Object<Manager>,
target_path: String,
tmp_path: Option<String>,
) -> Self {
FtpWriter {
target_path,
tmp_path,
ftp_stream,
data_stream: None,
}
}
}
impl oio::Write for FtpWriter {
async fn write(&mut self, mut bs: Buffer) -> Result<()> {
let path = if let Some(tmp_path) = &self.tmp_path {
tmp_path
} else {
&self.target_path
};
if self.data_stream.is_none() {
self.data_stream = Some(Box::new(
self.ftp_stream
.append_with_stream(path)
.await
.map_err(format_ftp_error)?,
));
}
while bs.has_remaining() {
let n = self
.data_stream
.as_mut()
.unwrap()
.write(bs.chunk())
.await
.map_err(|err| {
Error::new(ErrorKind::Unexpected, "copy from ftp stream").set_source(err)
})?;
bs.advance(n);
}
Ok(())
}
async fn close(&mut self) -> Result<Metadata> {
let data_stream = self.data_stream.take();
if let Some(mut data_stream) = data_stream {
data_stream.flush().await.map_err(|err| {
Error::new(ErrorKind::Unexpected, "flush data stream failed").set_source(err)
})?;
self.ftp_stream
.finalize_put_stream(data_stream)
.await
.map_err(format_ftp_error)?;
if let Some(tmp_path) = &self.tmp_path {
self.ftp_stream
.rename(tmp_path, &self.target_path)
.await
.map_err(format_ftp_error)?;
}
}
Ok(Metadata::default())
}
async fn abort(&mut self) -> Result<()> {
Err(Error::new(
ErrorKind::Unsupported,
"FtpWriter doesn't support abort",
))
}
}