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

Open
wants to merge 28 commits into
base: nwaku
Choose a base branch
from
Open

Toy chat fix #105

wants to merge 28 commits into from

Conversation

Ivansete-status
Copy link

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

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

Aside from that, it suggests to make the waku crate to behave tokio-asynchronously.

Note: I've noticed that the libwaku cannot be used by multiple threads in parallel. We might need to perform additional work to make it work properly:

In the following snippet, the initialized variable is shared among all threads. We should instead have a mechanism to check "initialized" within each thread.

proc initializeLibrary() {.exported.} =
  if not initialized.exchange(true): <-----------
    NimMain() # Every Nim library needs to call `NimMain` once exactly
  when declared(setupForeignThreadGc):
    setupForeignThreadGc()
  when declared(nimGC_setStackBottom):
    var locals {.volatile, noinit.}: pointer
    locals = addr(locals)
    nimGC_setStackBottom(locals)

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
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
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
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

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?

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