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

83 lines
2.4 KiB
Nim

import std/[json]
import chronos, results, ffi
import stew/byteutils
import
logos_delivery/waku/common/base64,
logos_delivery/waku/waku,
logos_delivery/waku/waku_core/topics/content_topic,
logos_delivery/api/types,
../declare_lib
proc logosdeliverySubscribe*(
lib: LogosDelivery, contentTopicStr: string
): Future[Result[string, string]] {.ffi.} =
requireMessaging(lib, "Subscribe"):
return err(errMsg)
# ContentTopic is just a string type alias
let contentTopic = ContentTopic(contentTopicStr)
(await lib.messagingClient.subscribe(contentTopic)).isOkOr:
let errMsg = $error
return err("Subscribe failed: " & errMsg)
return ok("")
proc logosdeliveryUnsubscribe*(
lib: LogosDelivery, contentTopicStr: string
): Future[Result[string, string]] {.ffi.} =
requireMessaging(lib, "Unsubscribe"):
return err(errMsg)
# ContentTopic is just a string type alias
let contentTopic = ContentTopic(contentTopicStr)
lib.messagingClient.unsubscribe(contentTopic).isOkOr:
let errMsg = $error
return err("Unsubscribe failed: " & errMsg)
return ok("")
proc logosdeliverySend*(
lib: LogosDelivery, messageJson: string
): Future[Result[string, string]] {.ffi.} =
requireMessaging(lib, "Send"):
return err(errMsg)
## Parse the message JSON and send the message
var jsonNode: JsonNode
try:
jsonNode = parseJson(messageJson)
except Exception as e:
return err("Failed to parse message JSON: " & e.msg)
# Extract content topic
if not jsonNode.hasKey("contentTopic"):
return err("Missing contentTopic field")
# ContentTopic is just a string type alias
let contentTopic = ContentTopic(jsonNode["contentTopic"].getStr())
# Extract payload (expect base64 encoded string)
if not jsonNode.hasKey("payload"):
return err("Missing payload field")
let payloadStr = jsonNode["payload"].getStr()
let payload = base64.decode(Base64String(payloadStr)).valueOr:
return err("invalid payload format: " & error)
# Extract ephemeral flag
let ephemeral = jsonNode.getOrDefault("ephemeral").getBool(false)
# Create message envelope
let envelope = MessageEnvelope.init(
contentTopic = contentTopic, payload = payload, ephemeral = ephemeral
)
# Send the message via the messaging layer's own API.
let requestId = (await lib.messagingClient.send(envelope)).valueOr:
let errMsg = $error
return err("Send failed: " & errMsg)
return ok($requestId)