Ivan FB 7080a629da
feat: migrate the FFI layer to nim-ffi 0.2.0
nim-ffi 0.2.0 reshapes the authoring model: `.ffi.` procs take the
library value plus typed params instead of threading (ctx, callback,
userData) by hand, the macro validates the context itself, and payloads
ride the wire as CBOR rather than ad-hoc JSON strings. The old idiom no
longer compiles against it, so the whole surface moves at once.

Proc names are camelCase chosen so the generated snake_case export
matches the previous C symbol exactly (wakuRelayPublish ->
waku_relay_publish), keeping the ABI names stable.

Node lifecycle now uses the dedicated pragmas: `.ffiCtor.` for
create_node (LogosDelivery.new already returns the Future[Result[...]]
the contract wants) and `.ffiDtor.` for destroy. Contexts come from the
macro-emitted FFIContextPool, which caps live contexts at 32.

Events become typed `.ffiEvent.` procs over `.ffi.` payload objects. The
payloads carry wire-friendly scalars rather than the domain types, which
are not serialisable; byte fields stay base64. This is what makes the
generated bindings emit typed listeners instead of leaving consumers to
register by name and parse JSON themselves.

The payload fields are deliberately unexported. genBindings copies field
names verbatim, so an export marker leaks into the generated Rust as
`pub payload*: String` and the file does not parse -- a nim-ffi bug (it
strips the marker from type names but not fields, so its single-file
examples never hit it). Construction therefore lives behind the emit*
procs in declare_lib, which also keeps event emission in one place and
collapses each listener body to a single call.

`requireInitializedNode` is gone: the macro rejects a null/invalid ctx
before the handler runs, so all 14 call sites were redundant.

Relay and filter push handlers are declared `raises: [Defect]`, so the
emit call is wrapped explicitly -- the dispatch path no longer guards
the body for us.

genBindings() emits the C/C++/Rust bindings and must stay last in the
compilation root; it is a no-op without -d:ffiGenBindings. The Rust
output is checked in so consumers can vendor it directly.

Known gaps, tracked separately: the hand-written liblogosdelivery.h /
_kernel.h still declare the pre-CBOR signatures and need generating or
dropping, and nimble resolves cbor_serialization 0.4.0 while the lock
and nim-ffi both pin 0.3.0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 00:55:59 +02:00

135 lines
4.5 KiB
Nim

import std/[strutils, json]
import chronicles, chronos, results, ffi
import
logos_delivery,
logos_delivery/waku/waku_core/topics/pubsub_topic,
logos_delivery/waku/waku_core/message,
logos_delivery/waku/waku_relay/protocol,
library/events/json_message_event,
library/declare_lib
proc wakuRelayGetPeersInMesh*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
let peers = (await lib.waku.relayPeersInMesh(PubsubTopic(pubSubTopic))).valueOr:
error "LIST_MESH_PEERS failed", error = error
return err(error)
## returns a comma-separated string of peerIDs
return ok(peers.join(","))
proc wakuRelayGetNumPeersInMesh*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
let n = (await lib.waku.relayNumPeersInMesh(PubsubTopic(pubSubTopic))).valueOr:
error "NUM_MESH_PEERS failed", error = error
return err(error)
return ok($n)
proc wakuRelayGetConnectedPeers*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
## Returns the list of all connected peers to an specific pubsub topic
let peers = (await lib.waku.relayConnectedPeers(PubsubTopic(pubSubTopic))).valueOr:
error "LIST_CONNECTED_PEERS failed", error = error
return err(error)
return ok(peers.join(","))
proc wakuRelayGetNumConnectedPeers*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
let n = (await lib.waku.relayNumConnectedPeers(PubsubTopic(pubSubTopic))).valueOr:
error "NUM_CONNECTED_PEERS failed", error = error
return err(error)
return ok($n)
proc wakuRelayAddProtectedShard*(
lib: LogosDelivery, clusterId: int32, shardId: int32, publicKey: string
): Future[Result[string, string]] {.ffi.} =
## Protects a shard with a public key
(
await lib.waku.relayAddProtectedShard(
uint16(clusterId), uint16(shardId), publicKey
)
).isOkOr:
return err(error)
return ok("")
proc wakuRelaySubscribe*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
proc receivedMessageHandler(): WakuRelayHandler =
return proc(pubsubTopic: PubsubTopic, msg: WakuMessage) {.async.} =
# This handler is `raises: [Defect]`, so the payload build has to be guarded.
try:
emitReceivedMessage(pubsubTopic, msg)
except Exception, CatchableError:
error "onReceivedMessage failed to emit event",
error = getCurrentExceptionMsg()
(
await lib.waku.relaySubscribe(
PubsubTopic(pubSubTopic), WakuRelayHandler(receivedMessageHandler())
)
).isOkOr:
error "SUBSCRIBE failed", error = error
return err(error)
return ok("")
proc wakuRelayUnsubscribe*(
lib: LogosDelivery, pubSubTopic: string
): Future[Result[string, string]] {.ffi.} =
(await lib.waku.relayUnsubscribe(PubsubTopic(pubSubTopic))).isOkOr:
error "UNSUBSCRIBE failed", error = error
return err(error)
return ok("")
proc wakuRelayPublish*(
lib: LogosDelivery, pubSubTopic: string, jsonWakuMessage: string, timeoutMs: uint32
): Future[Result[string, string]] {.ffi.} =
var jsonMessage: JsonMessage
try:
let jsonContent = parseJson(jsonWakuMessage)
jsonMessage = JsonMessage.fromJsonNode(jsonContent).valueOr:
raise newException(JsonParsingError, $error)
except JsonParsingError as exc:
return err("Error parsing json message: " & exc.msg)
let msg = json_message_event.toWakuMessage(jsonMessage).valueOr:
return err("Problem building the WakuMessage: " & $error)
let msgHash = (
await lib.waku.relayPublish(PubsubTopic(pubSubTopic), msg, uint32(timeoutMs))
).valueOr:
error "PUBLISH failed", error = error
return err(error)
return ok(msgHash)
proc wakuDefaultPubsubTopic*(
lib: LogosDelivery
): Future[Result[string, string]] {.ffi.} =
let topic = (await lib.waku.defaultPubsubTopic()).valueOr:
return err(error)
return ok(string(topic))
proc wakuContentTopic*(
lib: LogosDelivery,
appName: string,
appVersion: uint32,
contentTopicName: string,
encoding: string,
): Future[Result[string, string]] {.ffi.} =
let topic = (
await lib.waku.buildContentTopic(
appName, uint32(appVersion), contentTopicName, encoding
)
).valueOr:
return err(error)
return ok(string(topic))
proc wakuPubsubTopic*(
lib: LogosDelivery, topicName: string
): Future[Result[string, string]] {.ffi.} =
let topic = (await lib.waku.buildPubsubTopic(topicName)).valueOr:
return err(error)
return ok(string(topic))