Added file updates

This commit is contained in:
StNicolay committed 2024-07-27 19:20:07 +03:00
1 parent e8114c515d
commit 3ed30f0d9b
6 files changed
+117 -28

No files matched your search

+42 -1
View File
@@ -4,7 +4,14 @@ use std::{
sync::Arc,
};
use tokio::fs;
use axum::body::Bytes;
use futures::{Stream, StreamExt};
use sha2::Digest as _;
use tokio::{
fs,
io::{AsyncWrite, AsyncWriteExt, BufWriter},
};
use tokio_util::io::StreamReader;
use uuid::Uuid;
#[derive(Clone)]
@@ -63,6 +70,14 @@ impl FileStorage {
.map_err(Into::into)
}
pub async fn write(&self, file_id: Uuid) -> anyhow::Result<Option<impl tokio::io::AsyncWrite>> {
match fs::File::create(self.path_for_file(file_id)).await {
Ok(file) => Ok(Some(file)),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
pub async fn delete(&self, file_id: Uuid) -> anyhow::Result<bool> {
match fs::remove_file(self.path_for_file(file_id)).await {
Ok(()) => Ok(true),
@@ -70,4 +85,30 @@ impl FileStorage {
Err(err) => Err(err.into()),
}
}
pub async fn write_to_file<F, S, E>(file: F, stream: S) -> io::Result<(Vec<u8>, i64)>
where
F: AsyncWrite + Unpin,
S: Stream<Item = Result<Bytes, E>> + Unpin,
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
const BUF_CAP: usize = 64 * 1024 * 1024; // 64 MiB
let mut hash = sha2::Sha512::new();
let mut size: i64 = 0;
let stream = stream.map(|value| {
let bytes = value.map_err(io::Error::other)?;
hash.update(&bytes);
size = i64::try_from(bytes.len())
.ok()
.and_then(|part_size| size.checked_add(part_size))
.ok_or_else(|| io::Error::other(anyhow::anyhow!("Size calculation overflow")))?;
io::Result::Ok(bytes)
});
let mut reader = StreamReader::new(stream);
let mut writer = BufWriter::with_capacity(BUF_CAP, file);
tokio::io::copy_buf(&mut reader, &mut writer).await?;
writer.flush().await?;
let hash = hash.finalize().to_vec();
Ok((hash, size))
}
}