Ruby
The Ruby target generates a pure-Ruby gem that binds the C ABI (revision 6)
through the ffi gem. There’s no native
extension to compile: the gem depends on ffi ~> 1.16 and loads the
producer’s shared library at require time. Ruby 3.2 or newer is required
(the gemspec says so in required_ruby_version).
Ruby is a Tier 2 target: it may lag a new ABI revision for a while, but it passes the same conformance suite as every other target before a release.
What gets generated
For a package named kvstore (prefix kvstore, library kvstore):
ruby/
kvstore.gemspec gem `kvstore`, Ruby >= 3.2, depends on ffi ~> 1.16
README.md
lib/
kvstore.rb require 'kvstore': module Kvstore, the bindings
kvstore/
runtime.rb loader, load-time checks, errors, marshalling
Names come from the package identity:
| Name | Default | Override ([generators.ruby]) |
|---|---|---|
| Gem | the package name (key-store) | name |
| Ruby module | the package name in PascalCase (KeyStore) | module_name |
require path | the C prefix (key_store) | none |
A library is one namespace, so every declaration lives directly in the one
Ruby module: Kvstore::Store, Kvstore::Entry, Kvstore.render_report.
The module’s public surface is only the idiomatic API: error classes, enum
constants, records, rich enums, interface classes, callback-interface
modules, and library functions. The C functions are attached in a private
Native module, and the marshalling the wrappers share lives in a private
Bridge module (both are private_constant, so Kvstore::Native raises
NameError). lib/{prefix}/runtime.rb is fixed code shipped with the
generator (the source lives in targets/ruby/runtime/runtime.rb); only the
module name, the C prefix, and the library names are substituted into it.
A wrapper converts each argument into its one C value and hands the C call to one runtime helper as a block, so the generated code stays short:
def get(key)
key = Bridge.string_arg(key)
Bridge.pin(self) do |self_|
Bridge.call(KvError, [:buffer, Entry]) do |out_err|
Native.kvstore_Store_get(self_, key, out_err)
end
end
end
Bridge.string_arg copies the key’s UTF-8 into a kvstore_run the library
borrows; Bridge.call allocates the error slot, raises per the function’s
error domain, and receives the result (here, decodes an Entry from the
returned run and releases it with kvstore_run_free); Bridge.pin keeps
the receiver alive for the call.
Install, build, and load
weaveffi generate samples/kvstore -o bindings --target ruby
cargo build --release -p kvstore
cd bindings/ruby
gem build kvstore.gemspec
gem install kvstore-1.0.0.gem
The loader opens the library in this order:
- the path in
{PREFIX}_LIBRARY(KVSTORE_LIBRARY=/path/to/libkvstore.dylib), - a copy bundled at
lib/native/(platform gems fromweaveffi package), libkvstore.dylib,libkvstore.so, orkvstore.dllon the system search path.
require 'kvstore'
store = Kvstore::Store.open('/tmp/data')
store.put('greeting', 'hi'.b, Kvstore::EntryKind::VOLATILE)
store.close
weaveffi package --target ruby writes one precompiled platform gem per
desktop platform built, ruby/{gem}-{version}-{platform}.gem (arm64-darwin,
x86_64-darwin, x86_64-linux, aarch64-linux, x64-mingw-ucrt), with the
library at lib/native/. The gems install with gem install and publish
with gem push; Android, iOS, and wasm32 builds are skipped. See
Packaging.
Load-time checks
require checks, before anything else is attached, that the library
implements C ABI revision 6, and then that the library exports the
contract function of every declaration
the bindings were generated with and that each returns the expected hash.
The rows are embedded in the bindings, each with its canonical signature as
a comment:
module Kvstore
Bridge.check_contract!(
[
# method get(string) -> Entry throws KvError
[:kvstore_contract_dc5ad183936cb6fc, 0x1898683461a88009, 'Store.get'],
# ...one row per declaration, error code, and callback method
],
)
Any failure raises Kvstore::LoadError, a subclass of Ruby’s LoadError,
so both rescue Kvstore::LoadError and a plain rescue LoadError around
the require catch it: a library that can’t be opened, a different ABI
revision, or a declaration that’s missing or changed (kvstore: Store.put is missing from the library, kvstore: Store.put changed since these bindings were generated). Declarations, error codes, and callback methods
the library has and the bindings don’t are fine, so a library that only adds
to its API keeps working with older bindings. A failed require isn’t
recorded as loaded, so it can be retried (after setting {PREFIX}_LIBRARY,
for example).
Type mapping
Every value crosses as one C value, in every position (a parameter, a
return, an async result, an iterator element, and a callback argument or
return). The structs are FFI::Struct classes in Native, passed by value.
| IDL type | Ruby type | C value |
|---|---|---|
i8 to i64, u8 to u64 | Integer | :int8 to :uint64 |
f32, f64 | Float | :float, :double |
bool | true or false | :bool |
| C-style enum | Integer constants in a module | :int32 |
T? of a scalar, bool, or C-style enum | T or nil | Native::OptI32 and so on: {has, value} |
string | String (UTF-8) | Native::Run: {ptr, len} |
bytes | String (binary) | Native::Run |
[T] of a numeric scalar (not u8, not bool) | Array of Integer or Float | Native::Run (a typed array) |
| record | Data class | Native::Run (a value buffer) |
| rich enum | module of Data variant classes | Native::Run (a value buffer) |
any other T?, [T], {K: V} | T or nil, Array, Hash | Native::Run (a value buffer) |
| interface | wrapper class | :pointer |
Interface? | wrapper or nil | :pointer (NULL for nil) |
| callback interface | any object with the methods | Native::Callback: {ctx, vtable} |
Cb? | such an object or nil | Native::Callback (a NULL vtable for nil) |
iter<T> | lazy Enumerator | iterator handle |
Trailing optional parameters (T?, Interface?, Cb?) default to nil,
so store.keys is store.keys(nil).
Arguments are checked before the call:
- An integer (or a C-style enum value) must be an
Integerin its type’s range:RangeErrorrather than silent wrapping,TypeErrorfor aFloat. That holds for scalars, optional scalars, typed-array elements, and integers inside value buffers. - A string must be a
String(or convert withto_str) holding valid UTF-8; a string in another encoding is converted. Anything else raisesTypeErrororArgumentError. Strings cross as a run of bytes, so interior NUL characters survive. Returned strings are copied, tagged UTF-8, and released. - A typed-array argument must be an
Array(or convert withto_ary); its range-checked elements are packed into an 8-aligned native run the library borrows for the call. A typed-array return is copied into a newArrayand released. - An optional scalar crosses as its
{has, value}struct, never through a value buffer:nilin,nilout. - An object argument must be a wrapper of the declared interface, and a
record argument an instance of the record’s class (
TypeErrorotherwise).
Every run an argument borrows lives in native memory the Native::Run
struct keeps alive for the call, and every run the library returns is
copied into Ruby and released with {prefix}_run_free before the wrapper
returns.
Records are Data classes: immutable, constructed with keywords or
positionally, with value equality and hashing, with, to_h, and pattern
matching:
entry = Kvstore::Entry.new(key: 'k', value: 'v'.b, kind: Kvstore::EntryKind::VOLATILE,
version: 1, expires_at: nil, tags: [], metadata: {})
entry.with(version: 2)
A rich enum is a module whose variants are Data classes that include it,
so change.is_a?(Kvstore::Change) holds and case change in Kvstore::Change::Put(entry:) works; change.tag (and each variant’s TAG)
is the wire tag.
Value buffers use the value-buffer format.
Nothing per composite type is generated: the runtime’s codec walks a
literal type description ([:list, [:opt, Entry]], [:map, :string, :i64]),
and each record, variant, and error payload registers its field layout
once, at the end of the bindings (Bridge.record(Entry, key: :string, ...)).
A field named like a method a record or error relies on gains a trailing
_ (hash_, to_h_; an error field message is message_), and so does
a type named like a constant the bindings use (Error_, Data_, FFI_);
keywords are fine as member names (entry.end). See
reserved member names.
Objects and lifetime
Each interface becomes a subclass of the runtime’s Bridge::Handle, holding
one strong reference in an FFI::AutoPointer:
# An embedded key-value store. Each object owns its entries, logical
# clock, listeners, and policy; the last release drops them (and frees
# the consumer's callbacks).
class Store < Bridge::Handle
closereleases the reference now and is idempotent; otherwise the GC finalizer releases it. The object itself lives until its last reference anywhere (another wrapper, a record field, the library) goes.closed?says whether the wrapper was closed.- Two open wrappers of the same native object are
==(andeql?, with equalhash), so a record holding objects compares as expected. dupandclonemake an independent wrapper with its own reference.- A constructor named
newbecomesinitialize; other constructors are class methods (Store.open). An interface without one hidesnew. - Every call pins its receiver and object arguments, so a
closefrom another thread or from a callback during the call takes effect only when the call returns. - An object inside a value buffer carries its own reference, minted just before the call; an object decoded from one is adopted into a new wrapper.
- Using a closed wrapper raises
Error(“Kvstore::Store used after close”). - A method spelled like one the wrapper relies on (
close,initialize,class,dup,hash,inspect, …), or a static or factory namedallocate,new, orname, gains a trailing_: an IDL methodcloseisclose_.
Errors
Every error a call reports derives from {Module}::Error (a
StandardError), which carries code. Each error domain becomes a class
under it, named by the shared rule (KvError stays KvError,
KitchenErrors becomes KitchenError, Failure becomes FailureError),
with one nested class per code. A code’s class carries CODE, its
documented MESSAGE, and a reader per payload field:
begin
store.get('missing')
rescue Kvstore::KvError::KeyNotFound => e
e.code # => 1001
e.key # => "missing"
e.message # => "key not found: missing"
end
A library may declare several domains, and a function names the one it
throws, so codes are only unique per domain: Calculator.divide raises
CalcError::DivisionByZero for code 1 and Calculator.parse raises
ParseError::NotANumber for its code 1. Domains are open: a positive code
these bindings don’t know (a newer library added it) raises the domain
class itself, with the code and the library’s message.
What a failure raises follows the trap policy:
| Call | Domain code | Runtime code (-1 to -4) | -5 |
|---|---|---|---|
throws: Domain | the code’s class (KvError::Expired), or the domain class for an unknown code | Error with that code and the library’s message | Cancelled |
throws: any | not possible | Error (a failure is code -1 and its message) | Cancelled |
no throws | not possible | NativeBugError | Cancelled |
NativeBugError < Error marks a bug in the library (a panic, an argument it
couldn’t accept, a callback failure it let through a call that can’t report
one), never an outcome to handle. Its message names the code and the
library’s message, as in native call failed with code -2: {the panic message}; a malformed value the library returned raises it with code -3.
The runtime codes are constants on Error (Error::GENERIC,
Error::PANIC, Error::MARSHAL, Error::CALLBACK, Error::CANCELLED).
An error code’s class can be raised from a callback implementation; its payload fields are required keywords:
raise Kvstore::KvError::Rejected.new('read-only', key: entry.key, reason: 'read-only')
Async and cancellation
An async function blocks its caller until the library’s completion fires,
then returns the result or raises. The wait is a Thread::Queue#pop, so:
- It releases the GVL; other threads keep running. Run calls in threads for concurrency.
- Under a Fiber scheduler (
Fiber.set_scheduler, such as theasyncgem’s),Queue#popin a non-blocking Fiber yields to the scheduler, so only the calling Fiber waits and the thread’s other Fibers keep running; the completion wakes it through the scheduler’sunblock. The conformance suite checks this with two overlapping calls.
A cancellable function takes a cancel: keyword:
token = Kvstore::CancelToken.new
Thread.new { sleep 0.5; token.cancel }
begin
store.compact(60_000, cancel: token)
rescue Kvstore::Cancelled
# cancelled while the pause was running
ensure
token.close
end
CancelToken#cancel may be called from any thread; the call then raises
Cancelled (code -5) unless it already completed. A token stays
cancelled, can be shared by several calls, and is released by close or
the GC. Without a token, interrupting the waiting thread (Thread#raise,
Timeout) still cancels the library’s work through a private token.
The completion receives the result as its one C value (a scalar, an optional’s struct, a run, or an object pointer), which the runtime receives exactly as it does a return. The completion functions are shared by every async call whose result has the same C type and live for the process, so nothing the library may still call is ever garbage-collected.
Callback interfaces
A callback interface becomes a Ruby module whose methods raise
NotImplementedError. Any object that responds to the methods works;
including the module documents intent and supplies the defaults.
class FileLoader
include Kvstore::Loader
def name
'files'
end
def fallback(_key)
nil
end
def load(key)
path = File.join('/data', key)
raise Kvstore::KvError::KeyNotFound.new("no file for #{key}", key: key) unless File.exist?(path)
File.binread(path)
end
end
entry = store.get_or_load('settings', FileLoader.new)
Passing an implementation stores it in a handle table and hands the library
a {ctx, vtable} struct whose ctx is its key, so Ruby object addresses
never cross the boundary; the entry is removed when the library calls the
vtable’s free, which may happen on any library thread. A required callback
parameter rejects nil with TypeError; an optional one (loader = nil)
passes a NULL vtable.
Each interface has one vtable for the life of the process, registered at the end of the bindings as one row per method (its Ruby name, the error class it may raise, its return, and its parameters):
Bridge.vtable(
Listener,
[:accepts, Error, :bool, [:string]],
[:on_change, Error, nil, [[:buffer, Change]]],
)
The runtime builds the {size, flags, free} header, with size the
vtable’s own size and flags 0 (the methods may be called from any
thread), then one trampoline FFI::Function per row, which it keeps
referenced for the life of the process.
Arguments and returns follow the ABI:
- Strings, bytes, value buffers, and typed arrays arrive as copies of the
borrowed run; an optional scalar arrives as the value or
nil; an object argument arrives as a wrapper that adopted the reference the library passed, which the implementation may keep. - A returned number, boolean, C-style enum, or optional scalar crosses by
value (checked against its type’s range); a returned object (
StoreorStore?) as a fresh reference the library adopts (nilis NULL, which the library rejects where the return isn’t optional); and a returned string, bytes, typed array, or value buffer as a run allocated with{prefix}_alloc, which the library adopts. - A method that throws a domain may raise that domain’s code classes: the
library receives the code and the fields as the payload, exactly as if
the producer had raised it (the caller then sees the domain’s own message
for those fields). Any other exception, including
NotImplementedError, is reported as code-1with its message (-4for a method that declares no errors), and the method returns its type’s zero value. Nothing unwinds through C.
Threads and the GVL
Every call into the library except the trivial runtime helpers (_clone,
_destroy, an iterator’s _destroy, {prefix}_run_free, {prefix}_alloc,
{prefix}_debug_live, the error and cancel-token functions, and the
load-time checks) releases the GVL (blocking: true), so a long call
doesn’t stall other Ruby threads. That’s also what lets a callback arrive
while the call that triggered it is in flight: a callback on the calling
thread reacquires the GVL there, and one from a library thread (such as the
notifications compact sends from its worker) runs on the ffi gem’s
callback thread, which needs the GVL too.
Iterators
An iter<T> return is a lazy Enumerator, with every Enumerable method.
Each enumeration launches its own native iterator on its first pull, makes
one _next call per element, and destroys the iterator exactly once, when
iteration finishes, raises, or stops early (first(2), break), so the
same Enumerator can be enumerated again. An external enumeration (next)
releases its iterator the same way when it reaches the end or raises; one
abandoned midway can’t run its ensure, so the iterator handle is an
FFI::AutoPointer whose GC finalizer destroys it once the suspended
enumeration is collected. Either path destroys the iterator exactly once.
Each element is its one C value, received like a return.
Known limitations
- Async calls block the calling thread (or, under a Fiber scheduler, the calling Fiber); there’s no promise-based surface.
- Callback interfaces are duck-typed: a missing method is detected only when the library calls it (and reported to it as a failure).
- A callback that blocks waiting for the thread that made the triggering call deadlocks.
- A deprecated callable warns on every call in the
:deprecatedwarning category, which Ruby hides by default; enable it withWarning[:deprecated] = true(orruby -W:deprecated).