Skip to content
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

Toy chat fix #105

Merged
merged 36 commits into from
Jan 10, 2025
Merged

Toy chat fix #105

merged 36 commits into from
Jan 10, 2025

Conversation

Ivansete-status
Copy link
Contributor

@Ivansete-status Ivansete-status commented Dec 19, 2024

This PR aims for recovering toy chat powered by libwaku/nwaku.

This PR was motivated by Atoma, who wanted to start using it and we needed to prepare the waku-rust-bindings for them.

Additionally:

  • Bump nwaku to the current master branch ( commit: 625c8ee5 )
  • Suggests to make the waku crate to behave tokio-asynchronously
  • Use of store
  • Use of lightpush and filter
  • add waku-bindings/src/general/messagehash.rs
  • add waku-bindings/src/general/time.rs
  • add waku-bindings/src/general/waku_decode.rs
  • add WakuEvent management (WakuMessage, ConnectionChange, TopicHealthChange.)
  • add waku-bindings/src/macros.rs

Part of

Copy link
Collaborator

@danielSanchezQ danielSanchezQ left a comment

Choose a reason for hiding this comment

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

I think its nice, I would check on my comment to see if it can be improved. But nice job overall.

Comment on lines 72 to 78
let mut result = LibwakuResponse::default();
let notify = Arc::new(Notify::new());
let notify_clone = notify.clone();
let result_cb = |r: LibwakuResponse| {
result = r;
notify_clone.notify_one(); // Notify that the value has been updated
};
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this pattern its ok but should be simpler if you use a channel to return the result. You can probably use kanal a mixed flavored channel (sync/async). To simplify it.

@danielSanchezQ
Copy link
Collaborator

@Ivansete-status Are the nwaku calls on the other side of the FFI are async?

@Ivansete-status
Copy link
Contributor Author

@Ivansete-status Are the nwaku calls on the other side of the FFI are async?

Yes. Everything in nwaku is async and the interaction with the library is async too. To elaborate a bit more, libwaku runs a separate thread, a.k.a. The Waku Thread, which is in charge of running the Waku node and also, attending the app's requests (waku_new, waku_start, etc.)

@@ -68,12 +68,6 @@ fn generate_bindgen_code(project_dir: &Path) {

println!("cargo:rustc-link-lib=stdc++");

println!(
Copy link
Member

Choose a reason for hiding this comment

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

Negentropy is no longer needed to build libwaku?! that's very cool!

Comment on lines +93 to +95
// let ctopic = WakuContentTopic::new("waku", "2", "tictactoegame", Encoding::Proto);
// let content_topics = vec![ctopic];
// waku.filter_subscribe(&self.game_topic, content_topics).await.expect("waku should subscribe");
Copy link
Member

Choose a reason for hiding this comment

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

Maybe a comment can be added above these lines to explain what is their purpose (i.e. to indicate that filter subscriptions are done with it)

dbg!(format!("message hash published: {}", msg_hash));
}

// self.waku.lightpush_publish_message(&message, &self.game_topic);
Copy link
Member

Choose a reason for hiding this comment

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

Same comment as before. Add a comment to indicate what is this about

let s = "{\"eventType\":\"message\",\"messageHash\":\"0x26ff3d7fbc950ea2158ce62fd76fd745eee0323c9eac23d0713843b0f04ea27c\",\"pubsubTopic\":\"/waku/2/default-waku/proto\",\"wakuMessage\":{\"payload\":\"SGkgZnJvbSDwn6aAIQ==\",\"contentTopic\":\"/toychat/2/huilong/proto\",\"timestamp\":1665580926660}}";
let evt: Event = serde_json::from_str(s).unwrap();
assert!(matches!(evt, Event::WakuMessage(_)));
let s = "{\"eventType\":\"message\",\"messageHash\":[91, 70, 26, 8, 141, 232, 150, 200, 26, 206, 224, 175, 249, 74, 61, 140, 231, 126, 224, 160, 91, 80, 162, 65, 250, 171, 84, 149, 133, 110, 214, 101],\"pubsubTopic\":\"/waku/2/default-waku/proto\",\"wakuMessage\":{\"payload\":\"SGkgZnJvbSDwn6aAIQ==\",\"contentTopic\":\"/toychat/2/huilong/proto\",\"timestamp\":1665580926660}}";
Copy link
Member

Choose a reason for hiding this comment

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

Why use a numeric array instead of a byte array?
reason why I ask is that one of the advantages of json is that it's human readable (not much tbf), Then, comparing the byte array with the hash, it seems to me that a hash is much more friendly.
(Although tbf, we do use a MessageHash type that abstracts the dev from the array)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@richard-ramos - yes good point and I completely agree the need of having readable hex.
I found this is the most convenient approach of handling message hash from store and relay. Also, in the messagehash.rs module we have the following, which is interesting to "print" the msg_hash content:

// Implement the Display trait
impl fmt::Display for MessageHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex_string())
    }
}

Comment on lines 31 to 37
let mut result = LibwakuResponse::default();
let notify = Arc::new(Notify::new());
let notify_clone = notify.clone();
let result_cb = |r: LibwakuResponse| {
result = r;
notify_clone.notify_one(); // Notify that the value has been updated
};
Copy link
Member

Choose a reason for hiding this comment

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

This patterns tends to repeat consistently. I wonder if we can maybe extract this into a function?

Comment on lines 195 to 198
let one_day_in_secs = 60 * 60 * 24;
let time_start = (Duration::from_secs(Utc::now().timestamp() as u64)
- Duration::from_secs(one_day_in_secs))
.as_nanos() as usize;
Copy link
Member

Choose a reason for hiding this comment

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

Shoudn't the time-start and time-end be optional duration's passed by the developer?

Comment on lines 215 to 216
true, // pagination_forward
Some(25), // pagination_limit,
Copy link
Member

Choose a reason for hiding this comment

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

Should probably be parameters as well.

Perhaps for all of the parameters of the query it makes sense to define a query object that can be built with an options pattern (https://medium.com/@omid.jn/options-pattern-in-rust-6425520b2b23)

true, // pagination_forward
Some(25), // pagination_limit,
peer_addr,
None, // timeout_millis
Copy link
Member

Choose a reason for hiding this comment

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

Timeout should probably be a parameter given by the developer

#[serde(rename_all = "camelCase")]
pub struct StoreWakuMessageResponse {
pub message_hash: MessageHash,
pub message: WakuStoreRespMessage,
Copy link
Member

Choose a reason for hiding this comment

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

IIRC, include_data will determine whether a message will be returned or not, so probably makes sense for message to be an option

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes correct :) We are using the include_data concept in the requests. I think is fine unless I'm missing something

Copy link
Member

Choose a reason for hiding this comment

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

But wouldn't that mean that if you send include_data: false, your message will contain a (invalid) struct with default values? having it as an option perhaps would make it clearer for the dev that there's no message available

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Addressed in f1e4e02

pub timestamp: usize,
#[serde(default)]
pub ephemeral: bool,
// pub proof: Vec<u8>,
Copy link
Member

Choose a reason for hiding this comment

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

Should this be uncommented?

include_data: bool, // is true, resp contains payload, etc. Only msg_hashes otherwise
time_start: Option<u64>, // unix time nanoseconds
time_end: Option<u64>, // unix time nanoseconds
timeout_millis: Option<i32>,
Copy link
Member

Choose a reason for hiding this comment

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

Probably should be an Option<Duration>

Copy link
Contributor Author

@Ivansete-status Ivansete-status Jan 10, 2025

Choose a reason for hiding this comment

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

Addressed in 3b0015d

Copy link
Collaborator

@danielSanchezQ danielSanchezQ left a comment

Choose a reason for hiding this comment

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

Rusty stuff 🦀
Just left a few comments/nitpicks. Nothing critic.

}
}

impl Hash for MessageHash {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Couldn't this be derived directly?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 566fae9
Thanks so much indeed for the lesson :)

Comment on lines 48 to 63
impl<'de> Deserialize<'de> for MessageHash {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize the input as a vector of u8
let vec: Vec<u8> = Deserialize::deserialize(deserializer)?;

// Ensure the vector has exactly 32 elements
let array: [u8; 32] = vec
.try_into()
.map_err(|_| serde::de::Error::custom("Expected an array of length 32"))?;

Ok(MessageHash(array))
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Also couldn't use derive?
This would be useful to implement manually if you want to discern "human" readable (the hex_bytes you have from the parsing method above for example) form a simple array of bytes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 6541dc3
Super happy about it, thanks!

Comment on lines +1 to +26
use crate::general::Result;
use multiaddr::Multiaddr;
// Define the WakuDecode trait
pub trait WakuDecode: Sized {
fn decode(input: &str) -> Result<Self>;
}

impl WakuDecode for String {
fn decode(input: &str) -> Result<Self> {
Ok(input.to_string())
}
}

pub fn decode<T: WakuDecode>(input: String) -> Result<T> {
T::decode(input.as_str())
}

impl WakuDecode for Vec<Multiaddr> {
fn decode(input: &str) -> Result<Self> {
input
.split(',')
.map(|s| s.trim().parse::<Multiaddr>().map_err(|err| err.to_string()))
.collect::<Result<Vec<Multiaddr>>>() // Collect results into a Vec
.map_err(|err| format!("could not parse Multiaddr: {}", err))
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why not use FromStr directly? Otherwise, you could probably implement WakuDecode for T where T: FromStr.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've tried to apply that suggestion. At some point I came across an issue when trying to implement the FromStr trait for Vec<Multiaddr> and the problem is that Multiaddr is defined in an external crate.

I tried with the following but it requires Vec<Multiaddr> to implement FromStr , which I'm afraid isn't doable:

impl<T> WakuDecode for T
where
    T: FromStr,
    T::Err: ToString,
{
    fn decode(input: &str) -> Result<Self> {
        T::from_str(input).map_err(|e| e.to_string())
    }
}

Copy link
Collaborator

@danielSanchezQ danielSanchezQ Jan 10, 2025

Choose a reason for hiding this comment

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

Multiaddr do not impl FromStr?. Well, you could implement FromStr for a wrapper type MultiaddrVec(Vec<Multiaddr>) and the implementation would go through. Ah, yeah, Vec doesn't impl FromStr ofc. This are just nitpicks. But you could then impl WakuDecode for Vec<T> where T: WakuDecode. Sadly you cannot provide customized implementations yet for different types. It would be nice to implement both.
TLDR: it is ok as it is 😉

Comment on lines +188 to +211
loop {
let query = StoreQueryRequest::new()
.with_pubsub_topic(pubsub_topic.clone())
.with_content_topics(content_topics.clone())
.with_include_data(include_data)
.with_time_start(time_start)
.with_time_end(time_end)
.with_pagination_cursor(cursor)
.with_pagination_forward(true);

let response =
store::waku_store_query(&self.ctx, query, peer_addr, timeout_millis).await?;

messages.extend(response.messages);

if response.pagination_cursor.is_none() {
break;
}
cursor = response.pagination_cursor;
}

messages.reverse();

Ok(messages)
Copy link
Collaborator

Choose a reason for hiding this comment

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

It makes no sense too much for this method to be asynchronous as it stands. I would return a stream of values (requested asynchronously) instead so it can be consumed later by the caller if needed. Otherwise, you keep the asynchronous API without allocation into a Vec.

@Ivansete-status Ivansete-status linked an issue Jan 10, 2025 that may be closed by this pull request
@Ivansete-status Ivansete-status merged commit 0c0b834 into nwaku Jan 10, 2025
5 of 6 checks passed
@Ivansete-status Ivansete-status deleted the toy-chat-fix branch January 10, 2025 14:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants