-
Notifications
You must be signed in to change notification settings - Fork 8
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
Toy chat fix #105
Conversation
There was a problem hiding this 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.
waku-bindings/src/node/filter.rs
Outdated
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 | ||
}; |
There was a problem hiding this comment.
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.
@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 ( |
@@ -68,12 +68,6 @@ fn generate_bindgen_code(project_dir: &Path) { | |||
|
|||
println!("cargo:rustc-link-lib=stdc++"); | |||
|
|||
println!( |
There was a problem hiding this comment.
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!
// 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"); |
There was a problem hiding this comment.
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)
examples/tic-tac-toe-gui/src/main.rs
Outdated
dbg!(format!("message hash published: {}", msg_hash)); | ||
} | ||
|
||
// self.waku.lightpush_publish_message(&message, &self.game_topic); |
There was a problem hiding this comment.
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}}"; |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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())
}
}
waku-bindings/src/node/filter.rs
Outdated
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 | ||
}; |
There was a problem hiding this comment.
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?
waku-bindings/src/node/mod.rs
Outdated
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; |
There was a problem hiding this comment.
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?
waku-bindings/src/node/mod.rs
Outdated
true, // pagination_forward | ||
Some(25), // pagination_limit, |
There was a problem hiding this comment.
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)
waku-bindings/src/node/mod.rs
Outdated
true, // pagination_forward | ||
Some(25), // pagination_limit, | ||
peer_addr, | ||
None, // timeout_millis |
There was a problem hiding this comment.
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
waku-bindings/src/node/store.rs
Outdated
#[serde(rename_all = "camelCase")] | ||
pub struct StoreWakuMessageResponse { | ||
pub message_hash: MessageHash, | ||
pub message: WakuStoreRespMessage, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Addressed in f1e4e02
waku-bindings/src/general/mod.rs
Outdated
pub timestamp: usize, | ||
#[serde(default)] | ||
pub ephemeral: bool, | ||
// pub proof: Vec<u8>, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this be uncommented?
waku-bindings/src/node/mod.rs
Outdated
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>, |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Addressed in 3b0015d
There was a problem hiding this 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 { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 :)
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)) | ||
} | ||
} |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
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)) | ||
} | ||
} |
There was a problem hiding this comment.
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
.
There was a problem hiding this comment.
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())
}
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Multiaddr do not impl Ah, yeah, Vec doesn't impl FromStr
?. Well, you could implement FromStr for a wrapper type MultiaddrVec(Vec<Multiaddr>)
and the implementation would go through.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 😉
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) |
There was a problem hiding this comment.
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
.
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:
Part of