Reference / The wire protocol, version 1

The wire protocol, version 1

The bytes a TinyStore server and its clients exchange over any byte stream: a child's stdin and stdout, a Unix socket, a Windows named pipe, TCP or TLS. Read it to write a client in a language TinyStore has no SDK for, or to see what an SDK does on the wire; the Bun and Node, Python and Go SDKs are built to this page.

Frames, the profile, the handshake, the errors and every engine's methods are built in crates/tinystore/src/wire/, and why the server behaves as it does is its design. Every example on this page is a vector of testdata/wire/vectors.json, which the server and every SDK are tested against: a value in a typed notation, the bytes it is, and the bytes a decoder refuses, each named after the rule it breaks. Every message is also a vector of protocol.json, as Methods says. messages.json keeps a vector of each message as the Go server first wrote it, with the methods' numbers and the errors' codes, and the Bun SDK's tests still check every field of each.

Frames

Everything is little-endian. A frame is a twelve-byte header and a body:

0             4      5       6          8             12
│ body length │ kind │ flags │ method   │ stream      │ body …
  u32           u8     u8      u16        u32
  • The length is the body's. A frame is 12 + body length bytes; a body past the agreed maximum is refused before a byte of it is read. A message past it goes in several frames, as Messages in several frames says.
  • What is reserved is zero. An unknown kind, a flag this kind does not define, a method outside a REQUEST or a stream where the kind names none is a protocol error, and the connection ends.
kindstreammethodbodyflags
1HELLO00a message—
2WELCOME00a message—
3REQUESTthe new streamthe operationa message, or a piece of oneEND, MORE
4RESPONSEits stream0a message, a piece of one, or an errorEND, ERROR, MORE
5DATAits stream0bytes, or a message, as the method saysEND, ERROR
6CANCELits stream0empty—
7CREDITits stream, or 0 for the connection0u32: bytes granted—
8PING008 bytes—
9PONG00the PING's 8 bytes—
10GOAWAY00a message—

END is 1: the sender's last frame on its stream. ERROR is 2, only beside END: the body is an error. MORE is 4, on a REQUEST or a RESPONSE alone, never beside END or ERROR and never on an empty body: the message goes on in the next frame, as Messages in several frames says.

A method's high byte is its engine and its low byte the operation, so a new engine takes a new high byte and the frame stays as it is; Methods has every engine's byte and every method's number.

A HELLO from Bun:

16 00 00 00  01  00  00 00  00 00 00 00                                   a body of 22 bytes, HELLO
82                                                                        a map of two
   01 01                                                                  protocol: 1
   02 b1 74 69 6e 79 73 74 6f 72 65 2d 62 75 6e 2f 30 2e 31               client: "tinystore-bun/0.1"

A connection

  1. The client sends HELLO, and the server answers WELCOME, or GOAWAY and closes. Nothing comes before them, and the server waits five seconds for HELLO. The connection speaks the older of the client's newest protocol and the server's, which WELCOME names: a client newer than its server speaks the server's protocol, or closes when it no longer does, and only a client older than the oldest protocol the server speaks is refused.
  2. The client opens streams with REQUEST, as many at once as WELCOME allows.
  3. Either side may send PING; the other answers PONG with the same eight bytes.
  4. The server ends the connection with GOAWAY. The client opens no stream after it; a REQUEST that crossed it on the way is answered unavailable without being run, so it may be sent again elsewhere; the streams already running finish, and the server closes. Stream numbers are reused, so no number could say which requests the server saw: each answer says it.

HELLO:

keyfieldtype
1protocoluintthe newest the client speaks, 1
2clientstra name and version, for logs
3tokenstrrequired on TCP
4max bodyuintthe largest body the client takes; the server's when absent
5stream credituintthe DATA the server may send on a stream before the client grants more; 2 MiB when absent
6challengebin16 random bytes, when the client found the server through SERVE
7max messageuintthe largest message the client sends and takes in several frames; none when absent

A body must fit the credit it is sent under, so the max body both sides agree is the smallest of the server's, the client's and the client's stream credit: a client granting 64 KiB a stream takes bodies of 64 KiB at most. Every SDK grants 2 MiB, so its frames carry 2 MiB at most. Every SDK and the command line ask for a max message of 64 MiB, send a larger message in frames of the agreed body, and refuse a request past the max message before they send it, with the limit error that Over the wire shows.

WELCOME:

keyfieldtype
1protocoluintthe one this connection speaks
2serverstrits version
3instancebin16 random bytes a start
4capabilitystradmin, data or read
5max bodyuintthe largest body either side sends
6in flightuintthe streams a client may have open at once
7connection credituintthe bytes of REQUEST and DATA bodies a client may send before credit comes back; at least the max body
8stream credituintthe bytes of DATA a client may send on a stream before credit comes back
9enginesarray of strwhat this server serves
10nowintthe store's clock, unix milliseconds
11proofbinon a local connection whose HELLO carried a challenge: the HMAC-SHA256 of the challenge, keyed with the 32 bytes of SERVE's secret
12durabilitystrfull or os, when the store was opened with one: how far its files' commits go before they return
13max messageuintthe largest message either side sends in several frames, when HELLO asked for one: the smaller of the two, and never below max body

A client that found the server through SERVE sends no REQUEST before the proof checks, as the proof says below. HELLO carries nothing a stranger could use, since a local connection takes no token. A challenge of another length is a HELLO the server cannot take; a remote connection's challenge gets no proof, its server being the one its TLS certificate names. The vectors hold a proof, proofs, and a HELLO with a challenge.

A server that does not take the connection at all, past its connections or closing, still reads the HELLO and answers GOAWAY where the WELCOME belongs, with limit or unavailable.

GOAWAY:

keyfieldtype
1codestras an error's
2messagestr

Finding a local server

A store directory has at most one server, since its LOCK lets one process open it. That server publishes how to reach it in <dir>/server/, which only the user the server runs as may enter, whatever the store's directory lets others do: mode 0700, and SERVE 0600, on Linux and macOS. On Windows, which lets anyone traverse a directory to a file whose path they know, server\ and SERVE each have a protected DACL that grants that user every right and nobody else any, so that neither inherits the store directory's, and what else is made in server\ inherits its DACL alone. SERVE is created with its DACL rather than given it after. An owner may change a DACL whatever it says, so a server\ another user made first, as a folder at a drive's root lets every user, is refused, and so is a link in its place: the server does not start, and its error names the folder. On Linux and macOS such a folder refuses its new mode. SERVE there is a hint; LOCK is the truth.

json
{"protocol": 1, "server": "0.7.0", "pid": 4212, "instance": "q1q0l3yZ3JvYw8g7oM2sYA",
 "secret": "Zm9vYmFyYmF6cXV4Zm9vYmFyYmF6cXV4Zm9vYmFyYmE",
 "endpoints": ["unix:///srv/app/data/server/tinystore.sock"], "sidecar": true}
field
protocolthe newest protocol the server speaks
serverits version
pidits process, for a person reading the file; no client trusts it, since a pid is reused
instance16 random bytes a start, base64url without padding, which WELCOME repeats
secret32 random bytes a start, base64url without padding, the key of the proof
endpointswhere it listens: unix:// and a socket's path, or pipe: and a Windows named pipe's name
sidecartrue when the server is a sidecar, which tinystore serve --local starts for its clients. A client of a newer release may replace a sidecar. The field is absent for a Go program's own server and for tinystore serve <dir>, which a person runs
embeddedtrue when a program holds the store in its own process and opened it with cli, store.Options 18: its endpoint is the command line's, refuses server.stop and server.clock, and serves 4 connections at once. An SDK's sidecar open does not attach to it, and fails in_use
  • Written whole, under the lock. Only the store holding LOCK writes server/. A server removes a SERVE left behind before it listens, since the endpoint that file names may be another process's by now, writes its own once it listens, as a temporary file renamed into place, and removes it when it leaves, before it lets go of LOCK. A store opened with cli does the same, its connections told GOAWAY and given 2 seconds first.
  • Find or start. A client reads SERVE, connects to an endpoint and checks the proof. Any failure, no file, a refused connection or a proof that does not check, starts `tinystore serve --dir --local --log-file /server/serve.log`, detached, and reads its stderr until it answers. That child takes `LOCK`, which means the old server is gone, and publishes itself; or it finds `LOCK` held and exits with code 3, and the client reads `SERVE` again until the winner answers, 15 seconds at most, starting one again when none does. A child that exits with any other code failed, and the client says why: the last lines it wrote to stderr, which is where a failure before its log opened goes, or else the lines `serve.log` gained since that child started, since the log keeps every run's lines. Before anything starts, a client refuses a directory that is a file, or sits under one, `invalid`, in the core's words.
  • A start the program gives up on. The 15 seconds end sooner at the program's own cancel of its open: the client stops the start where it waits, starts no other server, and closes any connection it made after. A sidecar it already started may still take LOCK once the directory is free; with no client it leaves after its idle time, and never before the 15 seconds a client may wait for it.
  • The proof. A client that found its server through SERVE sends a HELLO with 16 random bytes as its challenge, and sends no REQUEST until WELCOME's proof equals the HMAC-SHA256 of the challenge keyed with the secret, compared in constant time. An endpoint's name is anyone's to take once its server is gone, a Windows pipe's above all, and only the user the server runs as can read the secret. A client whose proof fails reads SERVE again, as a stale one.
  • A reader delays a change and never fails it. On Windows a client holding SERVE open refuses its rename or removal, and so may a scanner; the server tries again eight times, from 1 to 64 ms apart.

How a client knows its server depends on the transport:

transporthow the client knows its server
stdioit started the server itself, as a private child
a Unix socket or a named pipe found through SERVEthe proof
TCP with TLSthe certificate, checked before its token leaves
TCPnot at all: the token travels in the clear, on a network its operator trusts

Where a local server listens:

  • A Unix socket, <dir>/server/tinystore.sock, when that absolute path fits a sockaddr_un, 104 bytes on macOS and the BSDs and 108 on Linux; past it, the same name in a directory of the owner's own, $XDG_RUNTIME_DIR/tinystore-<hash>, or in the temporary directory without one. <hash> is the first eight bytes of the SHA-256 of the store's absolute path, in hex: eight, so that a socket under macOS's temporary directory still fits.
  • A named pipe on Windows, pipe:tinystore-<hash>, which refuses remote clients. Named pipes share one namespace across every user, so it is created as the first instance of its name, and a process that took the name first is found by the server rather than by its clients. Every instance has a DACL that grants the user the server runs as alone, so that no other user connects to it or makes an instance of its own. No local endpoint takes a token: its permission is the file system's, and a local connection is admin.

A remote server's tokens file gives each token one capability: admin may do anything, data reads and writes, and read reads only. A read connection may call only the methods the schema marks read, every other one being permission; and its SQL runs on a reader and is a query, a statement that writes, attaches a file or sets a pragma being permission too. Its opens open only what the store already holds, as it is, and make nothing: no file, no name, no row, and no option that binds a later open. A file the store does not hold is not_found, and so is a read that names no handle, such as records.streams, on a store without that engine's file; a name the store does not hold is invalid. What an open chooses is the writers' to choose: a read connection's open of a queue or a database takes the options and the durability the store has, applies no migration, and refuses with permission a bucket's idle, under which a read renews a key, counters' flushEvery, a database's durability and a stream's keep. Its reads renew no key.

Streams

A client names a stream with any number from 1 not in use. A number is in use from its REQUEST to the server's final frame on it, and may be named again after. A REQUEST on a number in use, or past the streams in flight, ends the connection.

shapethe client sendsthe server sends
a callREQUEST·ENDRESPONSE·END
an uploadREQUEST, DATA…, DATA·ENDRESPONSE·END
a downloadREQUEST·ENDRESPONSE, DATA…, DATA·END
both waysREQUEST, DATA…, DATA·ENDRESPONSE, DATA…, DATA·END
  • The server ends every stream once: RESPONSE·END or DATA·END, either with ERROR, a cancelled stream too. It takes the number out of use before that frame leaves, so a client may name it again the moment it arrives.
  • A download's RESPONSE is its header, a message of the method's, {} when it has nothing to say; its items follow as DATA, and its last DATA·END is its trailer, a message saying where the next page begins.
  • DATA carries bytes or items. A blob's bytes are raw; rows, jobs and series are a message each. The method says which. A DATA carries at least one byte, but the one that ends its stream.
  • A transfer shares the connection. A sender splits bytes into frames of 64 KiB at most, so that no stream holds the connection longer than one such frame takes to send.
  • CANCEL asks the server to stop. It answers with the final frame it would have sent, or with the error cancelled; a client may drop what arrives on a stream it cancelled. A client ends an upload early with CANCEL: ERROR is the server's alone. A read under way stops at once, its statement interrupted, and answers cancelled, as do the reads of a connection that ends; a call that writes runs to its end.
  • A frame for a stream no longer in use is dropped: a DATA the client sent before the final frame reached it, a CANCEL or a CREDIT that crossed it. The dropped DATA still gives its connection credit back.
  • A body that is not its method's message fails its stream with invalid, naming the rule it broke; a frame that is not a frame ends the connection.

Messages in several frames

A message past the agreed body travels as pieces, on a connection whose WELCOME agreed a max message. A client asks for one with HELLO's key 7, and the server answers with the smaller of the client's and its own, 64 MiB, in WELCOME's key 13. A server that does not know the key skips it and answers no max message; a client that asks for none is sent none. Either way that connection sends every message in one frame, as before.

REQUEST·MORE  stream 5, search.setMany, 2 MiB    the first piece
REQUEST·MORE  stream 5, search.setMany, 2 MiB
REQUEST·END   stream 5, search.setMany, 1 MiB    the last: the 5 MiB message is whole
RESPONSE·END  stream 5, {}
  • Pieces are frames of one kind on one stream. Every piece but the last has MORE and no other flag; the last has none of MORE and the flags the message's one frame would have, END on a call's REQUEST. Each carries at least a byte and at most the agreed body, and a REQUEST's pieces each name its method. The receiver joins the bodies in order and reads the message as one frame's body: a call the engine commits once commits once.
  • The first piece takes the stream's number into use, as a REQUEST does, and the others belong to it. A REQUEST piece of another method, or MORE on a connection that agreed no max message, ends the connection.
  • What is joined is bounded. A server holds at most the max message of joined requests on a connection at once, counted from a request's first piece to its stream's end. A piece past it drops what that request had, and the server drops the pieces that follow; once the last one comes, the stream answers limit, with request bytes, wanted, the message's size and those of the others it was held beside, and bound. Nothing of it runs, and the connection goes on. An SDK sends a large request only once those before it leave room. A client reading pieces past its max message ends the connection.
  • What waits to be sent is bounded too. An answer is built whole before its first piece leaves. A connection holds at most the max message of reads' answers waiting in pieces: a read whose answer would pass it while others wait runs again once they have gone, so it is never refused for what others hold. A write's answer always waits its turn, since the write already ran. What waits counts toward what the connection owes its client, so past 8 MiB it reads no frame more and starts no call more, as for a client that does not read.
  • A client ends a request early with CANCEL before its last piece: the server drops what it joined and answers cancelled.
  • An answer past the max message is limit answer bytes for a read and outcome_unknown for a write, as one past the body is on a connection that agreed none. An error is never sent in pieces.
  • Pieces share the connection. A request's pieces count against the connection's credit as any REQUEST does, and the server gives that credit back as soon as it has copied a piece into its message, so a large request never holds the window. An answer's pieces go out one at a time while the connection owes its client less than 1 MiB, each answer in turn with the others in pieces, and the frames of other streams go between them as the client reads.

Credit

A sender never sends more than it was granted, and a receiver grants only room it has, so a connection holds no more than its grants and the server's reader never waits.

  • Client to server. Every REQUEST and DATA body counts against the connection's credit, and a DATA body against its stream's too. The server gives credit back with CREDIT as it lets go of bodies: on stream 0 for the connection, on a stream's number for that stream.
  • Server to client. DATA bodies count against the stream credit HELLO stated, and the client grants more with CREDIT on the stream as it consumes them. A RESPONSE body is not counted, nor are its pieces: it is one message within the agreed body, or the max message the client asked for, and every collection travels as DATA instead, so a client holds at most its streams in flight times that message in answers. Nor is the DATA·END·ERROR that fails a download, so that a stream always has room for its end. A client grants nothing for the connection: its CREDIT names a stream.
  • A grant waits for half the window. A receiver grants what it let go of once half its window has gone, and not a frame for every frame it takes.
  • A body past its credit ends the connection with GOAWAY and protocol, the connection's last frame.
  • A client that does not read is read no further. A call's stream ends, and its credit comes back, once its answer is queued rather than read, and a PONG counts against no credit; so a connection that owes its client more than 8 MiB reads no frame more until the client takes some, and the server stops reading its socket, where the client's sends wait. The requests of one write are all read before any of them is answered, so a call also checks when a worker starts it. Past 8 MiB, it waits until the client has read all but 1 MiB. A connection then owes at most 8 MiB, plus one answer for each of the 16 workers, the answers of writes already queued for a commit, and the DATA that its streams send within the credit that the client granted.

64 KiB of credit on stream 5:

04 00 00 00  07  00  00 00  05 00 00 00                                   a body of 4 bytes, CREDIT, stream 5
00 00 01 00                                                               65,536

Messages: the MessagePack profile

A message is one MessagePack value: a map from small unsigned integer keys to values, under these rules.

  • Types. Nil, bool, integers, float 64, str, bin, array and map. A float 32, an extension type, the timestamp among them, or any other type byte is invalid.

  • Integers. Each field says signed or unsigned and its range. A decoder takes any encoding of a value that fits, ce 00 00 01 2c for 300 as well as cd 01 2c, and refuses one that does not.

  • A float keeps its value; bits that must survive are bin. A float field is a float 64: cb 80 00 00 00 00 00 00 00 is -0. The server keeps its bits, so cb 7f f8 00 00 00 00 00 01, a NaN whose payload is 1, comes back as it went; an SDK keeps the value, NaN, the infinities and -0 included, as far as its language does, and JavaScript promises no NaN's payload. A float whose bits are the data therefore travels as bin: a kv float value, a series' samples, an aggregate's values. A float field also takes an integer that a float 64 holds exactly, since a JavaScript encoder writes 3.0 as 3.

  • Text is str, bytes are bin. A str is valid UTF-8, and neither stands for the other.

  • Keys. A message's keys are unsigned integers; a field that is a map of names, an error's what or a series' labels, says so and has str keys. A key twice is invalid. A key the reader does not know is read past, its value still well formed and within bounds, and then it depends on the reader. A server refuses a request carrying one, unimplemented naming the field, since a field it skipped could change what the client asked, and the answer would be to another question. A client reading an answer, and a server reading HELLO, skip it. So a client leaves out a field at its zero value, and an older server takes everything a newer client sends that it would have sent anyway; and a server adds an answer field only where a client that skips it still reads the answer right, or else answers it only to a client that asked for it in a field of its request. An absent key is the field's default, and nil stands only where a field allows it.

  • Bounds come before allocation. A length or a count past the bytes left in the body is invalid, since every element takes at least a byte; nesting deeper than 8 is invalid; a body is at most the agreed maximum. The server holds a request's lists in at most 64 times the body's bytes, 64 KiB at least: a list past it, as one of a million empty maps, is limit before it is read.

  • Time is an integer: unix milliseconds, unless a field says nanoseconds. Records keep nanoseconds, past what a JavaScript number holds, so an SDK reads such a field as a BigInt:

    1,790,000,000,123,456,789 ns → cf 18 d7 5b 84 2b 4e cd 15

    A duration is an integer of milliseconds.

  • Columns of numbers are bin: a series' times and values, little-endian int64 and float64 one after another.

  • Encoders are canonical, decoders are not. An encoder writes the shortest form of every integer, length and count, keys in ascending order, every float in eight bytes, so that a vector compares byte for byte; a decoder takes any valid form in any order.

  • An SDK's codec is its own: a general library writes plain maps and reads 64-bit integers without rounding when told, but takes a float 32, an extension, a key twice or a value nested nine deep, which this profile refuses. The SDKs' codecs refuse every refused vector.

Errors

An error is the final frame of its stream, with ERROR set:

keyfieldtype
1codestrbelow
2messagestrwhat failed, as the engine's error says it
3whata map of namesthe item it names: a bucket and key, a queue and key, a series' labels, a table and constraint
codemeanssent again
invalidthe request cannot be done as askedno
not_foundwhat the request needs is not there: a file, a config's declarationno
limita bound: memory, size or count; what names the limit, what the call wanted of it and the bound, where the engine knows themlater, or smaller
closedthe store or the handle closedafter opening again
in_usea name is taken, or a lock's key stayed held past a hold's waitlater
conflicta condition or a version no longer holdsafter reading again
corruptstored bytes no longer readno
too_old, too_newa time outside its engine's window; a metrics sample behind what its series has packed names its at and the time it is packed beforeno
suspendeda series in quarantineafter its repair
outcome_unknowna commit whose result is unknown, or a write that ran and whose answer, as the values a take removed, is past the agreed bodyafter reading what it wrote
committed_locallya synchronous commit its home made and no copy it waits for held in time: it stands, and losing that home's disk would lose itno
losta lease ran out or was revoked at its maxHold: another holder may have run beside itno
permissionthe connection's capability does not allow it, as a read connection opening an encrypted bucketno
unimplementeda method, or a field of a request, this server does not have: what names the field, the message the server's versionno
cancelledthe client cancelled it—
unavailablebusy for now: the server is closing, or a copy has no link to its homelater, or elsewhere
internala fault of the server's, or an error its system gave, as a disk's—
protocolin a GOAWAY alone: a frame or a HELLO that breaks this page's rulesno
unauthenticatedin a GOAWAY alone: a token the server does not knowno

Each code is one error class in every SDK, and one sentinel in Go, so that errors.Is(err, tinystore.ErrConflict) holds for a conflict. After a GOAWAY the connection ends. A name's value in what is str, or bin where its bytes are not UTF-8, as a kv key of bytes may be.

A conflict on stream 7:

2c 00 00 00  04  03  00 00  07 00 00 00                                   a body of 44 bytes, RESPONSE, END and ERROR, stream 7
83                                                                        a map of three
   01 a8 63 6f 6e 66 6c 69 63 74                                          code: "conflict"
   02 ad 73 74 61 74 65 20 63 68 61 6e 67 65 64                           message: "state changed"
   03 81 a6 62 75 63 6b 65 74 a8 73 65 73 73 69 6f 6e 73                  what: {"bucket": "sessions"}

Versions

A server and its clients upgrade apart: a remote server deployed once while the applications' SDKs move on, or a sidecar still serving a directory after its application's SDK was updated. So each side promises what it does with an older or a newer one:

  • A connection speaks the older protocol of its two sides. HELLO says the newest the client speaks and WELCOME the one the connection speaks; a server refuses only a client older than the oldest protocol it still speaks. A protocol moves only for what a field cannot carry: frames, the handshake, credit.
  • Within a protocol a message grows by fields, and a request is understood whole or refused. A field the server does not know is unimplemented, naming the field and the server's version, so a newer client using something new learns which server to upgrade rather than reading an answer to another question. A client leaves a field out at its zero value, so one using nothing new talks to any server of its protocol.
  • An answer grows only by what a client may skip. A field whose meaning a client must know is answered only to a client that asked for it with a field of its request, which an older server refuses.
  • A method is added, never repurposed. An older server answers a newer method unimplemented, naming its version. From v0.1.0 on, a message never changes meaning and a field's number is never reused.

A client that finds a sidecar of an older release than its own replaces it:

  1. The client sends server.stop. The sidecar answers, lets its running streams finish, and gives back SERVE and LOCK.
  2. The client starts its own binary, as it does when no sidecar runs, and prints one line about it on stderr.
  3. Every other client of the old sidecar gets GOAWAY and connects to the new sidecar when it connects again.

A client doesn't replace a server that SERVE doesn't call a sidecar, such as a Go program's own server or one that a person runs. It also keeps a sidecar that refuses to stop. In both cases, it prints a warning once on stderr.

Methods

Every method is declared in protocol/*.wire, a file an engine, in the language protocol/README.md defines: its number, who may call it, the message it takes, and its answer's shape and messages. Each message's fields are declared there too, their keys, their types and a comment after a field saying what it holds, and testdata/wire/protocol.json holds a vector of every message, which every SDK reads. The tables below are written from those files by just protocol, and CI checks them, so a number here is the number the server answers.

Each engine's high byte, as Frames says:

high byteengine
0x00server
0x01kv
0x02jobs
0x03sql
0x04blobs
0x05records
0x06metrics
0x07config
0x08backup
0x09locks
0x0achannels
0x0bsearch

may is who may call it: a read connection calls the methods marked read alone, and an admin method is an admin connection's. An answer T is a call's one message; the others are the shapes of Streams:

answerthe stream
Ta call: a T as its RESPONSE·END
download T until Uafter its RESPONSE, any number of T as DATA, then a U with END; an answer that fits one message may be a U as the RESPONSE·END alone
handover Ta T as the RESPONSE·END; or the run handed to the client, which sends the T to keep as its last DATA; or a T as the RESPONSE alone, which hands the client a run in the background and leaves the stream open for that last DATA
exchange T for Uafter its RESPONSE, T from the server and U from the client as DATA, until each side ends its own

The values they carry:

  • a kv value is nil, an integer or bin, as its row keeps it, a bin's first byte the kind that wrote it (1 text, 2 bytes, 3 JSON, 4 a float 64's eight bytes, 5 an unsigned 64, 6 a float 32), and a version is an opaque bin compared only for equality;
  • a job's value is its JSON as str;
  • an SQL value is one of SQLite's five: nil, an integer, a float, str or bin;
  • an event's fields and context are a JSON object as str;
  • a series' samples are two bin columns, an int64 time and a float64 value a sample, 8 bytes each, little-endian, so that every value's bits come back;
  • a search's document is its JSON as str, and a vector bin, four bytes a little-endian float a dimension.

the server

The server's own methods take the range below the engines', 0x00xx.

methodnamemayrequestanswer
0x0001server.stopadminEmptyEmpty
0x0002server.clockadminserver.Clockserver.Clock

A stop is an admin connection's alone, permission to a data connection, and a server whose program said nothing of stopping refuses it with permission too: a program serving its own store decides when that store's server stops. tinystore serve stops at one, as it does at Ctrl+C, which is how tinystore stop ends a sidecar and how an SDK newer than the sidecar it found replaces it with its own binary, as Versions says.

Only a private server started with tinystore serve --stdio --clock <time> has a clock that moves, and the store runs on it instead of the system's clock. An SDK starts such a server when you open a store with private and clock. Only an admin connection can move the clock, and only forward. The server answers invalid to a time before the clock's, both fields at once, or a clock call to a server that runs on the system's clock.

kv

Each open, of a bucket, counters, a rate limit, a quota or once's answers, answers a handle, which every call on it carries. A handle holds kv's rows as they are, so the server reads what any bucket wrote.

methodnamemayrequestanswer
0x0101kv.bucket.openreadkv.BucketOpenHandle
0x0102kv.getreadkv.Callkv.Entry
0x0103kv.hasreadkv.Callkv.Found
0x0104kv.setwritekv.Callkv.Written
0x0105kv.createwritekv.Callkv.Written
0x0106kv.takewritekv.Callkv.Entry
0x0107kv.deletewritekv.Callkv.Found
0x0108kv.expirewritekv.Callkv.Found
0x0109kv.clearwritekv.BranchEmpty
0x010akv.listreadkv.Listkv.Page
0x010bkv.resealwritekv.Branchkv.Resealed
0x010ckv.countreadkv.Branchkv.Count
0x0110kv.counters.openreadkv.CountersOpenHandle
0x0111kv.counters.addwritekv.Callkv.Count
0x0112kv.counters.getreadkv.Callkv.Count
0x0113kv.counters.deletewritekv.Callkv.Found
0x0114kv.counters.clearwritekv.BranchEmpty
0x0120kv.rateLimit.openreadkv.RateLimitOpenHandle
0x0121kv.quota.openreadkv.QuotaOpenHandle
0x0122kv.allowwritekv.Callkv.Allowance
0x0123kv.peekreadkv.Callkv.Allowance
0x0124kv.resetwritekv.CallEmpty
0x0125kv.refundwritekv.CallEmpty
0x0130kv.once.openreadkv.OnceOpenHandle
0x0131kv.once.runwritekv.Callhandover kv.Answer
0x0132kv.once.getreadkv.Callkv.Answer
0x0133kv.once.deletewritekv.Callkv.Found
0x0140kv.txwritekv.Txkv.TxResults

Its messages are in protocol/kv.wire. A kv.tx checks every read it carries and applies every write, all or none; one that fails names its place in what, as check or write and its index. kv.once.run lets one run of a key go at a time, every client's: another run of the key waits until that run ends, then is answered what it kept, or is handed the run when it kept nothing. A client that is handed a run, an answer not found as its RESPONSE, runs its function and sends a kv.Answer as its last DATA: found with the value to keep, or not found when the function failed, which keeps nothing. A client that cancels or leaves keeps nothing either, and the next run of the key is handed over again.

kv.get of token under the owner 7, on handle 1, and its answer:

0e 00 00 00  03  01  02 01  01 00 00 00                                   a body of 14 bytes, REQUEST, END, 0x0102, stream 1
83                                                                        a map of three
   01 01                                                                  handle: 1
   02 91 a1 37                                                            under: ["7"]
   03 a5 74 6f 6b 65 6e                                                   key: "token"

1a 00 00 00  04  01  00 00  01 00 00 00                                   a body of 26 bytes, RESPONSE, END, stream 1
84                                                                        a map of four
   01 c3                                                                  found: true
   02 c4 06 01 68 65 6c 6c 6f                                             value: bin 01 "hello", the text "hello"
   03 c4 01 31                                                            version: bin "1"
   04 cf 00 00 01 a0 c4 50 6c 00                                          expiresAt: 1,790,000,000,000

jobs

jobs.queue.open answers a handle on a queue of JSON values, and jobs.schedule.open one on a schedule, the queue of one repeating job under its name; every other call carries it.

methodnamemayrequestanswer
0x0201jobs.queue.openreadjobs.QueueOpenHandle
0x0202jobs.schedule.openwritejobs.ScheduleOpenHandle
0x0203jobs.addwritejobs.Calljobs.Changed
0x0204jobs.setwritejobs.CallEmpty
0x0205jobs.updatewritejobs.Calljobs.Changed
0x0206jobs.cancelwritejobs.Idjobs.Changed
0x0207jobs.getreadjobs.Idjobs.Job
0x0208jobs.listreadjobs.Listjobs.Page
0x0209jobs.workwritejobs.Workexchange jobs.Held for jobs.Answer
0x020ajobs.stepwritejobs.Stepjobs.Kept
0x020bjobs.keepwritejobs.StepEmpty
0x020cjobs.watchreadjobs.Iddownload jobs.Job until Empty
0x020djobs.txwritejobs.Txjobs.TxResults
0x020ejobs.countsreadHandlejobs.Counts
0x020fjobs.upsertwritejobs.Calljobs.Changed
0x0210jobs.runNowwriteHandleEmpty
0x0211jobs.gatherwritejobs.Gatherjobs.Gathered

Its messages are in protocol/jobs.wire. A jobs.work stream hands the client's worker each job as a jobs.Held, and the client answers it with a jobs.Answer on the same stream: how its run ended, how far it got, which settles nothing, or a stop, which takes no job more. The client ends its side with DATA·END once it takes no more. When that side ends, or the client cancels or leaves, the jobs in its hands fail that attempt, as a worker's whose process died, and the server's DATA·END, {}, follows once that is written. jobs.watch sends the job as it is now, then again as it changes, and ends after the job ends. jobs.step asks for the answer a step of a held job's run kept, and jobs.keep keeps one, so that the attempt after a retry or a lost worker gets it back without running the step again.

sql

sql.open answers a handle on a database by its name, its migrations applied and checked; a read connection's applies none and chooses no durability, and opens the file as it is, not_found when the store holds none.

methodnamemayrequestanswer
0x0301sql.openreadsql.OpenHandle
0x0302sql.queryreadsql.Querydownload sql.Rows until sql.Rows
0x0303sql.execwritesql.Statementsql.Done
0x0304sql.batchwritesql.Batchsql.Batched
0x0305sql.txwritesql.TxOpenexchange sql.TxAnswer for sql.TxCall
0x0306sql.columnsreadsql.Statementdownload sql.Columns until sql.Columns
0x0307sql.describereadsql.Statementsql.Described
0x0308sql.mirrorwritesql.Mirrorsql.Diff
0x0309sql.beginwritesql.BeginHandle
0x030asql.addwritesql.AddEmpty
0x030bsql.commitwritesql.Rundownload sql.Diff until sql.Diff
0x030csql.dropwritesql.RunEmpty

Its messages are in protocol/sql.wire. A query's rows come in its RESPONSE when they fit one message, and otherwise as DATA parts within the client's credit. A row a query downloads past the agreed body is limit. A batch's results travel in one message, and past the agreed body they are outcome_unknown, since the batch committed. A query holds its rows in the server's memory before the first leaves, as many as one all may hold (Limits and defaults). A sql.tx holds its database's writer while the client's calls come as DATA, and a transaction whose client stalls, cancels or leaves is rolled back. A call with parts set gets rows past one answer in several sql.TxAnswers, each within the client's credit and every one but the last with more; a call without it, as a client before 0.11 sends, is refused them as limit. A client sends parts only to a server of its own release or newer, which WELCOME's server says, since an older one refuses the field.

blobs

blobs.open answers a handle on a bucket of files, which every other call carries.

methodnamemayrequestanswer
0x0401blobs.openreadblobs.OpenHandle
0x0402blobs.putwriteblobs.Writeblobs.Written
0x0403blobs.uploadwriteblobs.Writeexchange blobs.Written for blobs.Piece
0x0404blobs.getreadblobs.Atblobs.Got
0x0405blobs.headreadblobs.Atblobs.Head
0x0406blobs.deletewriteblobs.DeleteEmpty
0x0407blobs.copywriteblobs.Moveblobs.Info
0x0408blobs.renamewriteblobs.Moveblobs.Info
0x0409blobs.expirewriteblobs.Expireblobs.Found
0x040ablobs.listreadblobs.Listblobs.Page
0x040bblobs.usagereadblobs.Folderblobs.Usage
0x040cblobs.clearwriteblobs.FolderEmpty
0x040dblobs.readreadblobs.Readdownload blobs.Piece until Empty
0x040eblobs.directoryreadblobs.DirectoryHandle
0x040fblobs.scanwriteblobs.Folderblobs.Scanned
0x0410blobs.changesreadblobs.Sinceblobs.Changes
0x0411blobs.forgetwriteblobs.FolderEmpty
0x0412blobs.getOrCreatewriteblobs.Claimhandover blobs.Filled
0x0413blobs.setMaxSizewriteblobs.SetMaxSizeEmpty
0x0414blobs.trimwriteblobs.Trimblobs.Trimmed

Its messages are in protocol/blobs.wire. blobs.upload takes a file's bytes as DATA pieces, its last publishing the file, and blobs.read sends them back, the first piece in its RESPONSE and the rest as DATA within the client's credit.

blobs.getOrCreate is handed over as kv.once.run is. A file at the path ends the stream with a blobs.Filled that numbers its fields as a get's blobs.Got. Otherwise one stream at a time holds the path's claim, every client's: another waits, then is answered the file that run wrote, or the failure it ended with, or is handed the claim itself. A client handed the run, a RESPONSE without END, runs its function and writes the result with a blobs.put or a blobs.upload on the same connection whose fill names the stream: the write lands only while the claim holds and the path is empty, and answers no info when it did not. It then sends a blobs.Filled as its last DATA, with the failure that every waiting call gets when the function or the write failed. The server renews the claim while the stream is open, up to timeout; a CANCEL or the connection's end lets it go at once.

records

records.open answers a handle on a stream of events, which every other call carries.

methodnamemayrequestanswer
0x0501records.openreadrecords.OpenHandle
0x0502records.appendwriterecords.Appendrecords.Appended
0x0503records.listreadrecords.Queryrecords.Page
0x0504records.countreadrecords.Queryrecords.Count
0x0505records.topreadrecords.TopAskedrecords.Tops
0x0506records.aggregatereadrecords.AggregateAskedrecords.Rows
0x0507records.streamsreadEmptyrecords.Streams
0x0508records.fieldNamesreadrecords.FieldNamesAskedrecords.Names
0x0509records.pollreadrecords.PollAskedrecords.Batch
0x050arecords.tailreadrecords.Querydownload records.TailBatch until Empty
0x050brecords.lineswriteHandleexchange records.Dropped for records.Piece
0x050crecords.damagedreadEmptyrecords.Damages
0x050drecords.dropwriterecords.DamageEmpty
0x050erecords.fieldsreadrecords.FieldsAskedrecords.StreamFields
0x050frecords.largestreadrecords.LargestAskedrecords.Events
0x0510records.deletewriterecords.Queryrecords.Count
0x0511records.sessionsreadrecords.SessionsAskedrecords.Sessions

Its messages are in protocol/records.wire. records.tail sends a batch each time events arrive that its query finds. records.lines takes another program's output as DATA, cut anywhere, and its last answers with what the writer dropped.

metrics

Metrics are one store of series, each named by its labels, so none opens a handle.

methodnamemayrequestanswer
0x0601metrics.readreadmetrics.Querydownload metrics.Read until metrics.Read
0x0602metrics.latestreadmetrics.Querydownload metrics.Latest until metrics.Latest
0x0603metrics.aggregatereadmetrics.AggregateAskeddownload metrics.Aggregates until metrics.Aggregates
0x0604metrics.explainreadmetrics.AggregateAskedmetrics.Plan
0x0605metrics.namesreadmetrics.PageAskedmetrics.NamePage
0x0606metrics.labelNamesreadmetrics.PageAskedmetrics.TextPage
0x0607metrics.labelValuesreadmetrics.PageAskedmetrics.TextPage
0x0608metrics.descriptionreadmetrics.NameAskedmetrics.Description
0x0609metrics.damagedreadEmptymetrics.Damages
0x060ametrics.ingestwritemetrics.IngestEmpty
0x060bmetrics.describewritemetrics.DescriptionEmpty
0x060cmetrics.deletewritemetrics.SeriesNamedmetrics.Deleted
0x060dmetrics.flushwriteEmptyEmpty
0x060emetrics.instrumentswritemetrics.Sessionexchange metrics.Ack for metrics.Batch
0x060fmetrics.ingestPrometheuswritemetrics.ExpositionEmpty
0x0610metrics.uploadPrometheuswritemetrics.Uploadexchange Empty for metrics.Piece
0x0611metrics.replacewritemetrics.ReplaceEmpty
0x0612metrics.uploadwritemetrics.IngestUploadexchange Empty for metrics.Piece
0x0613metrics.comparereadmetrics.CompareAskedmetrics.Compared
0x0614metrics.compareGroupsreadmetrics.CompareAskeddownload metrics.ComparedGroups until metrics.ComparedGroups

Its messages are in protocol/metrics.wire. A read, the newest samples and an aggregate answer in parts within the client's credit, a series longer than a part cut across parts. metrics.instruments takes a client's batches on a stream of their own, applied in turn, each answered with the last batch of the session the store applied. metrics.ingestPrometheus carries an exposition's text in its request; a text past the body agreed goes by metrics.uploadPrometheus, its size in the request, 32 MiB at most, and its bytes as DATA pieces. The store reserves its memory for the whole text before it keeps a piece, refuses pieces that come to more or fewer bytes than the size, and answers the last piece once the text is written, every series or none.

config

methodnamemayrequestanswer
0x0701config.openreadconfig.Openconfig.Value
0x0702config.followreadHandledownload config.Value until Empty
0x0703config.updatewriteconfig.Updateconfig.Value
0x0704config.resetwriteconfig.Resetconfig.Value

Its messages are in protocol/config.wire. config.follow sends the config's value now and again each time it changes, until the client cancels it.

backup

methodnamemayrequestanswer
0x0801backup.writeadminbackup.Writedownload backup.Piece until backup.Written

Its messages are in protocol/backup.wire. Only an admin connection can ask for a backup, since it holds every byte of the store. The server sends the zip of every engine's files in pieces, as it writes them, within the client's credit, then what it holds. include names files of the application's by their paths inside the store's directory, which the zip holds beside the engines'.

locks

methodnamemayrequestanswer
0x0901locks.holdwritelocks.Holdlocks.Held
0x0902locks.renewwritelocks.RenewEmpty
0x0903locks.releasewritelocks.LeaseEmpty
0x0904locks.statereadlocks.StateAskedlocks.State

Its messages are in protocol/locks.wire. A hold is answered once its key is given, from whichever thread lets it go, and a client that cancels it before is answered cancelled.

A hold's request is 16 random bytes the client picks. A hold sent again with the same request, after its answer was lost, on any connection, is answered the lease already given, which then lasts its ttl from that answer. A lease that ran out before it was asked again has ended, and the hold is a new one, with a new fence. A hold still waiting takes over the earlier one's place in line, which is answered cancelled. renew and release name the lease by lease, 16 random bytes only its holder learns: a fence, which a holder hands to others, proves nothing.

channels

methodnamemayrequestanswer
0x0a01channels.publishwritechannels.PublishEmpty
0x0a02channels.subscribereadchannels.Subscribedownload channels.Batch until Empty
0x0a03channels.subscribersreadchannels.Branchchannels.Count

Its messages are in protocol/channels.wire. A subscription answers once the store has it, then sends its batches within the client's credit. Neither the publisher nor the server waits for a client that grants nothing: it misses messages, and the next batch says how many, as Subscriptions explains.

An index opens a handle, as a bucket does; its documents are JSON as str, and a vector is bin, its floats little-endian, four bytes a dimension.

methodnamemayrequestanswer
0x0b01search.openreadsearch.OpenHandle
0x0b02search.setwritesearch.SetEmpty
0x0b03search.setManywritesearch.SetManyEmpty
0x0b04search.deletewritesearch.Keysearch.Deleted
0x0b05search.getreadsearch.Keysearch.Got
0x0b06search.searchreadsearch.Querysearch.Found
0x0b07search.statusreadHandlesearch.Status
0x0b08search.dropIndexwritesearch.Namesearch.Dropped
0x0b09search.listreadEmptysearch.Listed
0x0b0asearch.searchManyreadsearch.ManyQuerysearch.ManyFound

Its messages are in protocol/search.wire. A set on an index with vectors gives vector, or noVector: true for a document only its words find; one that says neither is invalid. A read connection opens an index only as it is.

A table's index opens with database, a handle sql.open gave, and table, with key and vectorColumn where it needs them: its fields and filters are columns of the table. Its search answers columns once and each hit's row, a cell a column, as sql.Rows carries rows, and value null. A set, setMany, delete or get on it is invalid, since the table owns the rows, and dropIndex names the database beside the name.

search's where

A search's where is a JSON list of conditions, every one of which a document passes, as the Bun SDK writes its where object:

conditionpasses a document that
{"eq": [path, value]}holds the value, or a list holding it
{"in": [path, [values]]}holds one of them; an empty list passes none
{"missing": path}holds no value there: no field, null or an empty list
{"range": [path, {"gte": 10, "lt": 100}]}holds a number within it: gt, gte, lt and lte
{"or": [conditions]}, {"and": [conditions]}passes any, or every, of them

A value is text, a number or a boolean: the text "50" never passes for the number 50, and an integer past 2⁵³ is written as its digits and matched exactly. A path the index was not opened with is invalid.

For a table's index, a list's place may hold {"statement": n} instead, {"in": [path, {"statement": 0}]}: the values the nth of the query's statements gives, a statement of the index's database of one column, run in the search's snapshot. On the table's key column it needs no filter. An index of documents refuses it as invalid, and so does a server before it, as a condition it does not read.

Edit this page on GitHub Updated 27 November 2026

esc
↑↓ navigate ↵ open ⇥ filter 0 results