remove file if write to update file fails

This commit is contained in:
marin postma 2021-06-23 14:45:26 +02:00
parent f62779671b
commit b000ae7614
No known key found for this signature in database
GPG Key ID: 6088B7721C3E39F9

View File

@ -122,7 +122,7 @@ where
&self, &self,
uuid: Uuid, uuid: Uuid,
meta: UpdateMeta, meta: UpdateMeta,
mut payload: mpsc::Receiver<PayloadData<D>>, payload: mpsc::Receiver<PayloadData<D>>,
) -> Result<UpdateStatus> { ) -> Result<UpdateStatus> {
let file_path = match meta { let file_path = match meta {
UpdateMeta::DocumentsAddition { .. } => { UpdateMeta::DocumentsAddition { .. } => {
@ -137,23 +137,37 @@ where
.open(&path) .open(&path)
.await?; .await?;
async fn write_to_file<D>(file: &mut fs::File, mut payload: mpsc::Receiver<PayloadData<D>>) -> Result<usize>
where
D: AsRef<[u8]> + Sized + 'static,
{
let mut file_len = 0; let mut file_len = 0;
while let Some(bytes) = payload.recv().await { while let Some(bytes) = payload.recv().await {
let bytes = bytes?; let bytes = bytes?;
file_len += bytes.as_ref().len(); file_len += bytes.as_ref().len();
file.write_all(bytes.as_ref()).await?; file.write_all(bytes.as_ref()).await?;
} }
Ok(file_len)
}
if file_len != 0 { let file_len = write_to_file(&mut file, payload).await;
match file_len {
Ok(len) if len > 0 => {
file.flush().await?; file.flush().await?;
let file = file.into_std().await; let file = file.into_std().await;
Some((file, update_file_id)) Some((file, update_file_id))
} else { }
// empty update, delete the empty file. Err(e) => {
fs::remove_file(&path).await?;
return Err(e)
}
_ => {
fs::remove_file(&path).await?; fs::remove_file(&path).await?;
None None
} }
} }
}
_ => None, _ => None,
}; };