Ivan Folgueira Bande 2f32e733aa refactor(cbindings): Thread-safe communication between the main thread and the Waku Thread (#1978)
* Thread-safe comms between main thread & Waku Thread - ChannelSPSCSingle.
* Renaming procs from 'new' to 'createShared'. They use the shared allocator.
* peer_manager_request: no need to use ptr WakuNode.
* waku_thread: moving the 'waitFor' to upper layer.
* waku_thread: `poll()` -> `waitFor sleepAsync(1)` to avoid risk of blocking.
* libwaku: thread-safe "sub-objects" in an inter-thread requests.
  When two threads send data each other, that data cannot contain any
  GC'ed type (string, seq, ref, closures) at any level.
* Allocating the 'configJson' in main thread and deallocating in Waku Thread.
2023-09-18 09:21:50 +02:00

54 lines
1.5 KiB
Nim

## This file contains the base message response type that will be handled.
## The response will be created from the Waku Thread and processed in
## the main thread.
import
std/json,
stew/results
type
ResponseType {.pure.} = enum
OK,
ERR,
type
InterThreadResponse* = object
respType: ResponseType
content: cstring
proc createShared*(T: type InterThreadResponse,
res: Result[string, string]): ptr type T =
## Converts a `Result[string, string]` into a `ptr InterThreadResponse`
## so that it can be transfered to another thread in a safe way.
var ret = createShared(T)
if res.isOk():
let value = res.get()
ret[].respType = ResponseType.OK
ret[].content = cast[cstring](allocShared0(value.len + 1))
copyMem(ret[].content, unsafeAddr value, value.len + 1)
else:
let error = res.error
ret[].respType = ResponseType.ERR
ret[].content = cast[cstring](allocShared0(error.len + 1))
copyMem(ret[].content, unsafeAddr error, error.len + 1)
return ret
proc process*(T: type InterThreadResponse,
resp: ptr InterThreadResponse):
Result[string, string] =
## Converts the received `ptr InterThreadResponse` into a
## `Result[string, string]`. Notice that the response is expected to be
## allocated from the Waku Thread and deallocated by the main thread.
defer:
deallocShared(resp[].content)
deallocShared(resp)
case resp[].respType
of OK:
return ok($resp[].content)
of ERR:
return err($resp[].content)