wasm_redb (wasm_redb v0.1.0)

View Source

The API of wasm_redb: redb, running inside WebAssembly.

Each database you open is a server process (wasm_redb_db) in front of a guest that runs redb. The functions here check and encode your arguments in your process, then call that server. Start here; you normally do not need the other modules.

A database is a set of named tables of binary keys and binary values, kept in key order. Every change happens in a transaction; one write transaction and any number of read transactions can be open at once, and a read transaction sees the database as it was when it began.

{ok, Db} = wasm_redb:open(#{storage => {wasm_storage_file, "data.redb"}}),
ok = wasm_redb:put(Db, <<"docs">>, <<"k1">>, <<"v1">>),
{ok, <<"v1">>} = wasm_redb:get(Db, <<"docs">>, <<"k1">>),

{ok, ok} = wasm_redb:transaction(Db, fun(Txn) ->
    ok = wasm_redb:put(Txn, <<"docs">>, <<"k2">>, <<"v2">>),
    ok = wasm_redb:put(Txn, <<"by_date">>, <<"2026-11-29/k2">>, <<>>)
end),

{ok, [{<<"k1">>, _}, {<<"k2">>, _}]} =
    wasm_redb:range(Db, <<"docs">>, #{prefix => <<"k">>}),
ok = wasm_redb:close(Db).

Most functions take either the database or a transaction. With the database, the call runs in a transaction of its own: a read sees one snapshot, a write commits before it returns, with the database's default durability.

Errors

  • {error, Reason} with an atom: the operation did not happen. table_not_found, write_busy, read_only_transaction, no_transaction, transaction_lost (the guest was replaced; the transaction is gone and nothing it wrote was committed), table_type_mismatch, value_too_large, invalid_name, overloaded, transaction_in_progress, closed (the database is gone).
  • {error, timeout}: the deadline passed. If the call had started, the guest was replaced, and every transaction open at that point was lost.
  • {error, {Reason, Detail}}: a storage failure, corruption, a trap or an exited guest. The guest was replaced and reopens at once, in the background; every transaction open at that point was lost.
  • {error, {commit_unknown, Why}}: a commit was interrupted. It may or may not be in the file. Read the data back to find out.
  • {error, {unavailable, Why}}: the guest could not be reopened after a failure. The next call tries again.

See the redb guide for the guarantees and what they rest on, and failures for what to do about each error.

Summary

Functions

End a transaction without committing. The database ends it even when the call's deadline passes first.

begin_read(Db, #{}).

Begin a read transaction. It sees the database as of now, whatever is committed later, until abort/1 ends it. It ends by itself when the calling process exits. A long-lived read transaction keeps redb from reusing the pages it sees, so the file grows while it is open.

begin_write(Db, #{}).

Begin the write transaction. If another one is open, wait for it, in order, up to timeout. Options: durability (immediate or none), two_phase_commit, quick_repair, timeout.

Check the whole file. {ok, true} when it passed, {ok, false} when redb found damage and repaired it. Needs every transaction closed.

A child spec for start_link/1.

Close the database. Open transactions end without committing.

End the iterator's own read transaction, if it has one.

commit(Txn, #{}).

Commit a write transaction. ok means it is in the file with the transaction's durability. If the deadline passes before the database gets to the commit, the database aborts the transaction instead and the answer is {error, timeout}. Read transactions cannot be committed; end them with abort/1.

compact(Db, #{}).

Rewrite the file to release free pages. {ok, true} when it shrank. #{maximum => true} trades insert speed afterwards for a smaller file. Needs every transaction closed.

Create a table. Creating an existing table is not an error.

Remove Key. Removing a missing key is not an error.

Remove every key of a range (lower, upper, prefix). Returns how many.

Delete a table and everything in it. Returns whether it existed.

Fold over a range (options as range/3). Fun(Key, Value, Acc) returns the next accumulator, or {stop, Acc} to end early.

get(Target, Table, Key, #{}).

The value of Key, or not_found.

What the database reports about itself: redb and guest versions, open transactions, queued writers, the guest's memory, the storage spec, whether redb repaired the file on open, whether it is reopening (opening), and the last failure. With readers, the counts are the writer's, readers is how many there are, and through the handle open/1 returned, reader_info lists each reader's generation, open read transactions, guest and last failure.

An iterator over a range (options as range/3), fetched in chunks. Given the database, it holds a read transaction of its own: end it with close_iterator/1 (it also ends when the calling process exits).

The names of every table.

The values of Keys, in order, each {ok, Value} or not_found, from one snapshot.

The next entry, or done.

Open a database, creating it when missing. The database is closed when the calling process exits, unless owner => none is given.

Set Key to Value. Creates the table if needed.

The entries of a range, in key order (or reverse), as one list. Opts

Run Fun(Txn) in a read transaction, then end it. Returns what Fun returns.

Start a database process linked to the caller, for your own supervision tree. Takes the options of open/1; owner defaults to none. Give it a name and pass the name wherever a database is expected.

redb's statistics for the database: tree height, pages, stored bytes, fragmentation. redb computes them in a write transaction, so with the database this waits for the write slot.

The number of entries in a table.

redb's statistics for one table.

transaction(Db, Fun, #{}).

Run Fun(Txn) in a write transaction and commit it. Returns {ok, Result}. If Fun returns {abort, Reason} the transaction is aborted and {error, {aborted, Reason}} is returned. If Fun raises, the transaction is aborted and the exception is raised again. Options are those of begin_write/2.

Apply Ops atomically, in order, across any tables: {put, Table, Key, Value} and {delete, Table, Key}. With the database, they commit together or not at all; in a transaction, they become part of it.

Types

bound()

-type bound() :: unbounded | {inclusive, binary()} | {exclusive, binary()}.

db()

-opaque db()

iterator()

-opaque iterator()

op()

-type op() :: {put, binary(), binary(), binary()} | {delete, binary(), binary()}.

range_opts()

-type range_opts() ::
          #{lower => bound(),
            upper => bound(),
            prefix => binary(),
            reverse => boolean(),
            limit => non_neg_integer(),
            chunk => pos_integer()}.

target()

-type target() :: db() | txn().

txn()

-opaque txn()

Functions

abort/1

-spec abort(txn()) -> ok | {error, term()}.

End a transaction without committing. The database ends it even when the call's deadline passes first.

begin_read(Db)

begin_read(Db, #{}).

begin_read(Db0, Opts)

-spec begin_read(db(), map()) -> {ok, txn()} | {error, term()}.

Begin a read transaction. It sees the database as of now, whatever is committed later, until abort/1 ends it. It ends by itself when the calling process exits. A long-lived read transaction keeps redb from reusing the pages it sees, so the file grows while it is open.

begin_write(Db)

begin_write(Db, #{}).

begin_write(Db0, Opts)

-spec begin_write(db(), map()) -> {ok, txn()} | {error, term()}.

Begin the write transaction. If another one is open, wait for it, in order, up to timeout. Options: durability (immediate or none), two_phase_commit, quick_repair, timeout.

It is aborted if the calling process exits without committing.

check_integrity(Db)

-spec check_integrity(db()) -> {ok, boolean()} | {error, term()}.

Check the whole file. {ok, true} when it passed, {ok, false} when redb found damage and repaired it. Needs every transaction closed.

child_spec(Opts)

-spec child_spec(map()) -> supervisor:child_spec().

A child spec for start_link/1.

close(Db)

-spec close(db() | atom() | pid()) -> ok.

Close the database. Open transactions end without committing.

close_iterator/1

-spec close_iterator(iterator()) -> ok.

End the iterator's own read transaction, if it has one.

commit(Txn)

commit(Txn, #{}).

commit/2

-spec commit(txn(), map()) -> ok | {error, term()}.

Commit a write transaction. ok means it is in the file with the transaction's durability. If the deadline passes before the database gets to the commit, the database aborts the transaction instead and the answer is {error, timeout}. Read transactions cannot be committed; end them with abort/1.

compact(Db)

compact(Db, #{}).

compact(Db, Opts)

-spec compact(db(), map()) -> {ok, boolean()} | {error, term()}.

Rewrite the file to release free pages. {ok, true} when it shrank. #{maximum => true} trades insert speed afterwards for a smaller file. Needs every transaction closed.

create_table(Target, Table)

-spec create_table(target(), binary()) -> ok | {error, term()}.

Create a table. Creating an existing table is not an error.

delete(Target, Table, Key)

-spec delete(target(), binary(), binary()) -> ok | {error, term()}.

Remove Key. Removing a missing key is not an error.

delete_range(Target, Table, Opts)

-spec delete_range(target(), binary(), range_opts()) -> {ok, non_neg_integer()} | {error, term()}.

Remove every key of a range (lower, upper, prefix). Returns how many.

delete_table(Target, Table)

-spec delete_table(target(), binary()) -> {ok, boolean()} | {error, term()}.

Delete a table and everything in it. Returns whether it existed.

fold(Target, Table, Fun, Acc, Opts)

-spec fold(target(), binary(), fun((binary(), binary(), Acc) -> Acc | {stop, Acc}), Acc, range_opts()) ->
              {ok, Acc} | {error, term()}.

Fold over a range (options as range/3). Fun(Key, Value, Acc) returns the next accumulator, or {stop, Acc} to end early.

get(Target, Table, Key)

get(Target, Table, Key, #{}).

get(Target, Table, Key, Opts)

-spec get(target(), binary(), binary(), map()) -> {ok, binary()} | not_found | {error, term()}.

The value of Key, or not_found.

info(Db0)

-spec info(db() | atom() | pid()) -> map().

What the database reports about itself: redb and guest versions, open transactions, queued writers, the guest's memory, the storage spec, whether redb repaired the file on open, whether it is reopening (opening), and the last failure. With readers, the counts are the writer's, readers is how many there are, and through the handle open/1 returned, reader_info lists each reader's generation, open read transactions, guest and last failure.

iterator/3

-spec iterator(target(), binary(), range_opts()) -> {ok, iterator()} | {error, term()}.

An iterator over a range (options as range/3), fetched in chunks. Given the database, it holds a read transaction of its own: end it with close_iterator/1 (it also ends when the calling process exits).

list_tables(Target)

-spec list_tables(target()) -> {ok, [binary()]} | {error, term()}.

The names of every table.

multi_get(Target, Table, Keys)

-spec multi_get(target(), binary(), [binary()]) -> {ok, [{ok, binary()} | not_found]} | {error, term()}.

The values of Keys, in order, each {ok, Value} or not_found, from one snapshot.

next/1

-spec next(iterator()) -> {ok, binary(), binary(), iterator()} | done | {error, term()}.

The next entry, or done.

open(Opts)

-spec open(map()) -> {ok, db()} | {error, term()}.

Open a database, creating it when missing. The database is closed when the calling process exits, unless owner => none is given.

Options:

  • storage (required): a wasm_storage spec, for example {wasm_storage_file, Path} or {wasm_storage_memory, new}.
  • create: create the storage when missing, default true.
  • cache_size: redb's page cache in bytes, default 16 MiB. It lives in the guest's memory, which counts against erlang_wasm's node page budget.
  • durability: immediate (default) or none, for writes made without an explicit transaction and for write transactions that do not say.
  • two_phase_commit, quick_repair: redb's commit options, default false.
  • timeout: the default deadline of every call in milliseconds, default
    1. A call that passes it stops the guest (see the module doc), and a call whose deadline has passed before it starts does not run, except that a commit or an abort still ends its transaction.
  • cleanup_timeout: the deadline, in milliseconds, of the calls the database makes on its own: ending the transaction of a process that exited, dropping a shared read transaction, closing. Default 30000. When it passes, the guest is replaced and the database reopens.
  • open_timeout: the deadline, in milliseconds, of an open of the guest, repair included. Default 600000. A reopen after a failure runs in the background: a call that needs the guest waits for it until its own deadline, and the reopen goes on without it.
  • compile: use erlang_wasm's compiled tier, default true.
  • instance: more wasm:instantiate/3 options for the guest, such as compile_after or compile_quality. For tuning and measurement.
  • readers: serve reads from this many guests in parallel, default 0. The writing guest then shares the file with N read-only guests, in redb's SingleWriter mode: reads and read transactions go to the least busy reader, writes go to the writer. Every commit is then durable and two-phase (durability => none is refused), a reader drops its page cache whenever it sees a new commit, and each reader has its own cache_size. The storage must be one the readers can open too: not {wasm_storage_memory, new}. See the redb guide.
  • min_heap_size, hibernate_after: the heap floor of the guest process in words (default 262144, 2 MiB, while busy) and the idle time in milliseconds after which it hibernates and gives the heap back (default 1000). See wasm_storage_guest:start_link/1.
  • idle_close: close the guest after this many idle milliseconds with no open transaction, and reopen on the next call. Default infinity.
  • max_queue: writers allowed to wait for the write slot, default 10000.
  • owner: the process whose exit closes the database, default the caller, or none.
  • name: register the database process under this name.

Returns {error, {badarg, storage}} without a {Provider, Arg} spec, {error, einval} if Provider is not a wasm_storage provider, and {error, already_open} if this node already has the storage open.

put(Target, Table, Key, Value)

-spec put(target(), binary(), binary(), binary()) -> ok | {error, term()}.

Set Key to Value. Creates the table if needed.

range(Target, Table, Opts)

-spec range(target(), binary(), range_opts()) -> {ok, [{binary(), binary()}]} | {error, term()}.

The entries of a range, in key order (or reverse), as one list. Opts:

  • lower, upper: unbounded (default), {inclusive, Key} or {exclusive, Key}.
  • prefix: every key that starts with it. Combines with no other bound.
  • reverse: from the highest key down. Default false.
  • limit: at most this many entries.
  • chunk: entries fetched per guest call, default 256.

With the database, the whole range comes from one snapshot.

read_transaction(Db, Fun)

-spec read_transaction(db(), fun((txn()) -> R)) -> R | {error, term()}.

Run Fun(Txn) in a read transaction, then end it. Returns what Fun returns.

start_link(Opts)

-spec start_link(map()) -> {ok, pid()} | {error, term()}.

Start a database process linked to the caller, for your own supervision tree. Takes the options of open/1; owner defaults to none. Give it a name and pass the name wherever a database is expected.

stats/1

-spec stats(target()) -> {ok, map()} | {error, term()}.

redb's statistics for the database: tree height, pages, stored bytes, fragmentation. redb computes them in a write transaction, so with the database this waits for the write slot.

table_len(Target, Table)

-spec table_len(target(), binary()) -> {ok, non_neg_integer()} | {error, term()}.

The number of entries in a table.

table_stats(Target, Table)

-spec table_stats(target(), binary()) -> {ok, map()} | {error, term()}.

redb's statistics for one table.

transaction(Db, Fun)

transaction(Db, Fun, #{}).

transaction(Db, Fun, Opts)

-spec transaction(db(), fun((txn()) -> term()), map()) -> {ok, term()} | {error, term()}.

Run Fun(Txn) in a write transaction and commit it. Returns {ok, Result}. If Fun returns {abort, Reason} the transaction is aborted and {error, {aborted, Reason}} is returned. If Fun raises, the transaction is aborted and the exception is raised again. Options are those of begin_write/2.

write(Target, Ops)

-spec write(target(), [op()]) -> ok | {error, term()}.

Apply Ops atomically, in order, across any tables: {put, Table, Key, Value} and {delete, Table, Key}. With the database, they commit together or not at all; in a transaction, they become part of it.