Skip to content

Commit

Permalink
Refactor storage and send methods
Browse files Browse the repository at this point in the history
  • Loading branch information
marlonbaeten authored and squell committed Apr 30, 2024
1 parent 6a9a3db commit d93a9a8
Show file tree
Hide file tree
Showing 16 changed files with 484 additions and 549 deletions.
22 changes: 11 additions & 11 deletions demo-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use tokio::sync::{broadcast, RwLock};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use tsp::{
definitions::{Payload, VerifiedVid},
vid::{PrivateVid, Vid},
vid::{OwnedVid, Vid},
AsyncStore,
};

Expand Down Expand Up @@ -75,7 +75,7 @@ async fn main() {

tokio::task::spawn(async {
let mut db = AsyncStore::new();
let piv: PrivateVid =
let piv: OwnedVid =
serde_json::from_str(include_str!("../../examples/test/carol.json")).unwrap();
db.add_private_vid(piv).unwrap();
db.verify_vid("did:web:did.tsp-test.org:user:dave")
Expand All @@ -95,7 +95,7 @@ async fn main() {

tokio::task::spawn(async {
let mut db = AsyncStore::new();
let piv: PrivateVid =
let piv: OwnedVid =
serde_json::from_str(include_str!("../../examples/test/dave.json")).unwrap();
db.add_private_vid(piv).unwrap();
db.verify_vid("did:web:did.tsp-test.org:user:carol")
Expand Down Expand Up @@ -241,8 +241,8 @@ fn format_part(title: &str, part: &tsp::cesr::Part, plain: Option<&[u8]>) -> ser
}

/// Decode a CESR encoded message into descriptive JSON
fn decode_message(message: &[u8], payload: Option<&[u8]>) -> Option<serde_json::Value> {
let parts = tsp::cesr::decode_message_into_parts(message).ok()?;
fn open_message(message: &[u8], payload: Option<&[u8]>) -> Option<serde_json::Value> {
let parts = tsp::cesr::open_message_into_parts(message).ok()?;

Some(json!({
"original": Base64UrlUnpadded::encode_string(message),
Expand All @@ -260,7 +260,7 @@ fn decode_message(message: &[u8], payload: Option<&[u8]>) -> Option<serde_json::
struct SendMessageForm {
message: String,
nonconfidential_data: Option<String>,
sender: PrivateVid,
sender: OwnedVid,
receiver: Vid,
}

Expand Down Expand Up @@ -314,7 +314,7 @@ async fn send_message(
message.clone(),
));

let decoded = decode_message(&message, Some(form.message.as_bytes())).unwrap();
let decoded = open_message(&message, Some(form.message.as_bytes())).unwrap();

Json(decoded).into_response()
}
Expand Down Expand Up @@ -357,7 +357,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
let (mut sender, mut receiver) = stream.split();
let mut rx = state.tx.subscribe();
let senders = Arc::new(RwLock::new(HashMap::<String, Vid>::new()));
let receivers = Arc::new(RwLock::new(HashMap::<String, PrivateVid>::new()));
let receivers = Arc::new(RwLock::new(HashMap::<String, OwnedVid>::new()));

// Forward messages from the broadcast channel to the websocket
let incoming_senders = senders.clone();
Expand All @@ -383,9 +383,9 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
continue;
};

decode_message(&message, Some(payload.as_bytes()))
open_message(&message, Some(payload.as_bytes()))
} else {
decode_message(&message, None)
open_message(&message, None)
};

let Some(decoded) = result else {
Expand All @@ -405,7 +405,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
// Receive encoded VID's from the websocket and store them in the local state
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(Message::Text(incoming_message))) = receiver.next().await {
if let Ok(identity) = serde_json::from_str::<PrivateVid>(&incoming_message) {
if let Ok(identity) = serde_json::from_str::<OwnedVid>(&incoming_message) {
receivers
.write()
.await
Expand Down
48 changes: 22 additions & 26 deletions examples/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::Path;
use tokio::io::AsyncReadExt;
use tracing::{info, trace};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use tsp::{cesr::Part, AsyncStore, Error, PrivateVid, ReceivedTspMessage, VerifiedVid, Vid};
use tsp::{cesr::Part, AsyncStore, Error, OwnedVid, ReceivedTspMessage, VerifiedVid, Vid};

#[derive(Debug, Parser)]
#[command(name = "tsp")]
Expand Down Expand Up @@ -51,26 +51,27 @@ enum Commands {

#[derive(Debug, Serialize, Deserialize)]
struct DatabaseContents {
private_vids: Vec<PrivateVid>,
private_vids: Vec<OwnedVid>,
verified_vids: Vec<Vid>,
}

async fn write_database(database_file: &str, db: &AsyncStore) -> Result<(), Error> {
let db_path = Path::new(database_file);
// TODO
async fn write_database(database_file: &str, _db: &AsyncStore) -> Result<(), Error> {
// let db_path = Path::new(database_file);

let (private_vids, verified_vids) = db.export()?;
// let (private_vids, verified_vids) = db.export()?;

let db_contents = DatabaseContents {
private_vids,
verified_vids,
};
// let db_contents = DatabaseContents {
// private_vids,
// verified_vids,
// };

let db_contents_json =
serde_json::to_string_pretty(&db_contents).expect("Could not serialize database");
// let db_contents_json =
// serde_json::to_string_pretty(&db_contents).expect("Could not serialize database");

tokio::fs::write(db_path, db_contents_json)
.await
.expect("Could not write database");
// tokio::fs::write(db_path, db_contents_json)
// .await
// .expect("Could not write database");

trace!("persisted database to {database_file}");

Expand Down Expand Up @@ -123,7 +124,7 @@ fn color_print_part(part: Option<Part>, color: u8) {
}

fn print_message(message: &[u8]) {
let Ok(parts) = tsp::cesr::decode_message_into_parts(message) else {
let Ok(parts) = tsp::cesr::open_message_into_parts(message) else {
eprintln!("Invalid encoded message");
return;
};
Expand Down Expand Up @@ -170,7 +171,7 @@ async fn run() -> Result<(), Error> {
let did = format!("did:web:tsp-test.org:user:{username}");
let transport =
url::Url::parse(&format!("https://tsp-test.org/user/{username}")).unwrap();
let private_vid = PrivateVid::bind(&did, transport);
let private_vid = OwnedVid::bind(&did, transport);

reqwest::Client::new()
.post("https://tsp-test.org/add-vid")
Expand Down Expand Up @@ -223,32 +224,27 @@ async fn run() -> Result<(), Error> {
message,
message_type: _,
} => {
info!(
"received message ({} bytes) from {}",
message.len(),
sender.identifier(),
);
info!("received message ({} bytes) from {}", message.len(), sender,);
println!("{}", String::from_utf8_lossy(&message),);
}
ReceivedTspMessage::RequestRelationship {
sender,
thread_id: _,
} => {
info!("received relationship request from {}", sender.identifier(),);
info!("received relationship request from {}", sender);
}
ReceivedTspMessage::AcceptRelationship { sender } => {
info!("received accept relationship from {}", sender.identifier(),);
info!("received accept relationship from {}", sender);
}
ReceivedTspMessage::CancelRelationship { sender } => {
info!("received cancel relationship from {}", sender.identifier(),);
info!("received cancel relationship from {}", sender);
}
ReceivedTspMessage::ForwardRequest {
sender, next_hop, ..
} => {
info!(
"messaging forwarding request from {} to {}",
sender.identifier(),
next_hop.identifier()
sender, next_hop
);
}
}
Expand Down
Loading

0 comments on commit d93a9a8

Please sign in to comment.