weida

GitHub crates.io

The C ABI of weida

Rendered from docs/c/README.md at 92c768a

Contents
  1. R1. Names
  2. R2. Returns
  3. R3. Async mapping
  4. R4. Timeouts
  5. R5. Handles and threads
  6. R6. Consuming
  7. R7. Values
  8. R8. Messages
  9. R9. Errors
  10. R10. Panics
  11. R11. Readiness
  12. R12. Signals
  13. R13. Runtime lifetime
  14. The EINTR retry loop

libweida (crates/weida-c) is the boundary every non-Rust language crosses (decisions/0045). Its header is crates/weida-c/include/weida.h, generated by cbindgen and committed; this directory is the normative prose. Rust callers never go through it: they use the async API of the weida crate on their own Tokio runtime.

The rules below (R1 to R13) are normative for every function the library exports, now and in later stages. The pages beside this one document each function of the current slice: runtime.md, tls.md, identity.md, resolver.md, listener.md, relay.md, requester.md, push.md, pubsub.md, pair.md, survey.md, bus.md, radio.md, cursor.md, peer.md, swarm.md, flow.md, transfer.md, msg.md, poll.md, stats.md and errors.md. What is not yet mapped is listed in libraries/weida-c.md.

The easy tier, crates/weida-c/include/weida_easy.h, is not part of the ABI: it is C source over it, header-only helpers that run a Req/Rep step as one blocking call with one deadline. easy.md documents it.

R1. Names

  • A Rust type T becomes the opaque C type weida_<snake(T)>, its method T::m the function weida_<snake(T)>_<m>. Examples: IncomingTransfer → weida_incoming_transfer, IncomingTransfer::collect → weida_incoming_transfer_collect.
  • Constructors keep their Rust names: T::new → weida_<t>_new, Runtime::owned → weida_runtime_owned, Identity::generate → weida_identity_generate, Identity::from_pem → weida_identity_from_pem.
  • Builders:
    • with_x(self, v) → weida_<t>_set_x(h, v);
    • and_x(self, v) → weida_<t>_add_x(h, v);
    • a public config field x → weida_<t>_set_x(h, v), with _ms appended when it is a Duration;
    • a public field of a read-only struct (IncomingMeta) → a getter weida_<t>_<x>(h, ...).
  • Releasing a handle is always void weida_<t>_drop(weida_<t> *h). It mirrors Rust's Drop, including its effects: an unanswered request answers NO_REPLY, an unfinished outgoing transfer is reset CANCELED, an unread incoming one is refused REJECTED. The name never clashes with a Rust method, since Rust methods named close exist (Binding::close).
  • Not mapped: a &mut self accessor that lends out a sub-handle (IncomingRequest::body), because a lent handle has no C lifetime. Its owning twin (take_body) is mapped.
  • In Rust, each opaque type is a struct named exactly like its C name, under #![allow(non_camel_case_types)], so cbindgen needs no rename table.

R2. Returns

  • A fallible function returns int: 0 on success (or a non-negative value where documented), -WEIDA_E<NAME> on failure.
  • Outputs are trailing out-parameters out (or out_<name>), written only on success.
  • An infallible accessor returns its value. A drop returns void.
  • An Option scalar getter returns int 1 and writes *out when present, 0 when absent.

R3. Async mapping

There are three kinds of call.

(a) Tries: on the caller's thread. These are AsyncRead::poll_read, AsyncWrite::poll_write, and an async fn(&self) that takes the next item of an endpoint's queue (Replier::accept). Signatures:

  • int weida_<t>_<m>(weida_<t> *h, int64_t timeout_ms, <out>);
  • int weida_<t>_read(h, uint8_t *buf, size_t cap, int64_t timeout_ms, size_t *out_n);
  • int weida_<t>_write(h, const uint8_t *buf, size_t len, int64_t timeout_ms, size_t *out_n).

How a try runs:

  • It polls with the handle's own waker. A queue take keeps its in-flight future in the handle across tries and never recreates it, so a timeout or EINTR loses nothing.
  • read and write poll straight into and out of the caller's buffer, with no copy of weida's own.
  • A read that returns 0 with *out_n == 0 means end of payload. cap == 0 is -WEIDA_EINVAL. A write with len == 0 returns 0 and writes *out_n = 0 without touching the stream.

(b) Pending operations: spawned on the reactor. Every other async fn, whether it takes self, &self or &mut self, is a start function int weida_<t>_<m>(h, <args>, weida_<t>_<m>_op **out).

  • It never blocks and never returns EAGAIN or EINTR, copies every input before it returns, and spawns the work on the runtime's Exec.
  • The op has _fd, _wait(op, int64_t timeout_ms, <outs>) and _drop. Dropping an op that has not finished aborts its task.
  • Its result is taken once; every later _wait returns -WEIDA_ECLOSED.

(c) Loops not mapped. An async fn(&mut self) that only loops over a poll method this ABI maps (write_all, read_capped) is not mapped; the caller loops. A consuming loop (collect(self, max)) is mapped as a (b) op that owns the value.

Sync Rust methods map to plain functions.

R4. Timeouts

A timeout_ms below 0 waits forever, 0 only tries, and a positive value is a bound.

  • When the wait gives up, the call returns -WEIDA_EAGAIN.
  • A signal delivered to the waiting thread returns -WEIDA_EINTR. The caller recomputes its remaining time and calls again.
  • On Windows there is no EINTR.

R5. Handles and threads

  • A handle pointer is Arc::into_raw(Arc<Inner>), and every call holds its own clone for its duration.
  • _drop marks the handle dropped, wakes every wait on it with -WEIDA_ECLOSED, and releases the caller's reference. The Rust value is dropped when the last in-progress call returns.
  • Using a pointer after its _drop returned is undefined.
  • NULL given for a required pointer:
    • an int function returns -WEIDA_EINVAL;
    • a getter returns NULL or 0;
    • a _drop does nothing.
  • Every call on any handle is thread-safe.

R6. Consuming

A Rust method taking self maps to a C function that consumes its handle on every return path. The caller neither uses nor drops the handle afterwards. The docs mark such functions "consumes".

R7. Values

  • Strings in: NUL-terminated UTF-8 const char *. Anything else returns -WEIDA_EINVAL.
  • Bytes in: const uint8_t *data, size_t len. data may be NULL only when len == 0.
  • Durations in: milliseconds as uint64_t.
  • Durations out: microseconds as uint64_t, the getter's name ending in _us (weida_connection_stats_age_us); a duration above UINT64_MAX µs reads UINT64_MAX.
  • Default-able parameters: a parameter whose Rust type implements Default (for example TransferMeta) is const weida_<t> *, and NULL means T::default().
  • Strings out from a handle: const char *weida_<t>_<x>(const weida_<t> *h, size_t *len_out).
    • The result is NUL-terminated, and len_out (NULL allowed) receives the exact byte length, so an interior NUL is representable.
    • The result is NULL when the value is absent.
    • The pointer is valid until that handle is dropped or consumed.
  • Bytes out that may hold key material: an owned weida_pem the caller drops, wiped on drop (tls.md).
  • Enumerations: an int taking a WEIDA_<TYPE>_<VARIANT> constant (a #define, emitted by cbindgen from a pub const ...: c_int). The value is the Rust enum's wire value where it has one (to_wire), otherwise its declaration order from 0. Any other value returns -WEIDA_EINVAL. The existing WEIDA_LOSS_* constants are the same kind, going out.
  • Flags in: int; 0 is false, any other value is true.
  • Counts in (usize): uint64_t. A value above usize::MAX becomes usize::MAX, as a collect's max_bytes already does.
  • Optional values in (Option<T> of a duration, a number or an enumeration): int64_t (an int for an enumeration). Any negative value means None, as a negative timeout_ms means "forever" in R4. A non-negative value outside T's range returns -WEIDA_EINVAL.
  • Nested configuration: a public config field whose type is itself a configuration struct (Limits, GuaranteeSet, ReconnectPolicy) is its own builder handle. The parent's _set_x(h, const weida_<t> *v) copies v at the call, and NULL means T::default(), by the default-able parameter rule.
  • Trace context: TraceContext is its W3C version-00 traceparent text, as a Fingerprint is sha256: text. A malformed text returns -WEIDA_EINVAL.

R8. Messages

weida_msg is what a collect op yields: the owned payload (weida_msg_data, weida_msg_len) plus the meta of the transfer it consumed (weida_msg_meta). Metadata is its own handle, weida_incoming_meta. weida_*_meta(h, &out) returns a new reference that the caller drops, so metadata outlives the transfer or request it came from.

R9. Errors

Constants for weida_core::Error, one per variant, in declaration order:

VariantConstantValue
RuntimeWEIDA_ERUNTIME1
InvalidAddressWEIDA_EINVALID_ADDRESS2
InvalidEndpointPathWEIDA_EINVALID_ENDPOINT_PATH3
InvalidFingerprintWEIDA_EINVALID_FINGERPRINT4
AlreadyRegisteredWEIDA_EALREADY_REGISTERED5
NotConnectedWEIDA_ENOT_CONNECTED6
ConnectionLostWEIDA_ECONNECTION_LOST7
NegotiationWEIDA_ENEGOTIATION8
ProtocolWEIDA_EPROTOCOL9
RejectedWEIDA_EREJECTED10
UnknownEndpointWEIDA_EUNKNOWN_ENDPOINT11
UnsupportedWEIDA_EUNSUPPORTED12
NoParkedConnectionWEIDA_ENO_PARKED_CONNECTION13
NoReplyWEIDA_ENO_REPLY14
CanceledWEIDA_ECANCELED15
ExpiredWEIDA_EEXPIRED16
IndeterminateWEIDA_EINDETERMINATE17
LimitExceededWEIDA_ELIMIT_EXCEEDED18
DatagramsUnavailableWEIDA_EDATAGRAMS_UNAVAILABLE19
TooLargeWEIDA_ETOO_LARGE20
TlsWEIDA_ETLS21
UntrustedWEIDA_EUNTRUSTED22
IoWEIDA_EIO23
TransportWEIDA_ETRANSPORT24

The ABI's own codes:

ConstantValueMeaning
WEIDA_EAGAIN100the wait gave up (R4)
WEIDA_EINTR101a signal reached the waiting thread (R4)
WEIDA_EINVAL102a NULL, an invalid UTF-8 string or an out-of-range argument
WEIDA_ECLOSED103the handle was dropped, spent or consumed
WEIDA_EPANIC104a panic was caught at the boundary (R10)

LossCause constants:

ConstantValue
WEIDA_LOSS_IDLE_TIMEOUT1
WEIDA_LOSS_PEER_CLOSED2
WEIDA_LOSS_PEER_RESTARTING3
WEIDA_LOSS_LOCALLY_CLOSED4
WEIDA_LOSS_RESET5
WEIDA_LOSS_TRANSPORT_ERROR6

ErrorCode constants, going in (R7): the code weida_incoming_request_refuse sends, and the code the requester's op then ends with:

ErrorCodeConstantValueRequester's op
UnknownEndpointWEIDA_ERROR_CODE_UNKNOWN_ENDPOINT1-WEIDA_EUNKNOWN_ENDPOINT
RejectedWEIDA_ERROR_CODE_REJECTED2-WEIDA_EREJECTED
UnsupportedWEIDA_ERROR_CODE_UNSUPPORTED3-WEIDA_EUNSUPPORTED
InternalWEIDA_ERROR_CODE_INTERNAL4-WEIDA_ETRANSPORT
NoReplyWEIDA_ERROR_CODE_NO_REPLY5-WEIDA_ENO_REPLY

The thread-local record. Every failing int function stores a record on its own thread; success does not clear it. It is read with:

  • const char *weida_last_error_message(void): the Display text, with interior NULs replaced by U+FFFD;
  • int weida_last_error_loss_cause(void): 0 when the error is not ConnectionLost;
  • const char *weida_last_error_fingerprint(void): Untrusted's fingerprint as sha256: text, otherwise NULL;
  • int64_t weida_last_error_max(void): TooLarge.max, otherwise -1;
  • int weida_last_error_os_code(void): Io's raw OS error, otherwise 0.

Lookup. const char *weida_strerror(int code) takes either sign and gives "unknown error" for an unknown code.

Exhaustiveness. The variant mapping is one exhaustive match, so a new variant does not compile without a code.

R10. Panics

Every exported body runs in catch_unwind(AssertUnwindSafe(..)).

  • A caught panic in an int function stores panic: <payload> and returns -WEIDA_EPANIC.
  • A pointer getter returns NULL.
  • A _drop swallows it.

R11. Readiness

The contract. A handle's descriptor is readable when the next try or _wait on that handle will not block. That call may still return -WEIDA_EAGAIN once, after a wake that turned out stale. After an EAGAIN the descriptor stays unreadable until there is news.

  • For an op, the descriptor is readable exactly while its result is waiting.
  • For a try handle, it is readable from a wake until a try returns EAGAIN.

The descriptor is created lazily, on the first _fd or the first blocking wait.

  • Unix: std::os::unix::net::UnixStream::pair(), non-blocking.
  • Windows: a loopback TCP pair. Bind 127.0.0.1:0, connect, and accept until the accepted peer address equals the connector's local address, dropping strangers. Both ends are non-blocking.

Signalling is an AtomicBool signalled plus the pair:

  • raise: if signalled swaps from false to true, write one byte;
  • clear: if signalled swaps from true to false, read until WouldBlock.

The waker (std::task::Wake) raises, and takes no other lock, so a wake can never deadlock against a poll in progress.

A try does three things, in order:

  1. it clears;
  2. it polls under the handle's own mutex;
  3. on Ready it raises again (there may be more), and on Pending it leaves the signal cleared, unless a wake raced in.

An op task stores its result and then raises.

A blocking wait loops:

  1. it tries;
  2. on Pending with time left, it waits for the descriptor to become readable, with the remaining time and with no lock held;
  3. on Unix it uses nix::poll::poll, whose EINTR returns -WEIDA_EINTR; on Windows it uses WSAPoll.

R12. Signals

weida_runtime::Exec::owned blocks every signal except SIGSEGV, SIGBUS, SIGILL and SIGFPE on all its threads, the blocking pool included, as libzmq does for its I/O threads. A process-directed signal therefore reaches a caller thread, whose poll returns EINTR.

R13. Runtime lifetime

  • weida_runtime_owned is weida::Runtime::owned; its reactor shuts down in the background once the last Rust reference is gone (OwnedReactor).
  • weida_runtime_drop releases the caller's reference only.
  • weida_runtime_shutdown(rt, &op) consumes rt and runs Runtime::shutdown as an op.
  • weida_runtime_drain(rt, deadline_ms, &op) consumes rt and runs Runtime::drain as an op whose wait yields its weida_drained report.

The EINTR retry loop

A blocking caller that wants a bound across signals recomputes its remaining time after every -WEIDA_EINTR, and checks its own flag (set by its signal handler) before trying again:

#include <signal.h>
#include <time.h>
#include "weida.h"

extern volatile sig_atomic_t stop_requested;

static int64_t now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

/* Accepts one request within `budget_ms`, surviving signals. */
int accept_within(weida_replier *r, int64_t budget_ms, weida_incoming_request **out) {
    int64_t deadline = now_ms() + budget_ms;
    for (;;) {
        int64_t left = deadline - now_ms();
        if (left < 0)
            left = 0;
        int rc = weida_replier_accept(r, left, out);
        if (rc != -WEIDA_EINTR)
            return rc; /* 0, -WEIDA_EAGAIN on timeout, or another failure */
        if (stop_requested)
            return rc;
        /* nothing was lost: the in-flight accept stays in `r` */
    }
}