creating new items now works

This commit is contained in:
Sebastian Moser
2022-10-13 19:10:07 +02:00
parent f18667b5b3
commit b37250ce43
5 changed files with 79 additions and 38 deletions

View File

@@ -134,7 +134,7 @@ async fn warp_server(mize_folder: String) {
let answer = fs::read_to_string("/home/sebastian/work/mize/js-client/src/main.js").unwrap(); let answer = fs::read_to_string("/home/sebastian/work/mize/js-client/src/main.js").unwrap();
warp::http::Response::builder().header("content-type", "application/javascript").body(answer) warp::http::Response::builder().header("content-type", "application/javascript").body(answer)
}); });
let defuatl_route = warp::path::end().map(||{ let defuatl_route = warp::path::full().map(|path|{
//normally should be included in the binary, but for developing just gonna read the file //normally should be included in the binary, but for developing just gonna read the file
//so I don't have to recompile all the time //so I don't have to recompile all the time
//let answer = include_str!("../js-client/src/main.html"); //let answer = include_str!("../js-client/src/main.html");
@@ -144,11 +144,12 @@ async fn warp_server(mize_folder: String) {
//let routes = warp::get().and(socket_route).or(render_route).or(file_route).map(move |hi| "default"); //let routes = warp::get().and(socket_route).or(render_route).or(file_route).map(move |hi| "default");
let routes = warp::get().and( let routes = warp::get().and(
defuatl_route
.or(render_route) render_route
.or(file_route) .or(file_route)
.or(socket_route) .or(socket_route)
.or(main_route), .or(main_route)
.or(defuatl_route)
//.or(sum) //.or(sum)
//.or(times), //.or(times),
); );
@@ -178,12 +179,12 @@ async fn handle_socket_connection(
let itemstore = &*itemstore_clone.lock().await; let itemstore = &*itemstore_clone.lock().await;
match handle_mize_message(msg.clone().into_bytes(), itemstore).await { match handle_mize_message(msg.clone().into_bytes(), itemstore).await {
Response::One(response) => { Response::One(response) => {
client_tx.send(Ok(msg)).unwrap() client_tx.send(Ok(Message::binary(response.clone()))).unwrap()
}, },
Response::All(response) => { Response::All(response) => {
let clients = clients_clone.lock().await; let clients = clients_clone.lock().await;
for client in &clients[..] { for client in &clients[..] {
client.tx.send(Ok(msg.clone())); client.tx.send(Ok(Message::binary(response.clone())));
} }
drop(clients); drop(clients);
}, },

View File

@@ -12,63 +12,68 @@ pub type Item = Vec<[Vec<u8>; 2]>;
impl Itemstore { impl Itemstore {
pub async fn new(path: String) -> Itemstore { pub async fn new(path: String) -> Itemstore {
let ds = Datastore::new(&(String::from("file://") + &path[..] + "/db")[..]).await.expect("Could not open database"); let ds = Datastore::new(&(String::from("file://") + &path[..] + "/db")[..]).await.expect("Could not open database");
println!("in new fn");
let mut tr = ds.transaction(true, false).await.expect("creation of transaction failed"); let mut tr = ds.transaction(true, false).await.expect("creation of transaction failed");
match tr.get(vec!('0' as u8)).await { match tr.get(vec!('0' as u8)).await {
Ok(Some(val)) => println!("item 0 already created"), Ok(Some(val)) => println!("item 0 already created"),
Ok(None) => { Ok(None) => {
let init = vec!("num_of_items".as_bytes().to_vec(), "next_free_id".as_bytes().to_vec()); let init = vec!["num_of_items".as_bytes().to_vec(), "next_free_id".as_bytes().to_vec()];
tr.set("0".to_string().into_bytes(), encode(init)).await; tr.set("0".to_string().into_bytes(), encode(init)).await;
tr.set("0:num_of_items".to_string().into_bytes(), vec!('1' as u8)).await; let one: u64 = 1;
tr.set("0:next_free_id".to_string().into_bytes(), vec!('1' as u8)).await; let zero: u64 = 0;
tr.commit().await; tr.set("0:num_of_items".to_string().into_bytes(), one.to_be_bytes()).await;
tr.set("0:next_free_id".to_string().into_bytes(), one.to_be_bytes()).await;
tr.set("0:_commit".to_string().into_bytes(), zero.to_be_bytes()).await;
tr.set("0:_type".to_string().into_bytes(), "mize-main".as_bytes().to_vec()).await;
tr.commit().await.expect("error commiting transaction in new function");
}, },
Err(e) => println!("Error while getting item index with id 0: {}", e) Err(e) => println!("Error while getting item index with id 0: {}", e)
}; };
return Itemstore {db:ds}; return Itemstore {db:ds};
} }
pub async fn create(&self, item: Item) -> u64 { pub async fn create(&self, item: Item) -> u64 {
let mut tr = self.db.transaction(true, true).await.expect("creation of transaction failed");
let mut tr = self.db.transaction(true, false).await.expect("creation of transaction failed");
let id = tr.get("0:next_free_id").await let id = tr.get("0:next_free_id").await
.expect("no item with id 0 when there definetly should be one") .expect("no item with id 0 when there definetly should be one")
.expect("error reading item 0 from db"); .expect("error reading item 0 from db");
let id_u64 = u64::from_be_bytes(id.clone().try_into().unwrap());
let mut keys: Vec<Vec<u8>> = Vec::new(); let mut keys: Vec<Vec<u8>> = Vec::new();
//set id:_commit //set id:_commit
let mut key = id.clone(); let key = format!("{}:_commit", id_u64).into_bytes();
key.extend(":_commit".to_string().into_bytes()); tr.set(key.clone(), vec![0,0,0,0,0,0,0,0]).await;
tr.set(key.clone(), vec![0,0,0,0,0,0,0,0]); keys.push("_commit".to_owned().into_bytes());
keys.push(key);
for field in item { for field in item {
let mut key = id.clone(); let mut key = format!("{}:", id_u64).into_bytes();
key.push(':' as u8);
key.extend(field[0].clone()); key.extend(field[0].clone());
let val = field[1].clone();
keys.push(field[0].clone()); keys.push(field[0].clone());
let val = field[1].clone();
tr.set(key, val).await; tr.set(key, val).await;
} }
tr.set(id.clone(), encode(keys)).await; tr.set(format!("{}", id_u64), encode(keys)).await;
//increment 0:number_of_items by 1 //increment 0:number_of_items by 1
let num = tr.get("0:num_of_items".to_string().into_bytes()).await let num = tr.get("0:num_of_items".to_string().into_bytes()).await
.expect("error getting \"0:num_of_items\"") .expect("error getting \"0:num_of_items\"")
.expect("error reading item 0 from db"); .expect("error reading item 0 from db");
let mut num_u64 = u64::from_be_bytes([num[0], num[1], num[2], num[3], num[4], num[5], num[6], num[7]]) +1; let mut num_u64 = u64::from_be_bytes([num[0], num[1], num[2], num[3], num[4], num[5], num[6], num[7]]) +1;
tr.set("0:num_of_items".to_string().into_bytes(), num); tr.set("0:num_of_items".to_string().into_bytes(), num_u64.to_be_bytes()).await;
//imcrement next_free_id by 1 //imcrement next_free_id by 1
let num = tr.get("0:next_free_id".to_string().into_bytes()).await let num = tr.get("0:next_free_id".to_string().into_bytes()).await
.expect("error getting \"0:next_free_id\"") .expect("error getting \"0:next_free_id\"")
.expect("error reading item 0 from db"); .expect("error reading item 0 from db");
let mut num_u64 = u64::from_be_bytes([num[0], num[1], num[2], num[3], num[4], num[5], num[6], num[7]]) +1; let mut num_u64 = u64::from_be_bytes([num[0], num[1], num[2], num[3], num[4], num[5], num[6], num[7]]) +1;
tr.set("0:next_free_id".to_string().into_bytes(), num); tr.set("0:next_free_id".to_string().into_bytes(), num_u64.to_be_bytes()).await;
tr.commit().await; let res = tr.commit().await.expect("error commiting transaction in create function");
return u64::from_be_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], ]) return u64::from_be_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], ])
} }
@@ -112,7 +117,7 @@ impl Itemstore {
keys = keys.into_iter().unique().collect::<Vec<Vec<u8>>>(); keys = keys.into_iter().unique().collect::<Vec<Vec<u8>>>();
tr.set(format!("{}", id).into_bytes(), encode(keys)).await; tr.set(format!("{}", id).into_bytes(), encode(keys)).await;
tr.commit().await; let res = tr.commit().await.expect("error commiting transaction in update function");
} }
pub async fn delete(&self, id: u64){ pub async fn delete(&self, id: u64){
@@ -130,7 +135,7 @@ impl Itemstore {
tr.del(key).await; tr.del(key).await;
} }
tr.del(format!("{}", id)).await; tr.del(format!("{}", id)).await;
tr.commit().await; let res = tr.commit().await.expect("error commiting transaction in delete function");
} }
pub async fn get(&self, id: u64) -> Item { pub async fn get(&self, id: u64) -> Item {
@@ -145,14 +150,11 @@ impl Itemstore {
Err(e) => panic!("Error while querying the db: {}", e), Err(e) => panic!("Error while querying the db: {}", e),
}; };
println!("ID: {}", id);
for key in keys { for key in keys {
let mut field: [Vec<u8>; 2] = [Vec::new(), Vec::new()]; let mut field: [Vec<u8>; 2] = [Vec::new(), Vec::new()];
field[0] = key.clone(); field[0] = key.clone();
let mut ke = format!("{}", id).into_bytes(); let mut ke = format!("{}:", id).into_bytes();
ke.push(':' as u8);
ke.extend(key.clone()); ke.extend(key.clone());
println!("Key: {}", String::from_utf8(ke.clone()).unwrap());
field[1] = match tr.get(ke).await { field[1] = match tr.get(ke).await {
Ok(Some(val)) => val, Ok(Some(val)) => val,
Ok(None) => panic!("a field that should be there wasn't"), Ok(None) => panic!("a field that should be there wasn't"),

View File

@@ -32,7 +32,8 @@ pub async fn handle_mize_message(
// 10: update // 10: update
// 11: delete // 11: delete
// 12: create // 12: create
// 13: unsupported_version // 13: created_id
// 14: unsupported_version
//println!("message: {:?}", message); //println!("message: {:?}", message);
//let version = message.clone().into_iter().nth(0).expect("message has no 0th byte"); //let version = message.clone().into_iter().nth(0).expect("message has no 0th byte");
@@ -57,8 +58,8 @@ pub async fn handle_mize_message(
count += 1; count += 1;
}; };
println!("VERSION: {}", version); //println!("VERSION: {}", version);
println!("CMD: {}", cmd); //println!("CMD: {}", cmd);
match cmd { match cmd {
1 => { 1 => {
@@ -85,10 +86,10 @@ pub async fn handle_mize_message(
answer.extend(num_of_fields.to_be_bytes()); answer.extend(num_of_fields.to_be_bytes());
for field in item { for field in item {
let key_len = field[0].len() as u64; let key_len = field[0].len() as u32;
answer.extend(key_len.to_be_bytes()); answer.extend(key_len.to_be_bytes());
answer.extend(field[0].clone()); answer.extend(field[0].clone());
let val_len = field[1].len() as u64; let val_len = field[1].len() as u32;
answer.extend(val_len.to_be_bytes()); answer.extend(val_len.to_be_bytes());
answer.extend(field[1].clone()); answer.extend(field[1].clone());
@@ -104,8 +105,45 @@ pub async fn handle_mize_message(
8 => {return Response::None;}, 8 => {return Response::None;},
9 => {return Response::None;}, 9 => {return Response::None;},
10 => {return Response::None;}, 10 => {return Response::None;},
11 => {return Response::None;}, 11 => {
12 => {return Response::None;}, let tmp = &message[2..10];
let id: u64 = u64::from_be_bytes([tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7]]);
if id == 0 {
return Response::None;
}
itemstore.delete(id);
return Response::None;
},
12 => {
let tmp = &message[2..6];
let num_of_fields: u32 = u32::from_be_bytes([tmp[0], tmp[1], tmp[2], tmp[3]]);
let mut item: Vec<[Vec<u8>; 2]> = Vec::new();
let mut index = 6;
for i in 0..num_of_fields {
let mut tmp = &message[index..index + 4];
let key_len = u32::from_be_bytes([tmp[0], tmp[1], tmp[2], tmp[3]]);
let key = message[index + 4..(index + 4 + key_len as usize)].to_vec();
index += 4 + key_len as usize;
tmp = &message[index..index + 4];
let val_len = u32::from_be_bytes([tmp[0], tmp[1], tmp[2], tmp[3]]);
let val = message[index + 4..(index + 4 + val_len as usize)].to_vec();
index += 4 + val_len as usize;
item.push([key, val]);
}
itemstore.create(item).await;
let anser: Vec<u8> = vec![1,1];
return Response::None;
},
13 => {return Response::None;},
14 => {return Response::None;},
_ => {return Response::None;}, _ => {return Response::None;},
} }