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

refactor(c-bindings): userdata #785

Merged
merged 1 commit into from
Oct 28, 2023
Merged

Conversation

richard-ramos
Copy link
Member

@richard-ramos richard-ramos commented Sep 28, 2023

Description

Adds an void* user_data parameter to all c-bindings API functions so it's possible to use them without having to use global variables

New API:

// Initialize a waku node. Receives a JSON string containing the configuration
// for the node. It can be NULL. Example configuration:
// ```
// {"host": "0.0.0.0", "port": 60000, "advertiseAddr": "1.2.3.4", "nodeKey": "0x123...567", "keepAliveInterval": 20, "relay": true}
// ```
// All keys are optional. If not specified a default value will be set:
// - host: IP address. Default 0.0.0.0
// - port: TCP port to listen. Default 60000. Use 0 for random
// - advertiseAddr: External IP
// - nodeKey: secp256k1 private key. Default random
// - keepAliveInterval: interval in seconds to ping all peers
// - relay: Enable WakuRelay. Default `true`
// - relayTopics: Array of pubsub topics that WakuRelay will automatically subscribe to when the node starts
// - gossipsubParams: an object containing custom gossipsub parameters. All attributes are optional, and if not specified, it will use default values.
//   - d: optimal degree for a GossipSub topic mesh. Default `6`
//   - dLow: lower bound on the number of peers we keep in a GossipSub topic mesh. Default `5`
//   - dHigh: upper bound on the number of peers we keep in a GossipSub topic mesh. Default `12`
//   - dScore: affects how peers are selected when pruning a mesh due to over subscription. Default `4`
//   - dOut: sets the quota for the number of outbound connections to maintain in a topic mesh. Default `2`
//   - historyLength: controls the size of the message cache used for gossip. Default `5`
//   - historyGossip: controls how many cached message ids we will advertise in IHAVE gossip messages. Default `3`
//   - dLazy: affects how many peers we will emit gossip to at each heartbeat. Default `6`
//   - gossipFactor: affects how many peers we will emit gossip to at each heartbeat. Default `0.25`
//   - gossipRetransmission: controls how many times we will allow a peer to request the same message id through IWANT gossip before we start ignoring them. Default `3`
//   - heartbeatInitialDelayMs: short delay in milliseconds before the heartbeat timer begins after the router is initialized. Default `100` milliseconds
//   - heartbeatIntervalSeconds: controls the time between heartbeats. Default `1` second
//   - slowHeartbeatWarning: duration threshold for heartbeat processing before emitting a warning. Default `0.1`
//   - fanoutTTLSeconds: controls how long we keep track of the fanout state. Default `60` seconds
//   - prunePeers: controls the number of peers to include in prune Peer eXchange. Default `16`
//   - pruneBackoffSeconds: controls the backoff time for pruned peers. Default `60` seconds
//   - unsubscribeBackoffSeconds: controls the backoff time to use when unsuscribing from a topic. Default `10` seconds
//   - connectors: number of active connection attempts for peers obtained through PX. Default `8`
//   - maxPendingConnections: maximum number of pending connections for peers attempted through px. Default `128`
//   - connectionTimeoutSeconds: timeout in seconds for connection attempts. Default `30` seconds
//   - directConnectTicks: the number of heartbeat ticks for attempting to reconnect direct peers that are not currently connected. Default `300`
//   - directConnectInitialDelaySeconds: initial delay before opening connections to direct peers. Default `1` second
//   - opportunisticGraftTicks: number of heartbeat ticks for attempting to improve the mesh with opportunistic grafting. Default `60`
//   - opportunisticGraftPeers: the number of peers to opportunistically graft. Default `2`
//   - graftFloodThresholdSeconds: If a GRAFT comes before GraftFloodThresholdSeconds has elapsed since the last PRUNE, then there is an extra score penalty applied to the peer through P7. Default `10` seconds
//   - maxIHaveLength: max number of messages to include in an IHAVE message, also controls the max number of IHAVE ids we will accept and request with IWANT from a peer within a heartbeat. Default `5000`
//   - maxIHaveMessages: max number of IHAVE messages to accept from a peer within a heartbeat. Default `10`
//   - iWantFollowupTimeSeconds: Time to wait for a message requested through IWANT following an IHAVE advertisement. Default `3` seconds
//   - seenMessagesTTLSeconds:  configures when a previously seen message ID can be forgotten about. Default `120` seconds
//
// - minPeersToPublish: The minimum number of peers required on a topic to allow broadcasting a message. Default `0`
// - legacyFilter: Enable LegacyFilter. Default `false`
// - discV5: Enable DiscoveryV5. Default `false`
// - discV5BootstrapNodes: Array of bootstrap nodes ENR
// - discV5UDPPort: UDP port for DiscoveryV5
// - logLevel: Set the log level. Default `INFO`. Allowed values "DEBUG", "INFO", "WARN", "ERROR", "DPANIC", "PANIC", "FATAL"
// - store: Enable Store. Default `false`
// - databaseURL: url connection string. Default: "sqlite3://store.db". Also accepts PostgreSQL connection strings
// - storeRetentionMaxMessages: max number of messages to store in the database. Default 10000
// - storeRetentionTimeSeconds: max number of seconds that a message will be persisted in the database. Default 2592000 (30d)
// - websockets: an optional object containing settings to setup the websocket configuration
//   - enabled: indicates if websockets support will be enabled. Default `false`
//   - host: listening address for websocket connections. Default `0.0.0.0`
//   - port: TCP listening port for websocket connection (0 for random, binding to 443 requires root access). Default: `60001“, if secure websockets support is enabled, the default is `6443“
//   - secure: enable secure websockets support. Default `false`
//   - certPath: secure websocket certificate path
//   - keyPath: secure websocket key path
//
// - dns4DomainName: the domain name resolving to the node's public IPv4 address.
//
extern int waku_new(char* configJSON, WakuCallBack cb, void* userData);

// Starts the waku node
//
extern int waku_start(WakuCallBack onErr, void* userData);

// Stops a waku node
//
extern int waku_stop(WakuCallBack onErr, void* userData);

// Determine is a node is started or not
//
extern int waku_is_started();

// Obtain the peer ID of the waku node
//
extern int waku_peerid(WakuCallBack cb, void* userData);

// Obtain the multiaddresses the wakunode is listening to
//
extern int waku_listen_addresses(WakuCallBack cb, void* userData);

// Add node multiaddress and protocol to the wakunode peerstore
//
extern int waku_add_peer(char* address, char* protocolID, WakuCallBack cb, void* userData);

// Connect to peer at multiaddress. if ms > 0, cancel the function execution if it takes longer than N milliseconds
//
extern int waku_connect(char* address, int ms, WakuCallBack cb, void* userData);

// Connect to known peer by peerID. if ms > 0, cancel the function execution if it takes longer than N milliseconds
//
extern int waku_connect_peerid(char* peerID, int ms, WakuCallBack cb, void* userData);

// Close connection to a known peer by peerID
//
extern int waku_disconnect(char* peerID, WakuCallBack cb, void* userData);

// Get number of connected peers
//
extern int waku_peer_cnt(WakuCallBack cb, void* userData);

// Create a content topic string according to RFC 23
//
extern int waku_content_topic(char* applicationName, unsigned int applicationVersion, char* contentTopicName, char* encoding, WakuCallBack cb, void* userData);

// Create a pubsub topic string according to RFC 23
//
extern int waku_pubsub_topic(char* name, char* encoding, WakuCallBack cb, void* userData);

// Get the default pubsub topic used in waku2: /waku/2/default-waku/proto
//
extern int waku_default_pubsub_topic(WakuCallBack cb, void* userData);

// Register callback to act as signal handler and receive application signals
// (in JSON) which are used to react to asynchronous events in waku. The function
// signature for the callback should be `void myCallback(char* signalJSON)`
//
extern void waku_set_event_callback(WakuCallBack cb);

// Retrieve the list of peers known by the waku node
//
extern int waku_peers(WakuCallBack cb, void* userData);

// Returns a list of objects containing the peerID, enr and multiaddresses for each node found
//
//	given a url to a DNS discoverable ENR tree
//
// The nameserver can optionally be specified to resolve the enrtree url. Otherwise NULL or
// empty to automatically use the default system dns.
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_dns_discovery(char* url, char* nameserver, int ms, WakuCallBack cb, void* userData);

// Update the bootnode list used for discovering new peers via DiscoveryV5
// The bootnodes param should contain a JSON array containing the bootnode ENRs i.e. `["enr:...", "enr:..."]`
//
extern int waku_discv5_update_bootnodes(char* bootnodes, WakuCallBack cb, void* userData);

// Decode a waku message using a 32 bytes symmetric key. The key must be a hex encoded string with "0x" prefix
//
extern int waku_decode_symmetric(char* messageJSON, char* symmetricKey, WakuCallBack cb, void* userData);

// Decode a waku message using a secp256k1 private key. The key must be a hex encoded string with "0x" prefix
//
extern int waku_decode_asymmetric(char* messageJSON, char* privateKey, WakuCallBack cb, void* userData);

// Encrypt a message with a secp256k1 public key.
// publicKey must be a hex string prefixed with "0x" containing a valid secp256k1 public key.
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
// The message version will be set to 1
//
extern int waku_encode_asymmetric(char* messageJSON, char* publicKey, char* optionalSigningKey, WakuCallBack cb, void* userData);

// Encrypt a message with a 32 bytes symmetric key
// symmetricKey must be a hex string prefixed with "0x" containing a 32 bytes symmetric key
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
// The message version will be set to 1
//
extern int waku_encode_symmetric(char* messageJSON, char* symmetricKey, char* optionalSigningKey, WakuCallBack cb, void* userData);

// Creates a subscription to a filter full node matching a content filter.
// filterJSON must contain a JSON with this format:
//
//		{
//		  "pubsubTopic": "the pubsub topic" // optional if using autosharding, mandatory if using static or named sharding.
//	      "contentTopics": ["the content topic"] // mandatory, at least one required, with a max of 10
//		}
//
// peerID should contain the ID of a peer supporting the filter protocol. Use NULL to automatically select a node
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
// It returns a json object containing the details of the subscriptions along with any errors in case of partial failures
//
extern int waku_filter_subscribe(char* filterJSON, char* peerID, int ms, WakuCallBack cb, void* userData);

// Used to know if a service node has an active subscription for this client
// peerID should contain the ID of a peer we are subscribed to, supporting the filter protocol
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_filter_ping(char* peerID, int ms, WakuCallBack cb, void* userData);

// Sends a requests to a service node to stop pushing messages matching this filter to this client.
// It might be used to modify an existing subscription by providing a subset of the original filter
// criteria
//
//		{
//		  "pubsubTopic": "the pubsub topic" //  optional if using autosharding, mandatory if using static or named sharding.
//	      "contentTopics": ["the content topic"] // mandatory, at least one required, with a max of 10
//		}
//
// peerID should contain the ID of a peer this client is subscribed to.
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_filter_unsubscribe(char* filterJSON, char* peerID, int ms, WakuCallBack cb, void* userData);

// Sends a requests to a service node (or all service nodes) to stop pushing messages
// peerID should contain the ID of a peer this client is subscribed to, or can be NULL to
// stop all active subscriptions
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_filter_unsubscribe_all(char* peerID, int ms, WakuCallBack cb, void* userData);

// Creates a subscription to a light node matching a content filter and, optionally, a pubSub topic.
// filterJSON must contain a JSON with this format:
//
//	{
//		 "contentFilters": [ // mandatory
//	    {
//	      "contentTopic": "the content topic"
//	    }, ...
//	  ],
//	  "pubsubTopic": "the pubsub topic" // optional
//	}
//
// peerID should contain the ID of a peer supporting the filter protocol. Use NULL to automatically select a node
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_legacy_filter_subscribe(char* filterJSON, char* peerID, int ms, WakuCallBack cb, void* userData);

// Removes subscriptions in a light node matching a content filter and, optionally, a pubSub topic.
// filterJSON must contain a JSON with this format:
//
//	{
//		 "contentFilters": [ // mandatory
//	    {
//	      "contentTopic": "the content topic"
//	    }, ...
//	  ],
//	  "pubsubTopic": "the pubsub topic" // optional
//	}
//
// If ms is greater than 0, the subscription must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_legacy_filter_unsubscribe(char* filterJSON, int ms, WakuCallBack cb, void* userData);

// Publish a message using waku lightpush. Use NULL for topic to derive the pubsub topic from the contentTopic.
// peerID should contain the ID of a peer supporting the lightpush protocol. Use NULL to automatically select a node
// If ms is greater than 0, the broadcast of the message must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_lightpush_publish(char* messageJSON, char* topic, char* peerID, int ms, WakuCallBack cb, void* userData);

// Determine if there are enough peers to publish a message on a topic. Use NULL
// to verify the number of peers in the default pubsub topic
//
extern int waku_relay_enough_peers(char* topic, WakuCallBack cb, void* userData);

// Publish a message using waku relay and returns the message ID. Use NULL for topic to use the default pubsub topic
// If ms is greater than 0, the broadcast of the message must happen before the timeout
// (in milliseconds) is reached, or an error will be returned.
//
extern int waku_relay_publish(char* messageJSON, char* topic, int ms, WakuCallBack cb, void* userData);

// Subscribe to WakuRelay to receive messages matching a content filter.
// filterJSON must contain a JSON with this format:
//
//		{
//		  "pubsubTopic": "the pubsub topic" // optional if using autosharding, mandatory if using static or named sharding.
//	      "contentTopics": ["the content topic"] // mandatory, at least one required, with a max of 10
//		}
//
// When a message is received, a "message" event is emitted containing the message and pubsub topic in which
// the message was received
//
extern int waku_relay_subscribe(char* contentfilterJSON, WakuCallBack cb, void* userData);

// Returns a json response with the list of pubsub topics the node
// is subscribed to in WakuRelay
//
extern int waku_relay_topics(WakuCallBack cb, void* userData);

// Closes the pubsub subscription to stop receiving messages matching a content filter
// filterJSON must contain a JSON with this format:
//
//		{
//		  "pubsubTopic": "the pubsub topic" // optional if using autosharding, mandatory if using static or named sharding.
//	      "contentTopics": ["the content topic"] // mandatory, at least one required, with a max of 10
//		}
//
extern int waku_relay_unsubscribe(char* filterJSON, WakuCallBack cb, void* userData);

// Query historic messages using waku store protocol.
// queryJSON must contain a valid json string with the following format:
//
//	{
//		"pubsubTopic": "...", // optional string
//	 "startTime": 1234, // optional, unix epoch time in nanoseconds
//	 "endTime": 1234, // optional, unix epoch time in nanoseconds
//	 "contentFilters": [ // optional
//			{
//		      contentTopic: "contentTopic1"
//			}, ...
//	 ],
//	 "pagingOptions": {// optional pagination information
//	     "pageSize": 40, // number
//			"cursor": { // optional
//				"digest": ...,
//				"receiverTime": ...,
//				"senderTime": ...,
//				"pubsubTopic" ...,
//	     }
//			"forward": true, // sort order
//	 }
//	}
//
// If a non empty cursor is returned, this function should be executed again, setting  the `cursor` attribute with the cursor returned in the response
// peerID should contain the ID of a peer supporting the store protocol. Use NULL to automatically select a node
// If ms is greater than 0, the broadcast of the message must happen before the timeout
// (in milliseconds) is reached, or an error will be returned
//
extern int waku_store_query(char* queryJSON, char* peerID, int ms, WakuCallBack cb, void* userData);

// Query historic messages stored in the localDB using waku store protocol.
// queryJSON must contain a valid json string with the following format:
//
//	{
//		"pubsubTopic": "...", // optional string
//	 "startTime": 1234, // optional, unix epoch time in nanoseconds
//	 "endTime": 1234, // optional, unix epoch time in nanoseconds
//	 "contentFilters": [ // optional
//			{
//		      contentTopic: "contentTopic1"
//			}, ...
//	 ],
//	 "pagingOptions": {// optional pagination information
//	     "pageSize": 40, // number
//			"cursor": { // optional
//				"digest": ...,
//				"receiverTime": ...,
//				"senderTime": ...,
//				"pubsubTopic" ...,
//	     }
//			"forward": true, // sort order
//	 }
//	}
//
// If a non empty cursor is returned, this function should be executed again, setting  the `cursor` attribute with the cursor returned in the response
// Requires the `store` option to be passed when setting up the initial configuration
//
extern int waku_store_local_query(char* queryJSON, WakuCallBack cb, void* userData);

Tests

@status-im-auto
Copy link

status-im-auto commented Sep 28, 2023

Jenkins Builds

Click to see older builds (41)
Commit #️⃣ Finished (UTC) Duration Platform Result
✔️ f97091e #1 2023-09-28 19:38:37 ~1 min nix-flake 📄log
f97091e #1 2023-09-28 19:39:02 ~2 min linux 📄log
✔️ f97091e #1 2023-09-28 19:39:56 ~3 min tests 📄log
✔️ f97091e #1 2023-09-28 19:39:57 ~3 min tests 📄log
✔️ f97091e #1 2023-09-28 19:40:46 ~4 min android 📦tgz
✔️ f97091e #1 2023-09-28 19:41:53 ~5 min ios 📦tgz
✔️ b9c78bc #2 2023-09-29 12:52:02 ~53 sec tests 📄log
✔️ b9c78bc #2 2023-09-29 12:53:00 ~1 min nix-flake 📄log
b9c78bc #2 2023-09-29 12:53:07 ~1 min linux 📄log
✔️ b9c78bc #2 2023-09-29 12:54:10 ~2 min tests 📄log
✔️ b9c78bc #2 2023-09-29 12:54:44 ~3 min android 📦tgz
✔️ cdad87e #3 2023-09-30 16:53:30 ~56 sec tests 📄log
✔️ cdad87e #3 2023-09-30 16:53:37 ~1 min linux 📦deb
✔️ cdad87e #3 2023-09-30 16:54:25 ~1 min nix-flake 📄log
✔️ cdad87e #3 2023-09-30 16:54:31 ~1 min tests 📄log
✔️ cdad87e #3 2023-09-30 16:56:22 ~3 min android 📦tgz
✔️ cdad87e #3 2023-09-30 16:57:32 ~5 min ios 📦tgz
✔️ 8c7d25c #4 2023-09-30 17:00:09 ~52 sec tests 📄log
✔️ 8c7d25c #4 2023-09-30 17:00:13 ~59 sec linux 📦deb
✔️ 8c7d25c #4 2023-09-30 17:01:05 ~1 min nix-flake 📄log
✔️ 8c7d25c #4 2023-09-30 17:02:13 ~2 min tests 📄log
✔️ 8c7d25c #4 2023-09-30 17:02:38 ~3 min android 📦tgz
✔️ 8c7d25c #4 2023-09-30 17:03:39 ~4 min ios 📦tgz
✔️ b3bd45f #5 2023-09-30 18:00:55 ~1 min linux 📦deb
✔️ b3bd45f #5 2023-09-30 18:01:24 ~1 min tests 📄log
✔️ b3bd45f #5 2023-09-30 18:01:46 ~1 min nix-flake 📄log
✔️ b3bd45f #5 2023-09-30 18:02:02 ~2 min tests 📄log
✔️ b3bd45f #5 2023-09-30 18:03:40 ~3 min android 📦tgz
✔️ b3bd45f #5 2023-09-30 18:04:33 ~4 min ios 📦tgz
✔️ 1fe14c0 #6 2023-10-20 16:04:04 ~2 min linux 📦deb
✔️ 1fe14c0 #6 2023-10-20 16:04:39 ~3 min tests 📄log
✔️ 1fe14c0 #6 2023-10-20 16:04:41 ~3 min tests 📄log
✔️ 1fe14c0 #6 2023-10-20 16:05:07 ~3 min nix-flake 📄log
✔️ 1fe14c0 #6 2023-10-20 16:05:23 ~4 min android 📦tgz
✔️ 1fe14c0 #6 2023-10-20 16:06:42 ~5 min ios 📦tgz
✔️ 1e2d8ac #7 2023-10-27 19:18:19 ~1 min nix-flake 📄log
✔️ 1e2d8ac #7 2023-10-27 19:18:49 ~2 min linux 📦deb
✔️ 1e2d8ac #7 2023-10-27 19:19:45 ~3 min tests 📄log
✔️ 1e2d8ac #7 2023-10-27 19:19:55 ~3 min tests 📄log
✔️ 1e2d8ac #7 2023-10-27 19:20:35 ~4 min android 📦tgz
✔️ 1e2d8ac #7 2023-10-27 19:20:58 ~4 min ios 📦tgz
Commit #️⃣ Finished (UTC) Duration Platform Result
✔️ f29008f #8 2023-10-27 21:04:35 ~2 min nix-flake 📄log
✔️ f29008f #8 2023-10-27 21:05:06 ~2 min linux 📦deb
✔️ f29008f #8 2023-10-27 21:05:16 ~2 min tests 📄log
✔️ f29008f #8 2023-10-27 21:05:48 ~3 min android 📦tgz
✔️ f29008f #8 2023-10-27 21:05:57 ~3 min tests 📄log
✔️ f29008f #8 2023-10-27 21:06:16 ~3 min ios 📦tgz
✔️ c031167 #9 2023-10-28 23:32:20 ~1 min linux 📦deb
✖️ c031167 #9 2023-10-28 23:32:33 ~1 min tests 📄log
✔️ c031167 #9 2023-10-28 23:33:03 ~1 min nix-flake 📄log
✔️ c031167 #9 2023-10-28 23:33:21 ~2 min tests 📄log
✔️ c031167 #9 2023-10-28 23:34:57 ~3 min android 📦tgz
✔️ c031167 #9 2023-10-28 23:35:53 ~4 min ios 📦tgz
✔️ c031167 #10 2023-10-28 23:37:41 ~2 min tests 📄log

@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch 2 times, most recently from b9c78bc to cdad87e Compare September 30, 2023 16:52
@richard-ramos richard-ramos added the E:RLN non-native SDKs See https://github.com/waku-org/pm/issues/88 for details label Sep 30, 2023
@richard-ramos richard-ramos linked an issue Sep 30, 2023 that may be closed by this pull request
@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch from cdad87e to 8c7d25c Compare September 30, 2023 16:58
@richard-ramos richard-ramos marked this pull request as ready for review September 30, 2023 16:59
@richard-ramos richard-ramos changed the title fix(c-bindings): userdata refactor(c-bindings): userdata Sep 30, 2023
@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch from 8c7d25c to b3bd45f Compare September 30, 2023 17:59
Copy link

@Ivansete-status Ivansete-status left a comment

Choose a reason for hiding this comment

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

It looks really nice!Thanks for this!
However, the approach may be a little bit different from what we need in nwaku. In nwaku we have this global variable (now in master branch) which holds the internal Context struct:

https://github.com/waku-org/nwaku/blob/8897ae1a2f9ef4dac98f982a6250ed378bc3d234/library/waku_thread/waku_thread.nim#L29C11-L29C11

You don't have such a similar context variable, do you?

And, in an upcoming PR we will extract this as a void* when a waku_init or waku_new is called. Then, we will need to pass down this "context" variable from outside the library to the rest of the library function invocations.

On the other hand, I was considering the userData parameter as a user-defined context, which in the case of Rust, is the address of the closure. I had suggested the creation of the next function, which links the library Context to the user-defined context, although I'd like to revisit this approach: https://github.com/waku-org/nwaku/blob/653a712ba1f6ccab016ddc1ebc9319b572db275f/library/libwaku.nim#L121

@richard-ramos
Copy link
Member Author

@Ivansete-status,
something to keep in mind is that if the context variable is added, it will be possible to have more than one running node. Is that okay?

For having an extra waku_set_user_data function, I'm not sure I like this approach.
The user_data attribute is associated to the function being called, and waku_user_data unnecessarily decouples the user_data from the function being executed, as well as potentially introducing bugs in case someone forgets to call waku_set_user_data before actually executing the intended function.

A problem I also identified while doing this PR is that in the end I might end up adding an additional parameter to the callback: the return code, as I ended up noticing that from inside the callback it is actually not possible to know whether the function was executed correctly or not. So in the end WakuCallback might look like this:

typedef void (*WakuCallBack) (int ret_code, const char* msg, void * user_data);

@Ivansete-status
Copy link

@Ivansete-status, something to keep in mind is that if the context variable is added, it will be possible to have more than one running node. Is that okay?

Yes correct!


For having an extra waku_set_user_data function, I'm not sure I like this approach. The user_data attribute is associated to the function being called, and waku_user_data unnecessarily decouples the user_data from the function being executed, as well as potentially introducing bugs in case someone forgets to call waku_set_user_data before actually executing the intended function.

I completely agree with that! I will avoid using the waku_set_user_data approach in nwaku then.


A problem I also identified while doing this PR is that in the end I might end up adding an additional parameter to the callback: the return code, as I ended up noticing that from inside the callback it is actually not possible to know whether the function was executed correctly or not. So in the end WakuCallback might look like this:

typedef void (*WakuCallBack) (int ret_code, const char* msg, void * user_data);

Sorry but I don't fully understand this reasoning. Let's comment that tomorrow :)

@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch from b3bd45f to 1fe14c0 Compare October 20, 2023 16:01
@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch 2 times, most recently from 1e2d8ac to f29008f Compare October 27, 2023 21:02
@richard-ramos
Copy link
Member Author

@harsh-98 @chaitanyaprem sorry for the large PR :(
this should be ready to review now.

@Ivansete-status I'll extract the context from waku_init in a separate PR

Copy link
Collaborator

@chaitanyaprem chaitanyaprem left a comment

Choose a reason for hiding this comment

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

LGTM

Left some minor comments.

@richard-ramos richard-ramos force-pushed the feat/c-bindings-callback branch from f29008f to c031167 Compare October 28, 2023 23:30
@richard-ramos richard-ramos merged commit db222a2 into master Oct 28, 2023
@richard-ramos richard-ramos deleted the feat/c-bindings-callback branch October 28, 2023 23:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
E:RLN non-native SDKs See https://github.com/waku-org/pm/issues/88 for details
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

refactor: add user_data to c-bindings
4 participants