2026-06-03 12:14:29 +02:00
|
|
|
## C-compatible FFI wrapper around the SDS ReliabilityManager.
|
|
|
|
|
##
|
2026-06-03 13:22:11 +02:00
|
|
|
## Built on nim-ffi (v0.2.0+): `declareLibrary` emits the bootstrap plus the
|
|
|
|
|
## event-listener ABI (`sds_add_event_listener` / `sds_remove_event_listener`);
|
|
|
|
|
## `{.ffiCtor.}`/`{.ffi.}`/`{.ffiDtor.}` generate the C entry points; and
|
|
|
|
|
## `{.ffiEvent.}` declares library-initiated events. Requests, responses and
|
|
|
|
|
## events are marshalled as CBOR (see library/libsds.h). Exported C names are
|
|
|
|
|
## snake_case. The Go bindings (sds-go-bindings) must match this API.
|
2026-06-03 12:14:29 +02:00
|
|
|
##
|
2026-06-03 13:22:11 +02:00
|
|
|
## The one hand-written export is `sds_set_retrieval_hint_provider`: it takes a
|
|
|
|
|
## C function pointer (no CBOR representation), so it dispatches a request that
|
|
|
|
|
## stores the provider in a worker-thread thread-local.
|
2026-06-03 12:14:29 +02:00
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
import std/[sequtils]
|
2026-06-03 09:46:52 +02:00
|
|
|
import ffi
|
|
|
|
|
import sds
|
|
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
# Bootstrap + sds_add_event_listener / sds_remove_event_listener.
|
2026-06-03 12:14:29 +02:00
|
|
|
declareLibrary("sds", ReliabilityManager)
|
2026-06-03 09:46:52 +02:00
|
|
|
|
|
|
|
|
type SdsRetrievalHintProvider* = proc(
|
|
|
|
|
messageId: cstring, hint: ptr cstring, hintLen: ptr csize_t, userData: pointer
|
|
|
|
|
) {.cdecl, gcsafe, raises: [].}
|
|
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
# Active retrieval-hint provider, per worker thread (one thread per context).
|
|
|
|
|
# Set by sds_set_retrieval_hint_provider through a dispatched request so the
|
|
|
|
|
# write lands on the worker thread, where the manager's hint closure reads it.
|
2026-06-03 12:14:29 +02:00
|
|
|
var sdsRetrievalHintCb {.threadvar.}: pointer
|
|
|
|
|
var sdsRetrievalHintUserData {.threadvar.}: pointer
|
2025-05-29 16:48:53 +05:30
|
|
|
|
|
|
|
|
################################################################################
|
2026-06-03 13:22:11 +02:00
|
|
|
### CBOR-marshalled request/response types
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
type SdsConfig* {.ffi.} = object
|
|
|
|
|
participantId: string ## empty disables SDS-R (see newReliabilityManager)
|
|
|
|
|
|
|
|
|
|
type SdsWrapRequest* {.ffi.} = object
|
|
|
|
|
message: seq[byte]
|
|
|
|
|
messageId: string
|
|
|
|
|
channelId: string
|
|
|
|
|
|
|
|
|
|
type SdsWrapResponse* {.ffi.} = object
|
|
|
|
|
message: seq[byte]
|
|
|
|
|
|
|
|
|
|
type SdsUnwrapRequest* {.ffi.} = object
|
|
|
|
|
message: seq[byte]
|
|
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
type SdsMissingDep* {.ffi.} = object
|
|
|
|
|
messageId: string
|
|
|
|
|
retrievalHint: seq[byte]
|
|
|
|
|
|
|
|
|
|
type SdsUnwrapResponse* {.ffi.} = object
|
|
|
|
|
message: seq[byte]
|
|
|
|
|
channelId: string
|
|
|
|
|
missingDeps: seq[SdsMissingDep]
|
|
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
type SdsMarkDependenciesRequest* {.ffi.} = object
|
|
|
|
|
messageIds: seq[string]
|
|
|
|
|
channelId: string
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
################################################################################
|
|
|
|
|
### Library-initiated events
|
|
|
|
|
###
|
|
|
|
|
### Each {.ffiEvent.} proc is an emitter: calling it from a worker-thread
|
|
|
|
|
### handler dispatches a CBOR EventEnvelope to every listener subscribed (via
|
|
|
|
|
### sds_add_event_listener) to the matching wire name.
|
|
|
|
|
|
|
|
|
|
type SdsMessageReadyPayload* {.ffi.} = object
|
|
|
|
|
messageId: string
|
|
|
|
|
channelId: string
|
|
|
|
|
|
|
|
|
|
type SdsMessageSentPayload* {.ffi.} = object
|
|
|
|
|
messageId: string
|
|
|
|
|
channelId: string
|
|
|
|
|
|
|
|
|
|
type SdsMissingDependenciesPayload* {.ffi.} = object
|
|
|
|
|
messageId: string
|
|
|
|
|
channelId: string
|
|
|
|
|
missingDeps: seq[SdsMissingDep]
|
|
|
|
|
|
|
|
|
|
type SdsPeriodicSyncPayload* {.ffi.} = object
|
|
|
|
|
placeholder: bool ## events need a payload type; periodic sync carries no data
|
|
|
|
|
|
|
|
|
|
type SdsRepairReadyPayload* {.ffi.} = object
|
|
|
|
|
message: seq[byte]
|
|
|
|
|
channelId: string
|
|
|
|
|
|
|
|
|
|
proc emitMessageReady*(p: SdsMessageReadyPayload) {.ffiEvent: "message_ready".}
|
|
|
|
|
proc emitMessageSent*(p: SdsMessageSentPayload) {.ffiEvent: "message_sent".}
|
|
|
|
|
proc emitMissingDependencies*(
|
|
|
|
|
p: SdsMissingDependenciesPayload
|
|
|
|
|
) {.ffiEvent: "missing_dependencies".}
|
|
|
|
|
proc emitPeriodicSync*(p: SdsPeriodicSyncPayload) {.ffiEvent: "periodic_sync".}
|
|
|
|
|
proc emitRepairReady*(p: SdsRepairReadyPayload) {.ffiEvent: "repair_ready".}
|
|
|
|
|
|
2026-06-03 09:46:52 +02:00
|
|
|
################################################################################
|
2026-06-03 12:14:29 +02:00
|
|
|
### Constructor — creates the FFI context and the ReliabilityManager.
|
2026-06-03 09:46:52 +02:00
|
|
|
###
|
2026-06-03 13:22:11 +02:00
|
|
|
### The AppCallbacks closures run on the worker thread; they build typed
|
|
|
|
|
### payloads and fire the {.ffiEvent.} emitters, which reach the C listeners.
|
2026-06-03 12:14:29 +02:00
|
|
|
|
|
|
|
|
proc sdsCreate*(
|
|
|
|
|
config: SdsConfig
|
|
|
|
|
): Future[Result[ReliabilityManager, string]] {.ffiCtor.} =
|
|
|
|
|
let rm = newReliabilityManager(participantId = config.participantId.SdsParticipantID).valueOr:
|
|
|
|
|
error "Failed creating reliability manager", error = error
|
|
|
|
|
return err("Failed creating reliability manager: " & $error)
|
|
|
|
|
|
|
|
|
|
let messageReadyCb = proc(
|
|
|
|
|
messageId: SdsMessageID, channelId: SdsChannelID
|
|
|
|
|
) {.gcsafe.} =
|
2026-06-03 13:22:11 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
|
emitMessageReady(
|
|
|
|
|
SdsMessageReadyPayload(messageId: $messageId, channelId: $channelId)
|
|
|
|
|
)
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
let messageSentCb = proc(
|
|
|
|
|
messageId: SdsMessageID, channelId: SdsChannelID
|
|
|
|
|
) {.gcsafe.} =
|
2026-06-03 13:22:11 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
|
emitMessageSent(
|
|
|
|
|
SdsMessageSentPayload(messageId: $messageId, channelId: $channelId)
|
|
|
|
|
)
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
let missingDependenciesCb = proc(
|
feat: make Persistence interface async (#69)
* feat: make Persistence interface async
The 14 Persistence proc fields now return Future[...] with
{.async: (raises: []), gcsafe.}, allowing real I/O backends (SQLite,
encrypted file, network) to suspend rather than block the Chronos event
loop the manager runs on.
Propagates through:
- ReliabilityManager.lock: system.Lock -> chronos.AsyncLock. Acquired
across awaits cleanly; matches the single-threaded Chronos worker the
FFI uses. Multi-OS-thread use is now explicitly the caller's
responsibility.
- sds_utils + sds.nim public API procs (wrapOutgoingMessage,
unwrapReceivedMessage, markDependenciesMet, setCallbacks,
resetReliabilityManager, cleanup, ensureChannel, removeChannel, the
getter snapshots, etc.) are now async.
- FFI request handlers in library/sds_thread/... await the new API.
- Tests converted via an asyncTest template that wraps each test body
in an async proc; setup/teardown use waitFor for their single async
call (ensureChannel / cleanup).
Lock scope is preserved exactly: the same call sites that held the
kernel Lock today hold AsyncLock now -- no new locking added.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor: drop asyncSpawn, add asyncSetup/asyncTeardown
Three asyncSpawn usages removed:
- sds.nim startPeriodicTasks: stored the periodic-task futures on
ReliabilityManager (new field `periodicTasks: seq[FutureBase]`) so
cleanup can cancel them on shutdown instead of leaking the loops
against a cleared manager.
- library/sds_thread/sds_thread.nim: fireSync moved BEFORE processing,
then `await SdsThreadRequest.process(...)` instead of asyncSpawn'ing
it. Aligns the worker with the SP-channel + lock assumption that
there are no concurrent requests; caller throughput is unchanged
because the caller only waits for receipt (fireSync), not processing.
- tests TestBus repair callback: replaced asyncSpawn(deliverExcept...)
with an explicit pending-delivery queue drained by `bus.drain()`.
Integration tests no longer rely on `sleepAsync(10ms)` to let
spawned deliveries finish — they await drain instead.
Tests also pick up an asyncSetup/asyncTeardown pair (tests/async_unittest.nim)
so suite fixtures can `await` directly. All `waitFor` in setup/teardown
blocks is gone; only the top-level asyncTest wrapper still uses waitFor
(once, to drive the async proc to completion).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* Correctly propagate error hidden by new async move
* Correctly handle future cancellation exceptions, +some housekeeping
* Apply suggestion from @Ivansete-status
Co-authored-by: Ivan FB <128452529+Ivansete-status@users.noreply.github.com>
* Stylistics, async default implication addressed, nph style run
* Remove leaking CancelledFuture from public facing + as a consequence it is tuneled into handling CatchableError everywhere
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Ivan FB <128452529+Ivansete-status@users.noreply.github.com>
2026-05-25 22:30:15 +02:00
|
|
|
messageId: SdsMessageID, missingDeps: seq[HistoryEntry], channelId: SdsChannelID
|
|
|
|
|
) {.gcsafe.} =
|
2026-06-03 13:22:11 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
|
let deps = missingDeps.mapIt(
|
|
|
|
|
SdsMissingDep(messageId: $it.messageId, retrievalHint: it.retrievalHint)
|
|
|
|
|
)
|
|
|
|
|
emitMissingDependencies(
|
|
|
|
|
SdsMissingDependenciesPayload(
|
|
|
|
|
messageId: $messageId, channelId: $channelId, missingDeps: deps
|
|
|
|
|
)
|
|
|
|
|
)
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
let periodicSyncCb = proc() {.gcsafe.} =
|
2026-06-03 13:22:11 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
|
emitPeriodicSync(SdsPeriodicSyncPayload(placeholder: false))
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
let repairReadyCb = proc(message: seq[byte], channelId: SdsChannelID) {.gcsafe.} =
|
2026-06-03 13:22:11 +02:00
|
|
|
{.cast(gcsafe).}:
|
|
|
|
|
emitRepairReady(SdsRepairReadyPayload(message: message, channelId: $channelId))
|
2026-05-01 18:35:38 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
let retrievalHintProvider = proc(messageId: SdsMessageID): seq[byte] {.gcsafe.} =
|
|
|
|
|
if sdsRetrievalHintCb.isNil():
|
2026-01-29 15:22:40 +05:30
|
|
|
return @[]
|
|
|
|
|
var hint: cstring
|
|
|
|
|
var hintLen: csize_t
|
2026-06-03 12:14:29 +02:00
|
|
|
cast[SdsRetrievalHintProvider](sdsRetrievalHintCb)(
|
|
|
|
|
messageId.cstring, addr hint, addr hintLen, sdsRetrievalHintUserData
|
2026-01-29 15:22:40 +05:30
|
|
|
)
|
2026-06-03 09:46:52 +02:00
|
|
|
if not hint.isNil() and hintLen > 0:
|
2026-01-29 15:22:40 +05:30
|
|
|
var hintBytes = newSeq[byte](hintLen)
|
|
|
|
|
copyMem(addr hintBytes[0], hint, hintLen)
|
|
|
|
|
deallocShared(hint)
|
|
|
|
|
return hintBytes
|
|
|
|
|
return @[]
|
|
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
await rm.setCallbacks(
|
|
|
|
|
messageReadyCb, messageSentCb, missingDependenciesCb, periodicSyncCb,
|
|
|
|
|
retrievalHintProvider, repairReadyCb,
|
|
|
|
|
)
|
2026-06-03 09:46:52 +02:00
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
return ok(rm)
|
2025-05-29 16:48:53 +05:30
|
|
|
|
|
|
|
|
################################################################################
|
2026-06-03 12:14:29 +02:00
|
|
|
### Async methods — each runs its body on the worker thread.
|
|
|
|
|
|
|
|
|
|
proc sdsWrapOutgoingMessage*(
|
|
|
|
|
rm: ReliabilityManager, req: SdsWrapRequest
|
|
|
|
|
): Future[Result[SdsWrapResponse, string]] {.ffi.} =
|
|
|
|
|
let wrapped = (
|
|
|
|
|
await wrapOutgoingMessage(
|
|
|
|
|
rm, req.message, req.messageId.SdsMessageID, req.channelId.SdsChannelID
|
|
|
|
|
)
|
|
|
|
|
).valueOr:
|
|
|
|
|
error "WRAP_MESSAGE failed", error = error
|
|
|
|
|
return err("error processing wrap request: " & $error)
|
|
|
|
|
return ok(SdsWrapResponse(message: wrapped))
|
|
|
|
|
|
|
|
|
|
proc sdsUnwrapReceivedMessage*(
|
|
|
|
|
rm: ReliabilityManager, req: SdsUnwrapRequest
|
2026-06-03 13:22:11 +02:00
|
|
|
): Future[Result[SdsUnwrapResponse, string]] {.ffi.} =
|
2026-06-03 12:14:29 +02:00
|
|
|
let (unwrapped, missingDeps, channelId) = (
|
|
|
|
|
await unwrapReceivedMessage(rm, req.message)
|
|
|
|
|
).valueOr:
|
|
|
|
|
return err("error processing unwrap request: " & $error)
|
|
|
|
|
|
2026-06-03 13:22:11 +02:00
|
|
|
let deps = missingDeps.mapIt(
|
|
|
|
|
SdsMissingDep(messageId: $it.messageId, retrievalHint: it.retrievalHint)
|
|
|
|
|
)
|
|
|
|
|
return ok(
|
|
|
|
|
SdsUnwrapResponse(message: unwrapped, channelId: $channelId, missingDeps: deps)
|
|
|
|
|
)
|
2026-06-03 12:14:29 +02:00
|
|
|
|
|
|
|
|
proc sdsMarkDependenciesMet*(
|
|
|
|
|
rm: ReliabilityManager, req: SdsMarkDependenciesRequest
|
|
|
|
|
): Future[Result[string, string]] {.ffi.} =
|
|
|
|
|
let messageIds = req.messageIds.mapIt(it.SdsMessageID)
|
|
|
|
|
(await markDependenciesMet(rm, messageIds, req.channelId.SdsChannelID)).isOkOr:
|
|
|
|
|
error "MARK_DEPENDENCIES_MET failed", error = error
|
|
|
|
|
return err("error processing mark-dependencies request: " & $error)
|
|
|
|
|
return ok("")
|
|
|
|
|
|
|
|
|
|
proc sdsReset*(rm: ReliabilityManager): Future[Result[string, string]] {.ffi.} =
|
|
|
|
|
(await resetReliabilityManager(rm)).isOkOr:
|
|
|
|
|
error "RESET failed", error = error
|
|
|
|
|
return err("error processing reset request: " & $error)
|
|
|
|
|
return ok("")
|
|
|
|
|
|
|
|
|
|
proc sdsStartPeriodicTasks*(
|
|
|
|
|
rm: ReliabilityManager
|
|
|
|
|
): Future[Result[string, string]] {.ffi.} =
|
|
|
|
|
# The empty await forces the macro down its async path so the body runs on the
|
|
|
|
|
# worker thread — startPeriodicTasks schedules futures on that thread's loop.
|
|
|
|
|
await sleepAsync(chronos.milliseconds(0))
|
|
|
|
|
rm.startPeriodicTasks()
|
|
|
|
|
return ok("")
|
2025-05-29 16:48:53 +05:30
|
|
|
|
|
|
|
|
################################################################################
|
2026-06-03 12:14:29 +02:00
|
|
|
### Destructor — runs library cleanup then tears down the FFI context.
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
proc sdsDestroy*(rm: ReliabilityManager) {.ffiDtor.} =
|
|
|
|
|
discard
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
################################################################################
|
2026-06-03 13:22:11 +02:00
|
|
|
### Retrieval-hint provider.
|
|
|
|
|
###
|
|
|
|
|
### The provider is a C function pointer, which has no CBOR representation, so
|
|
|
|
|
### it is passed as integer addresses. The body runs on the worker thread (the
|
|
|
|
|
### empty await forces the async path) and stores the pointers in the
|
|
|
|
|
### thread-local that sdsCreate's hint closure reads. The caller passes the
|
|
|
|
|
### function pointer and user-data as uint64 addresses.
|
|
|
|
|
|
|
|
|
|
type SdsHintProviderRequest* {.ffi.} = object
|
|
|
|
|
callbackAddr: uint64
|
|
|
|
|
userDataAddr: uint64
|
|
|
|
|
|
|
|
|
|
proc sdsSetRetrievalHintProvider*(
|
|
|
|
|
rm: ReliabilityManager, req: SdsHintProviderRequest
|
|
|
|
|
): Future[Result[string, string]] {.ffi.} =
|
|
|
|
|
discard rm
|
|
|
|
|
await sleepAsync(chronos.milliseconds(0))
|
|
|
|
|
sdsRetrievalHintCb = cast[pointer](req.callbackAddr)
|
|
|
|
|
sdsRetrievalHintUserData = cast[pointer](req.userDataAddr)
|
|
|
|
|
return ok("")
|
2025-05-29 16:48:53 +05:30
|
|
|
|
2026-06-03 12:14:29 +02:00
|
|
|
# Emit binding metadata (no-op unless -d:ffiGenBindings). Must follow every
|
2026-06-03 13:22:11 +02:00
|
|
|
# {.ffi.}/{.ffiCtor.}/{.ffiDtor.}/{.ffiEvent.} annotation.
|
2026-06-03 12:14:29 +02:00
|
|
|
genBindings()
|