Skip to content

Wp/ updated delete file to use pk as filename #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 54 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
25eef4c
WP/skip files if exists on write
Mar 13, 2023
61b2edc
WP/check_catalog_exists [test]
Mar 14, 2023
eddf0d5
WP/block write_read [test] temporarily
Mar 14, 2023
07e5283
WP/delete-file-blake3hash-http-route
rustchain64 Mar 14, 2023
227ed37
WP/delete-file-format-update
rustchain64 Mar 14, 2023
7d85f6b
WP/delete-file-fix-clippy-issues
rustchain64 Mar 14, 2023
e148dd9
WP/18-slices-blake3_hash-slice_index-slice_range
rustchain64 Mar 15, 2023
8f30773
WP/18-slice-blake3_hash-slice-prototype
rustchain64 Apr 5, 2023
767156c
WP/18-slice-implement-http-get-slice
rustchain64 Apr 5, 2023
f02bc40
WP/18-slice-blake3_hash-slice-dev
rustchain64 Apr 6, 2023
ab317e4
WP/18-slice-blacke3-hash-slice-test-error-file-108
rustchain64 Apr 8, 2023
908e39d
WP/18-slice-black3-hash-Encoded
rustchain64 Apr 8, 2023
5f6c4c2
WP/18-slice-black3-hash-debug-stage
rustchain64 Apr 10, 2023
ba92b5d
WP/18-slice-black3-HT-to-debug
rustchain64 Apr 10, 2023
684bb7c
WP/18-slicke-blake3_hash-stash
rustchain64 Apr 11, 2023
fc8634e
WP/18-slice-blake3_hash-analyze-test
rustchain64 Apr 12, 2023
29a31b4
WP/18-slice-blake3-resolve-cargo-toml
rustchain64 Apr 12, 2023
e50a2d5
WP/18-slice-blake3-clippy
rustchain64 Apr 12, 2023
6b77b22
WP/18-slice-blake3-read_slices
rustchain64 Apr 12, 2023
657c120
WP/18-slice-blake3-test-update
rustchain64 Apr 12, 2023
50dc264
WP/18-slice-blake3-unneeded-return
rustchain64 Apr 12, 2023
dedb85d
WP/18-slice-blake3-http-get-slice
rustchain64 Apr 12, 2023
13134f7
WP/upload-get-last-hash
rustchain64 Apr 19, 2023
2f2e403
WP/upload-get-last-hash-debug
rustchain64 Apr 21, 2023
cbf7e9b
WP/upload-get-last-hash-cleanup
rustchain64 Apr 25, 2023
990420d
WP/upload-get-last-hash-test-to-pass
rustchain64 Apr 25, 2023
eff5232
WP/upload-get-last-hash-file-read-test
rustchain64 Apr 25, 2023
d32eeca
WP/upload-get-last-hash-implement-catalog-exists
rustchain64 Apr 25, 2023
5b9a950
WP/upload-get-last-hash-revert-tests
rustchain64 Apr 25, 2023
91ae1b9
WP/upload-get-last-hash-remove-file-write-local
rustchain64 Apr 25, 2023
30f7878
WP/upload-get-last-hash-clippy
rustchain64 Apr 25, 2023
a7fc00a
WP/upload-get-last-hash-path-exists
rustchain64 Apr 26, 2023
01ba0f7
WP/upload-get-last-debug-binary-files
rustchain64 Apr 29, 2023
8e88ead
WP/upload-get-last-point-cargo-toml
rustchain64 Apr 29, 2023
9e3a446
WP/upload-get-hash-clippy
rustchain64 Apr 29, 2023
8849101
Implement HTTP body streaming version of post_file.
cryptoquick Apr 30, 2023
ea0c994
Refactor streaming interface format. Fix tests.
cryptoquick Apr 30, 2023
4629aa2
Reduce number of files created in test by increasing chunk size to 1MB.
cryptoquick Apr 30, 2023
3e9949d
Fix check catalog_exists test. Cleanup unused libraries.
cryptoquick Apr 30, 2023
d1f9216
Log node public key in config. Correct Error Message in fs backend. R…
rustchain64 May 1, 2023
961f663
WP/upload-last-hash-merger-with-stream-post-file
rustchain64 May 2, 2023
730f208
upload-get-lash-hash fixes. (#38)
cryptoquick May 4, 2023
7188500
Merge main.
cryptoquick May 4, 2023
7db7d4d
temp stash
rustchain64 May 4, 2023
4e21025
update delete
rustchain64 May 4, 2023
642acb4
delete across volumes
rustchain64 May 4, 2023
8637f02
deleted files counter
rustchain64 May 5, 2023
04d53bf
comments
rustchain64 May 5, 2023
04ef77f
handle HT comments
rustchain64 May 8, 2023
dd5fa8c
updated delete file for file_name
rustchain64 May 8, 2023
c675bd0
remove slice function
rustchain64 May 8, 2023
18fc5df
fix clippy error
rustchain64 May 8, 2023
f651742
read_slices backup
rustchain64 May 8, 2023
c4329ad
backup only
rustchain64 May 9, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
313 changes: 179 additions & 134 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion src/backend.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod fs;
// pub mod task;
111 changes: 47 additions & 64 deletions src/backend/fs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::{
fs::{self, OpenOptions},
io::{self, Read, Seek, Write},
path::{Path, PathBuf},
io::{Read, Seek, Write},
pin::Pin,
sync::Arc,
};
Expand Down Expand Up @@ -131,6 +130,7 @@ pub async fn write_catalog(
segment_hashes: &[BaoHash],
) -> Result<()> {
debug!("Write catalog");

let contents: Vec<u8> = segment_hashes
.iter()
.flat_map(|bao_hash| bao_hash.to_bytes())
Expand Down Expand Up @@ -189,7 +189,7 @@ pub fn read_file(pk: &Secp256k1PubKey, blake3_hash: &Blake3Hash) -> Result<FileS
0,
&write_pk_str,
SEGMENT_DIR,
&format!("{}.c{}", segment_hash, NODE_FORMAT),
&format!("{segment_hash}.c{NODE_FORMAT}"),
)?;

let mut chunk_file = OpenOptions::new().read(true).open(chunk_path)?;
Expand Down Expand Up @@ -276,73 +276,56 @@ pub fn read_catalog(write_pk_str: &str, file_hash: &Blake3Hash) -> Result<Vec<Ba
Ok(bao_hashes)
}

#[allow(unused_variables)]
pub fn delete_file(pk: Secp256k1PubKey, file_bytes: &[u8]) -> Result<()> {
let pk_bytes = pk.to_bytes();
let (x_only_pk, _) = pk.into_inner().x_only_public_key();
pub fn read_slice(
pk: &Secp256k1PubKey,
file_hash: &Blake3Hash,
slice_start: usize,
slice_len: usize,
) -> Result<Vec<BaoHash>> {
trace!("Create a shared secret using ECDH");
let ss = node_shared_secret(&pk.into_inner())?.secret_bytes();
let write_pk = PublicKey::from_secret_key_global(&SecretKey::from_slice(&ss)?);
let write_pk_str = write_pk.to_string();

let file_hash = Blake3Hash(blake3::keyed_hash(&x_only_pk.serialize(), file_bytes));
trace!(">>>>>file_hash:: {}", file_hash);
let path = file_path(0, &write_pk_str, CATALOG_DIR, &file_hash.to_string())?;

for vol in &SYS_CFG.volumes {
let seg_file = &vol.path.join(SEGMENT_DIR).join(file_hash.to_string());
let seg_dir = &vol.path.join(SEGMENT_DIR);
remove_dir_contents(seg_dir, seg_file.to_path_buf()).unwrap();
}
trace!("Read catalog at {path:?}");
let mut catalog_file = OpenOptions::new().read(true).open(path)?;

for vol in &SYS_CFG.volumes {
let cat_path = &vol.path.join(CATALOG_DIR).join(file_hash.to_string());
let cat = &vol.path.join(CATALOG_DIR);
remove_dir_catalogs(cat.to_path_buf(), cat_path.to_path_buf()).unwrap();
}
Ok(())
}
let mut bytes = vec![];
catalog_file.read_to_end(&mut bytes)?;

#[allow(unused_variables)]
fn remove_dir_contents<P: AsRef<Path>>(path: P, seg_file: PathBuf) -> io::Result<()> {
trace!(">>> remove_Segment_contents");
for entry in fs::read_dir(path)? {
trace!("Delete Segment File at {:?}", entry);
fs::remove_file(entry?.path())?;
}
Ok(())
trace!("Read catalog at {:?}", catalog_file);
trace!(" )))) Read catalog BYTES len() {:?}", bytes.len());

// GET RANGE ex: &bytes[1..4]);
let slice_end = slice_start + slice_len;
trace!(" {:?}", &bytes[slice_start..slice_end]);

let bao_hashes = bytes
.chunks_exact(bao::HASH_SIZE)
.map(BaoHash::try_from)
.collect::<Result<Vec<BaoHash>>>()?;

Ok(bao_hashes)
}

#[allow(unused_variables)]
fn remove_dir_catalogs(path: PathBuf, file: PathBuf) -> io::Result<()> {
for entry in fs::read_dir(path)? {
trace!("Delete CATALOG File at {:?}", entry);
fs::remove_file(entry?.path())?;
pub async fn delete_file(pk: &Secp256k1PubKey) -> Result<()> {
let ss = node_shared_secret(&pk.into_inner())?.secret_bytes();
let write_pk = PublicKey::from_secret_key_global(&SecretKey::from_slice(&ss)?);
let write_pk_str = write_pk.to_string();
trace!("WRITE_PK_STR: {}", write_pk_str);

for vol in &SYS_CFG.volumes {
trace!("VOLUME PATH: {:?}", vol.path);

let pk_path = vol.path.join(&write_pk_str);
let is_removed = fs::remove_dir_all(pk_path).is_ok();
trace!(
"VOLUME_{:?} WRITE_PK_STR REMOVED {:?}: ",
vol.path,
is_removed
);
}
Ok(())
}

// fn remove_dir_segements<P: AsRef<Path>>(path: P, seg_file: PathBuf) -> io::Result<()> {
// trace!(">>> remove_Segment_contents");
// for entry in fs::read_dir(path)? {
// let entry = entry?;
// trace!("ENTRY Delete SEGMENT File at {:?}", entry);

// match &entry {
// seg_file => {
// fs::remove_file(seg_file.path())?;
// trace!("Delete Segment File at {:?}", seg_file);
// }
// }
// }
// Ok(())
// }

// fn remove_dir_catalogs(path: PathBuf, file: PathBuf) -> io::Result<()> {
// for entry in fs::read_dir(path)? {
// let entry = entry?;
// trace!("ENTRY Delete CATALOG File at {:?}", entry);
// match &entry {
// file => {
// fs::remove_file(file.path())?;
// trace!("FILE MATCH Delete CATALOG File at {:?}", file);
// }
// }
// }
// Ok(())
// }
58 changes: 50 additions & 8 deletions src/frontend/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{net::SocketAddr, str::FromStr};
use anyhow::Result;
use axum::{
body::StreamBody,
extract::{BodyStream, Path},
extract::{BodyStream, Path, Query},
http::StatusCode,
response::{IntoResponse, Response},
routing::{delete, get, post},
Expand All @@ -16,11 +16,33 @@ use secp256k1::PublicKey;
use tower_http::cors::CorsLayer;

use crate::{
backend::fs::{delete_file, read_file, write_file, FileStream},
backend::fs::{delete_file, read_file, read_slice, write_file, FileStream},
config::{node_shared_secret, SYS_CFG},
prelude::*,
};

struct FileSlice {
//#[serde(default, deserialize_with = "empty_string_as_none")]
pk: String,
black3_hash: String,
index_start: usize,
range_end: usize,
}

/// Serde deserialization decorator to map empty Strings to None,
// fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
// where
// D: Deserializer<'de>,
// T: FromStr,
// T::Err: fmt::Display,
// {
// let opt = Option::<String>::deserialize(de)?;
// match opt.as_deref() {
// None | Some("") => Ok(None),
// Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some),
// }
// }

#[axum_macros::debug_handler]
async fn post_file(
Path(pk): Path<String>,
Expand Down Expand Up @@ -69,13 +91,32 @@ async fn get_file(
Ok((StatusCode::OK, StreamBody::new(file_stream)))
}

// #[axum_macros::debug_handler]
// //async fn get_slice(Query(my_params): Query<FileSlice>) -> Result<impl IntoResponse, AppError> {
// async fn get_slice(Query(my_params): Query<FileSlice>) -> Result<impl IntoResponse, AppError> {
// // let pk = my_params.black3_hash;
// // let blake3_hash = my_params.black3_hash;
// // let start_index = my_params.index_start;
// // let range_end = my_params.range_end;
// // debug!("my_params :: blake {:?} ", my_params.black3_hash);
// // debug!("my_params :: start {:?} ", my_params.index_start);
// // debug!("my_params :: end {:?} ", my_params.range_end);
// let file_stream = read_slices(
// my_params.pk,
// my_params.black3_hash,
// my_params.index_start,
// my_params.range_end,
// )
// .await?;
// Ok((StatusCode::OK, StreamBody::new(file_stream)))
// }

#[axum_macros::debug_handler]
async fn remove_file(
Path((pk, blake3_hash)): Path<(String, String)>,
) -> Result<impl IntoResponse, AppError> {
async fn remove_file(Path(pk): Path<String>) -> Result<impl IntoResponse, AppError> {
let pk = Secp256k1PubKey::try_from(pk.as_str())?;
delete_file(pk, blake3_hash.as_bytes())?;
Ok((StatusCode::OK, blake3_hash))
let del = delete_file(&pk).await.is_ok();

Ok((StatusCode::OK, del.to_string()))
}

async fn key(Path(pk): Path<String>) -> Result<impl IntoResponse, AppError> {
Expand All @@ -89,9 +130,10 @@ async fn key(Path(pk): Path<String>) -> Result<impl IntoResponse, AppError> {

pub async fn start() -> Result<()> {
let app = Router::new()
.route("/remove/:pk/:blake3_hash", delete(remove_file))
.route("/remove/:blake3_hash", delete(remove_file))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You removed the pk... We'll need this to be passed for the changes I'm making in #39. I've trimmed that PR down so we can get that merged and you can use that to make sure file deletion is namespaced by pk.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, your changes address that.

.route("/store/:pk", post(post_file))
.route("/retrieve/:pk/:blake3_hash", get(get_file))
// .route("/slice/", get(get_slice))
.route("/key/:pk", get(key))
// .route("/catalog/:blake3_hash", get(get_catalog))
// .route("/raw/:bao_hash", get(get_raw))
Expand Down
10 changes: 10 additions & 0 deletions src/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ impl fmt::Display for Blake3Hash {
}
}

impl TryFrom<&[u8]> for Blake3Hash {
type Error = Error;

fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let mut hash = [0_u8; 32];
hash.copy_from_slice(&value[0..32]);
Ok(Self(blake3::Hash::try_from(hash)?))
}
}

pub struct BaoHash(pub bao::Hash);

impl BaoHash {
Expand Down
Binary file removed tests/.DS_Store
Binary file not shown.
Loading