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
Tbecomes the opaque C typeweida_<snake(T)>, its methodT::mthe functionweida_<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_msappended when it is aDuration; - a public field of a read-only struct (
IncomingMeta) → a getterweida_<t>_<x>(h, ...).
- Releasing a handle is always
void weida_<t>_drop(weida_<t> *h). It mirrors Rust'sDrop, including its effects: an unanswered request answersNO_REPLY, an unfinished outgoing transfer is resetCANCELED, an unread incoming one is refusedREJECTED. The name never clashes with a Rust method, since Rust methods namedcloseexist (Binding::close). - Not mapped: a
&mut selfaccessor 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:0on success (or a non-negative value where documented),-WEIDA_E<NAME>on failure. - Outputs are trailing out-parameters
out(orout_<name>), written only on success. - An infallible accessor returns its value. A
dropreturnsvoid. - An
Optionscalar getter returnsint1and writes*outwhen present,0when 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
EINTRloses nothing. readandwritepoll straight into and out of the caller's buffer, with no copy of weida's own.- A
readthat returns 0 with*out_n == 0means end of payload.cap == 0is-WEIDA_EINVAL. Awritewithlen == 0returns 0 and writes*out_n = 0without 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
EAGAINorEINTR, copies every input before it returns, and spawns the work on the runtime'sExec. - 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
_waitreturns-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. _dropmarks 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
_dropreturned is undefined. - NULL given for a required pointer:
- an
intfunction returns-WEIDA_EINVAL; - a getter returns NULL or 0;
- a
_dropdoes nothing.
- an
- 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.datamay be NULL only whenlen == 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 aboveUINT64_MAXµs readsUINT64_MAX. - Default-able parameters: a parameter whose Rust type implements
Default(for exampleTransferMeta) isconst weida_<t> *, and NULL meansT::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.
- The result is NUL-terminated, and
- Bytes out that may hold key material: an owned
weida_pemthe caller drops, wiped on drop (tls.md). - Enumerations: an
inttaking aWEIDA_<TYPE>_<VARIANT>constant (a#define, emitted by cbindgen from apub 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 existingWEIDA_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 aboveusize::MAXbecomesusize::MAX, as a collect'smax_bytesalready does. - Optional values in (
Option<T>of a duration, a number or an enumeration):int64_t(anintfor an enumeration). Any negative value meansNone, as a negativetimeout_msmeans "forever" in R4. A non-negative value outsideT'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)copiesvat the call, and NULL meansT::default(), by the default-able parameter rule. - Trace context:
TraceContextis its W3C version-00traceparenttext, as aFingerprintissha256: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:
| Variant | Constant | Value |
|---|---|---|
Runtime | WEIDA_ERUNTIME | 1 |
InvalidAddress | WEIDA_EINVALID_ADDRESS | 2 |
InvalidEndpointPath | WEIDA_EINVALID_ENDPOINT_PATH | 3 |
InvalidFingerprint | WEIDA_EINVALID_FINGERPRINT | 4 |
AlreadyRegistered | WEIDA_EALREADY_REGISTERED | 5 |
NotConnected | WEIDA_ENOT_CONNECTED | 6 |
ConnectionLost | WEIDA_ECONNECTION_LOST | 7 |
Negotiation | WEIDA_ENEGOTIATION | 8 |
Protocol | WEIDA_EPROTOCOL | 9 |
Rejected | WEIDA_EREJECTED | 10 |
UnknownEndpoint | WEIDA_EUNKNOWN_ENDPOINT | 11 |
Unsupported | WEIDA_EUNSUPPORTED | 12 |
NoParkedConnection | WEIDA_ENO_PARKED_CONNECTION | 13 |
NoReply | WEIDA_ENO_REPLY | 14 |
Canceled | WEIDA_ECANCELED | 15 |
Expired | WEIDA_EEXPIRED | 16 |
Indeterminate | WEIDA_EINDETERMINATE | 17 |
LimitExceeded | WEIDA_ELIMIT_EXCEEDED | 18 |
DatagramsUnavailable | WEIDA_EDATAGRAMS_UNAVAILABLE | 19 |
TooLarge | WEIDA_ETOO_LARGE | 20 |
Tls | WEIDA_ETLS | 21 |
Untrusted | WEIDA_EUNTRUSTED | 22 |
Io | WEIDA_EIO | 23 |
Transport | WEIDA_ETRANSPORT | 24 |
The ABI's own codes:
| Constant | Value | Meaning |
|---|---|---|
WEIDA_EAGAIN | 100 | the wait gave up (R4) |
WEIDA_EINTR | 101 | a signal reached the waiting thread (R4) |
WEIDA_EINVAL | 102 | a NULL, an invalid UTF-8 string or an out-of-range argument |
WEIDA_ECLOSED | 103 | the handle was dropped, spent or consumed |
WEIDA_EPANIC | 104 | a panic was caught at the boundary (R10) |
LossCause constants:
| Constant | Value |
|---|---|
WEIDA_LOSS_IDLE_TIMEOUT | 1 |
WEIDA_LOSS_PEER_CLOSED | 2 |
WEIDA_LOSS_PEER_RESTARTING | 3 |
WEIDA_LOSS_LOCALLY_CLOSED | 4 |
WEIDA_LOSS_RESET | 5 |
WEIDA_LOSS_TRANSPORT_ERROR | 6 |
ErrorCode constants, going in (R7): the code weida_incoming_request_refuse sends, and the code the requester's op then ends with:
ErrorCode | Constant | Value | Requester's op |
|---|---|---|---|
UnknownEndpoint | WEIDA_ERROR_CODE_UNKNOWN_ENDPOINT | 1 | -WEIDA_EUNKNOWN_ENDPOINT |
Rejected | WEIDA_ERROR_CODE_REJECTED | 2 | -WEIDA_EREJECTED |
Unsupported | WEIDA_ERROR_CODE_UNSUPPORTED | 3 | -WEIDA_EUNSUPPORTED |
Internal | WEIDA_ERROR_CODE_INTERNAL | 4 | -WEIDA_ETRANSPORT |
NoReply | WEIDA_ERROR_CODE_NO_REPLY | 5 | -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): theDisplaytext, with interior NULs replaced by U+FFFD;int weida_last_error_loss_cause(void): 0 when the error is notConnectionLost;const char *weida_last_error_fingerprint(void):Untrusted's fingerprint assha256: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
intfunction storespanic: <payload>and returns-WEIDA_EPANIC. - A pointer getter returns NULL.
- A
_dropswallows 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
signalledswaps from false to true, write one byte; - clear: if
signalledswaps from true to false, read untilWouldBlock.
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:
- it clears;
- it polls under the handle's own mutex;
- on
Readyit raises again (there may be more), and onPendingit leaves the signal cleared, unless a wake raced in.
An op task stores its result and then raises.
A blocking wait loops:
- it tries;
- on
Pendingwith time left, it waits for the descriptor to become readable, with the remaining time and with no lock held; - on Unix it uses
nix::poll::poll, whoseEINTRreturns-WEIDA_EINTR; on Windows it usesWSAPoll.
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_ownedisweida::Runtime::owned; its reactor shuts down in the background once the last Rust reference is gone (OwnedReactor).weida_runtime_dropreleases the caller's reference only.weida_runtime_shutdown(rt, &op)consumesrtand runsRuntime::shutdownas an op.weida_runtime_drain(rt, deadline_ms, &op)consumesrtand runsRuntime::drainas an op whose wait yields itsweida_drainedreport.
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` */
}
}