1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image

Source/'s content is at the root now, Source/README.md merged into
readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1),
release.ps1 (over release.py) and clean.ps1. Everything is LF except the
.ps1 files.

CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks,
then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on
its own kind of runner, the archives kept as artifacts. release.py names
the platform from the Rust host, make_wheel.py tags the wheel from the
library's header.

docker/: the server's image (built from source, the tools beside it, uid
10001), compose.yml and test.sh. CI builds amd64 and arm64 natively,
checks them, and on a tag pushes them to ghcr.io with an index for
<version> and latest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 01:13:44 +01:00
parent 17ec69c03c
commit 5045019df4
93 changed files with 634 additions and 277 deletions
+135
View File
@@ -0,0 +1,135 @@
# Certificates
Who connects to whom, and how it's checked. The code is
`crates/bakashrot-pki` (the library) and `crates/bakashrot-tools`
(`bakashrot-cert`, the tool). Decided in `../revamp.md`, "Decided".
## The idea
One CA per deployment. Every client and every server has a certificate
from it, saying who it is: a node's name and its roles. Servers trust the
CA, not lists of keys; clients trust the CA, not a server's key. Revoking
is a CRL file from the CA, pushed to the servers.
## Certificates
- **Keys:** ECDSA P-384, signatures SHA-384 (the strongest rustls checks).
- **The identity**, an extension of BakaShrot's own, non-critical (rustls
refuses critical extensions it doesn't know):
```
BakaShrotIdentity ::= SEQUENCE {
version INTEGER, -- 1
name UTF8String, -- the node: "kitchen"
roles SEQUENCE OF UTF8String -- free: "sensor", "peer"...
}
```
Names and roles follow the name rules (1-64 of `A-Z a-z 0-9 _ . -`, not
only digits), 64 roles at most. Roles mean nothing to the certificates:
the server's config says what each may do.
- **Its OID is a placeholder** (`IDENTITY_OID`, `1.3.6.1.4.1.32473.1.1`,
under the PEN RFC 5612 reserves for documentation; `bakashrot-cert`
warns while it is): it goes under NibblePoker's own PEN before
certificates are issued for real. Why, how to request it, what to change:
`oid.md`.
- **The CN is the name too**, for people (`openssl x509 -text`, logs). Only
the extension is trusted.
- **Clients' certificates** are for `clientAuth`. **Servers'** are for
`serverAuth` and `clientAuth` (a server is its peers' client), and have
one DNS name, `bakashrot-server` (`SERVER_NAME`): a label, not a host.
- **No host names or IPs:** a client connects to any address and asks for
`bakashrot-server`; rustls' own verifier then checks the server's
certificate is the CA's, valid, not revoked... and for servers. A
client's certificate can't pose as a server's: it isn't for `serverAuth`
and doesn't have the name.
- **Lifetimes:** the CA 10 years, the others 1 year, by default.
- **The CA's key stays off the servers:** whoever has it can make any
identity, peers included.
## TLS
`bakashrot_pki::tls`: TLS 1.3 only, through aws-lc, offering only the
strongest of everything (both ends are ours, nothing to negotiate down to):
- cipher suite `TLS13_AES_256_GCM_SHA384`;
- key exchange `X25519MLKEM768`, the X25519 + ML-KEM hybrid (holds against
quantum computers too);
- ALPN `bakashrot`: what isn't BakaShrot is refused in the handshake (the
protocol's version is checked right after, `protocol.md`);
- a certificate from the CA on both ends;
- randomness (keys, nonces) from the OS: aws-lc's generator seeded from
Windows' `ProcessPrng` or Linux's `getrandom`, plus RDRAND, as BoringSSL
and `ring` do. Built without its CPU Jitter Entropy
(`AWS_LC_SYS_NO_JITTER_ENTROPY`, `../.cargo/config.toml`), which only adds
a source and cost 25 ms in every process, at its first connection.
`server_config()` checks clients with rustls' verifier, `client_config()`
checks the server with rustls' verifier too (for `bakashrot-server`). Then
both check the certificate isn't revoked and has an identity. Once
connected, `peer_identity()` gives the other end's `Identity`.
## Revocation
- `bakashrot-cert revoke` writes `ca.crl`, signed by the CA, with every
certificate revoked before (written aside, then moved in place).
- A server reads it into `Revocations`, which its TLS setup shares
(`SharedRevocations`): replacing what's inside takes effect for the next
handshake, no new configuration needed. `Revocations::revokes()` tells
the server which open connections to drop.
- **Both ends check it:** `server_config()` and `client_config()` both take
the revocations (`Revocations::none()` without a CRL). A server dialing
its peer is the peer's client, with the same CRL: servers block each
other, whichever end dials.
- **Revoking is by certificate, not by name:** each certificate has its own
key and its own serial number (made from that key), so two of the same
name (two servers named alike, a new one before the old one goes) are
revoked one at a time.
- A CRL is only taken if it's the CA's: issued by it, its signature
checked. One that isn't is refused, the server keeps the previous one.
Its "next update" isn't held against it: CRLs are pushed by hand.
- The server watches the file (its time and size, every 5 s), reloads
it, and drops a revoked certificate's connection at its next request
(`server.md`).
## The tool
```
bakashrot-cert ca --name "Home CA" ca.crt, ca.key
bakashrot-cert issue --name kitchen --role sensor kitchen.crt, kitchen.key
bakashrot-cert issue --name server-1 --role peer --server
bakashrot-cert revoke kitchen.crt ca.crl
bakashrot-cert show kitchen.crt
```
`--ca` (the folder of `ca.crt` / `ca.key`, `.` by default), `--out` (where
to write), `--days`, `--file` (the files' name when it isn't the node's:
another certificate of the same name, `--file server-1b`). Files are PEM. Nothing is ever written over an
existing certificate or key; keys are readable by their owner only on
Unix. `revoke` only takes certificates the CA issued.
## Tests
- `bakashrot-pki/tests/tls.rs`: handshakes in memory. The strongest
settings negotiated, identities both ways, a server as its peer's
client; refused: a client or a server of another CA, a client's
certificate posing as a server's, a revoked client (and taken again once
the CRL changes, on the same configuration), a certificate without an
identity, another protocol; clients given the CRL refusing a revoked
server, servers blocking each other both ways, two servers of the same
name each with its own certificate, revoked one at a time.
- `bakashrot-pki/tests/ca.rs`: what certificates say, a CA's key that isn't
its own, CRLs revoking exactly what they list, another CA's or a
tampered CRL refused, and OpenSSL agreeing (`openssl verify` for clients
and servers, the CRL's signature, a revoked certificate; skipped without
OpenSSL, Git's is found).
- `bakashrot-tools/tests/cert.rs`: the tool end to end, two certificates
of the same name, and what it refuses (overwriting, bad names and roles,
another CA's certificate).
## For later
- **`AllowedServerNames`** in a client's config and for the peers a
server dials: the server names it accepts (any of the CA's servers
without it).
- NibblePoker's PEN, replacing the placeholder OID (`oid.md`).
+187
View File
@@ -0,0 +1,187 @@
# The clients
What apps connect with, in layers:
| Layer | Where | For |
|---|---|---|
| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` |
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the old `BakaShrot_*` exports, one connection per process |
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes, as the old DLL's |
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
| The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` |
Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the
wire: `protocol.md`; the server's side: `server.md`.
**Status:** steps 7 to 9: connecting, pushes, messages, attachments,
names, queries.
## Who connects: certificates
A client is its certificate, issued by the CA the servers trust
(`certificates.md`, `bakashrot-cert issue`): its name is its node, its
roles say what it may do on each server (`config.md`). It needs the CA's
certificate (to check the server's), its own certificate and key, and the
CA's CRL if there is one (servers it revokes are refused).
### `client.toml`
What Python's `Client.from_file()` and the tools read. Paths are relative
to the file's folder.
```toml
server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port
ca = "ca.crt"
certificate = "kitchen.crt"
key = "kitchen.key"
crl = "ca.crl" # optional
```
## The DLL
The old DLL's conventions, kept:
- **One connection per process.** Calls from several threads wait for each
other.
- **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16
(`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these),
null-terminated. A null string is an empty one where that means
something (a message), refused otherwise (`InvalidArgument`).
- **Strings out** are copied into the caller's buffer of `BufferSize`
bytes: the getter returns the bytes needed, terminator included, and
copies nothing if they don't fit; a null buffer asks for the size.
- **Failures:** 0, or -1 where a count or an id is returned. Then
`BakaShrot_GetLastError()` gives the code (`../crates/bakashrot-proto/src/error.rs`:
1-99 a server's refusal, the connection still open; 100 and up the
client's own) and `BakaShrot_GetRefusalReason()` why, in words (now for
every failure, not only refusals). After `ConnectionLost` or
`ProtocolError` the connection is closed: connect again. Nothing
reconnects by itself; a push whose answer was lost may have been stored.
- **Inside:** every export catches panics (`Internal`); no threads, no
runtime, so it unloads cleanly; nothing allocated on one side is freed
on the other; the C runtime linked statically on Windows (the release
DLL imports system DLLs only).
| Exports | What |
|---|---|
| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` |
| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` |
| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed |
| `GetNode` (`A`/`W`) | the node the server says this client is |
| `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure |
| `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet |
| `GetMessages(Topic, Node, After, Limit)` (`A`/`W`) | how many (0 isn't a failure), -1 on failure; then `GetMessageCount`, `SelectMessage(Index)`, `HasMoreMessages` |
| `GetMessageId`, `GetMessagePushedAt`, `GetMessageAttachmentSize`, `IsMessageAttachmentReady`, `GetMessageData`/`Topic`/`Node` (`A`/`W`) | the selected message; topic and node as asked |
| `ListTopics`, `ListNodes`, then `GetNamesList` (`A`/`W`) | how many; `{"kind":"topic","names":[...],"truncated":false}` |
| `Query(Sql)`, then `GetQueryResult` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` |
| `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) |
| `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file |
| `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit |
| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed |
The header has each one's comment. Every name starts with `BakaShrot_`.
### Changed from the PureBasic DLL
- **Connecting:** certificates instead of keys and a node:
`SetCaCertificate`, `SetCertificate`, `SetCrl` are new, `SetPrivateKey`
takes a PEM key; `SetPublicKey`, `SetServerPublicKey`, `SetNode`,
`SetNodeId` are gone. `GetNode` is new (the node comes from the
certificate).
- **No default topic:** `PushMessage(Data)` is gone, `PushMessageTo` names
its topic.
- **Attachments:** the same six, by names.
- **No ids:** `GetLatestMessage(TopicId, NodeId)`, `GetMessageTopicId`,
`GetMessageNodeId`, `ResolveTopic`, `ResolveNode`, `GetResolvedName` are
gone; `GetNamesList` lists names.
- **The file:** `bakashrot.dll` (`libbakashrot.so`), no libsodium next to
it.
## Python
`bindings/python/bakashrot.py`, the old module adapted: `Client(server, ca,
certificate, key, crl=None)` (PEM text or paths) or
`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs
on 3.8), `client.node` once connected, `push(data, topic,
attachment=None)` (the topic required; the attachment bytes or a path),
`latest()`, `get_messages()`, `iter_messages()`, `follow()`,
`get_attachment()` (bytes), `save_attachment()` (a file),
`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`.
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
refused, either way, or no role allowed), `BakaShrotError`. The DLL is
looked for next to the module, or `BAKASHROT_DLL`. The release has a
wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
`bindings/python/make_wheel.py`, `../README.md`, "Releases").
## PureBasic
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then
the `W` exports under the old names, `BakaShrot_*String()` helpers for the
getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile>
<CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one
with an attachment, reading both back (checked by hand with 5.73 against
a server; not in CI, which has no PureBasic).
## The tools
`bakashrot`, the old `BakaShrot*` tools in one program (`bakashrot-cert`,
for the CA, is apart: `certificates.md`). Each command connects with
`-c <file>` (`client.toml` by default), does one thing and exits: 0, 1 on a
failure (why on stderr: `Refused by the server (NotAllowed): ...`,
`Failed to connect to ...`), 2 on bad arguments. `--help` on each.
```text
bakashrot push logs '{"t":21}' Pushed as message #42
bakashrot push logs @reading.json (- for the standard input)
bakashrot push logs '{"cam":1}' -a photo.jpg Pushed as message #43, with an attachment of 81234 bytes
bakashrot latest logs kitchen Message logs:kitchen#43, pushed 2026-11-14T09:12:03.120Z
Attachment: 81234 bytes
{"cam":1}
bakashrot attachment logs kitchen 43 copy.jpg Saved 81234 bytes as copy.jpg
bakashrot messages logs kitchen 1<TAB>{"t":20}, a line each
bakashrot messages logs kitchen -f --after latest --time
bakashrot query "SELECT topic, count(*) FROM messages GROUP BY topic"
bakashrot list Topics (2): ... Nodes (1): ...
bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false}
```
- **`messages`:** the first 100 by default (`--limit 0` for all), `--after
<id>` or `latest`; data as stored, a line break in it spanning lines;
`--follow` checks every `--interval` ms (500) until stopped or the
connection fails (exit 1); `--time` adds the push time between the id and
the data.
- **Attachments:** `push -a <file>`; `attachment` replaces the file,
leaves none if it fails; `latest` says a message's (", not on this
server yet" for one on its way from a peer).
- **Messages and SQL:** inline, `@file` or `-` (a UTF-8 BOM dropped).
PowerShell before 7.3 drops the double quotes inside arguments: use a
file there.
- **Changed from the old tools:** one program; `-c` instead of the last
argument, `client.toml` instead of `client.ini`; `push` names its topic;
names only (no ids in the output, `ResolveIds` gone); errors on stderr;
`GetAttachment` is the `attachment` command.
- **Speed** (release, a local server, 2026-11-14): a command takes about
11 ms, connecting included (the old tools 8 ms); `messages --limit 0`
writes 200,000 messages to a file in 0.26 s (Python's `iter_messages()`:
1.5 s). Against the old ones: `server.md`, "Measured".
## Tests
`crates/bakashrot-capi/tests/`, each against a server on a free port:
- `exports.rs`: the exports as C calls them: certificates from files and
PEM, the `W` strings (and some `A`), the buffers (the size, too small,
unaligned), selecting messages, attachments (from a file and memory,
saved and loaded, the buffer, refused ones), every refusal and the
client's own errors, closing, another identity.
- `python.rs`: runs `bindings/python/check_bakashrot.py` (the old one,
ported: 52 checks) on the DLL; skipped, saying so, without Python 3.11+.
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
when it doesn't: check it in).
`crates/bakashrot-tools/tests/bakashrot.rs` runs the tool against a server:
the old GetMessages suite's checks (`--follow` too), the Names,
BigMessages and Attachments suites' tool checks, queries, lists,
`client.toml`.
+114
View File
@@ -0,0 +1,114 @@
# The server's config
One TOML file, read and checked at once by `crates/bakashrot-config`: a
config that's wrong is refused whole, saying where (the line, shown) and
why. Every value is checked as it's read (serde), so every refusal has its
line. Every key, with its default: `crates/bakashrot-config/example.toml`.
Decided in `../revamp.md`, "Decided".
## What's in it
| Section | What |
|---|---|
| `[server]` | where it listens, the certificate files, the database, its topics, how pushes are flushed, attachments, retention's pace |
| `[retention]` | how long each topic's messages are kept |
| `[replication]` | the servers it sends to and takes from, the topics replicated at all, retry and sync pace, batch size |
| `[roles.<name>]` | what certificates with that role may do |
Unknown keys are refused, so a typo or a key of the old ini is caught.
## Who's who: certificates, then roles
A connection's certificate (`certificates.md`) says its node (its name)
and its roles. The server looks its roles up in `[roles.*]`:
- **Everything its roles allow, each role on its own**: `sensor` and
`reader` push what `sensor` may push, read what `reader` may read. For
replication, a role's topics go with that role's nodes, they're not
mixed with another role's.
- **None of its roles has a section: refused.** Roles the server doesn't
know are ignored (a certificate may have roles for other servers).
- Roles compare without case, like names.
What a role gives:
| Key | Default | Allows |
|---|---|---|
| `push_topics` | none | pushing to these topics, always as its own node |
| `read_topics` | none | reading these topics' messages |
| `query` | `false` | read-only SQL, which reads every topic |
| `send_topics` | none | replication: these topics sent to it |
| `accept_topics` | none | replication: these topics taken from it |
| `send_nodes` | `["*"]` | replication: only these nodes' messages sent |
| `accept_nodes` | `["*"]` | replication: only these nodes' messages taken |
No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No
default topic: a push always names its topic (protocol 7 has none).
## Peers
Who replicates with whom is each server's config, by address (not the
certificates: that would mean reissuing them):
- **`[replication] push_to`:** the servers it dials and sends to,
`host:port`.
- **`[replication] accept_from`:** the servers it takes replicated
messages from, IP addresses or hostnames without a port, `"*"` for
all; none by default. Clients aren't concerned: they push wherever
their roles allow.
A link carries messages one way: the server that dials sends, the one
dialed takes them. What's sent and taken is still the roles': the other
server's certificate's roles here, their `send_*` for what's sent to it,
their `accept_*` for what's taken from it.
`[replication] replicated_topics`, optional, filters every peer's
replication whatever its roles say: an edge node that keeps some topics to
itself. Without it, no filter; `[]` replicates nothing. Pushing and reading
aren't filtered.
## Names and values
- **Names** (topics, nodes, roles): 1-64 of `A-Z a-z 0-9 _ . -`, not only
digits, compared without case. Lists of topics or nodes also take
patterns: `*` any characters, `?` one, `"*"` for all. `[server] topics`
takes names only.
- **Names with dots are quoted as keys:** `"sensors.kitchen" = "12h"`,
`[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused,
`[retention]` says to quote.
- **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`,
`"1d12h"`. Ages in `[retention]` can also be `"forever"`.
- **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T.
- **Paths:** relative ones are from the config file's folder.
## Retention
A topic takes its name's line, else the first pattern matching it in the
file's order, else `"*"`'s line wherever it is; without any, it's kept
forever. Ages count from when a message was first pushed, on whichever
server; each server has its own.
## What changed from the old ini
| Old (`OldSource/Server/Config/schema.ini`) | Now |
|---|---|
| `PrivateKey`, `[BakaShrot] Node` | `ca`, `certificate`, `key`: the node is the certificate's name |
| `[BakaShrot.Client.*]`: keys, `Node`, `Allow*` | `[roles.*]`, the node and roles from the certificate |
| `[BakaShrot.Peer.*]`: `Host`, `Port`, `Node`, `PublicKey`, topic and node lists | `[replication] push_to` and `accept_from` (addresses), the lists in the peer's roles |
| `ReplicatingTopics` | each peer role's `send_topics` / `accept_topics`; `replicated_topics` filters them all |
| topic and node ids, pins, ranges, `[BakaShrot.Nodes]` | names only: ids are the database's |
| `DefaultTopic` | dropped: a push always names its topic |
| `Host` + `Port` | `listen` |
| seconds | durations (`"10s"`) |
| `NetThreadPoolSize` | gone (tokio) |
| `UploadTimeout` | gone: attachments are streamed in their push (protocol 7), nothing waits |
| `FULL` / `NORMAL` | `"full"` / `"normal"`; `off` still refused |
## Tests
`crates/bakashrot-config/tests/config.rs`: the example, the defaults,
every setting, retention's order, permissions (several roles, none known,
replication per role), `replicated_topics`, paths from the config's
folder, and the refusals, each with its line: TOML errors, unknown keys
(the old ini's too), every value that's wrong, names twice (without case),
unquoted dotted names.
+75
View File
@@ -0,0 +1,75 @@
# Known issues and ideas
What's still true of the PureBasic version's notes, for this one. That
version was removed on 2026-11-15; it's in git history up to commit
`68966a8` (`OldSource/Notes.md`, "Open items"; `OldSource/Design/`).
## Threat model
BakaShrot is an **internal tool, on trusted machines and a trusted
network**, not exposed to the internet. So:
- TLS and the certificates are defence in depth: they stop a misconfigured
client or server from talking to the wrong one and keep data off the
wire in clear, they aren't holding off attackers.
- The security issues below are low priority unless the deployment
changes. If it ever faces an untrusted network, start with messages
signed by their origin and rate limiting connections.
- Correctness, durability and operations matter more: losing or mixing up
data, or a server that can't run unattended, hurts on day one.
## Known issues
- **One server per node, not checked.** A node's messages are pushed to
one server; the others get them by replication. A node pushing to two
servers that replicate makes the same ids with different messages on
each: only the last id per topic and node is compared, so it's never
noticed, and a replicated id already stored keeps the local message.
Fix if that rule ever has to go: one server owns each topic and node's
ids (the others refuse or forward pushes), or at least compare a hash of
the messages to log the drift.
- **Gaps in a topic and node's ids aren't detected** on replication (old
item 6). A server with `1, 2, 5` says 5 and never gets 3 and 4. Batches
are sent in order and a refusal stops them, so it needs something
unusual, but nothing repairs it. Fix: send the count with the last id
(count = last id: no gaps), compare ranges when they differ.
- **The attachments a server lacks:** it reports the 256 oldest at a
time (`SyncState`). With several peers, ones none of them has can hold
back newer ones.
- **Peers are trusted with what they replicate** (old item 12): a server
in `accept_from` can send any message its roles accept, for any node.
Messages carry no proof of who first wrote them. Fix: sign each message
with its node's key when first stored, check it on replication (every
server then needs every node's public key).
- **Private keys sit in PEM files**, readable by whoever can read them: on
trusted machines, file permissions are enough.
- **One connection per process in the DLL** (old item 10, `revamp.md`,
"Open questions"): a handle-based API for several. Polling rather than
pushed subscriptions; nothing reconnects by itself, on purpose.
- **At least once:** a push whose answer was lost (the server stopped
between committing and answering) is stored twice if retried. A client
that minds reads the latest message before retrying.
## Ideas for later
From the old benchmarks and suggestions (`OldSource/Design/Suggestions.md`),
worth it only when a use calls for them:
- **Several pushes in flight per connection.** One request at a time
(`protocol.md`, "Rules") caps a node at one push per round trip:
thousands a second on a LAN, about 20 over 50 ms. A client could send
several before the first answer (answers come back in order; a request
id to match them), with an asynchronous push in the DLL beside the
blocking one. The server already groups pushes from every connection.
- **Replication, lower lag:** a link checks in again at once after
sending, otherwise every `sync_interval`. Next, cheapest first: check
in as soon as the writer commits something (at most every 100 ms or so);
send several batches before the first answer (the receiver must then
refuse a batch that doesn't follow its last id, which also closes the
gaps above); several connections per link, each topic and node always
on the same one.
- **Benchmark on two machines:** on one, the load generator and the
servers compete for the CPU and the disk.
- **A JSON field queried often:** a generated column with an index on it
turns a full scan into a lookup (`storage.md`, "For later", has the
other storage ideas).
+77
View File
@@ -0,0 +1,77 @@
# The identity extension's OID
**Open point:** the OID is a placeholder until NibblePoker has its own
Private Enterprise Number (PEN) from IANA. The owner's to request
(below), then a few lines to change here.
## Why it matters
Servers find a certificate's name and roles by its identity extension's
OID (`bakashrot_pki::IDENTITY_OID`). Changing the OID makes every
certificate issued before unreadable as a BakaShrot identity: all of them
would have to be issued again. So it's settled before certificates are in
use; what's inside the extension can still change (its `version` field)
without touching the OID.
Within a deployment, only the CA's certificates are read, so another
extension using the same OID somewhere else can't confuse a server. The OID
mostly needs to be stable, and properly ours.
## Now: a placeholder
- `IDENTITY_OID = 1.3.6.1.4.1.32473.1.1`: under PEN 32473, "Example
Enterprise Number for Documentation Use" (RFC 5612). It works, but isn't
meant for real use, and examples elsewhere use it too.
- `IDENTITY_OID_IS_PLACEHOLDER = true`: `bakashrot-cert` warns whenever it
makes a CA or issues a certificate.
- Fine for development and tests; not for certificates in use.
- `OldSource/`'s UUID arc (`2.25.2320...0981`) can't be used: `rcgen`
writes OID parts of 64 bits at most, a UUID is 128.
## Requesting a PEN
From IANA's application page (checked 2026-11-13):
1. **Check first** that NibblePoker doesn't have one: search the registry,
<https://www.iana.org/assignments/enterprise-numbers/> (it had none on
2026-11-13). An organization that has one hands out sub-numbers under
it instead of asking for another.
2. **Apply** at <https://pen.iana.org/pen/PenApplication.page>. It's free.
It asks for:
- the **assignee**, the organization (or person) the number is for:
name ("NibblePoker"), address, country, phone (optional);
- a **contact**, the person IANA and others write to with questions,
who may also request changes later: name, address, country, phone and
fax (optional), **email** (required).
3. **Confirm** the request from the email IANA sends to that address.
4. **Wait:** if nothing else is needed, the number comes within seven days
of that confirmation. Questions: iana-pen@iana.org.
**What's public:** the registry lists, for every number, the organization,
the contact's name and the contact's email address (written with `&` for
`@`). Use an address meant to be published (a role address, not a
personal one).
Ask for one number for NibblePoker as a whole, not one per project: every
project gets its own branch under it.
## Once the number is there
With `<PEN>` the number IANA gave:
1. **Plan the branches**, and record them in the table below; a number
once given is never reused:
| OID | What |
|---|---|
| `1.3.6.1.4.1.<PEN>` | NibblePoker |
| `1.3.6.1.4.1.<PEN>.1` | BakaShrot |
| `1.3.6.1.4.1.<PEN>.1.1` | BakaShrot's identity extension |
2. **In `crates/bakashrot-pki/src/lib.rs`:** `IDENTITY_OID` to
`[1, 3, 6, 1, 4, 1, <PEN>, 1, 1]`, `IDENTITY_OID_IS_PLACEHOLDER` to
`false`.
3. **Update** this file (the table, "Now"), `certificates.md` and the open
point in `../revamp.md`.
4. **Issue again** any certificate made with the placeholder, and run
`test.ps1` (the tests issue their own, nothing to change there).
+183
View File
@@ -0,0 +1,183 @@
# Protocol 7
What goes over a connection between a client and a server, or two servers.
The code is `crates/bakashrot-proto`; this describes it. Protocol 6, the
PureBasic one, is `OldSource/Design/Packets.md`: what the requests do is
mostly the same, the transport, the encoding and the packets themselves
were simplified (see the end).
**Status (2026-11-13):** packets, frames, names and error codes are written
and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`,
`certificates.md`). The server and the client speak it so far for
connecting, pushes and messages (`server.md`).
## Transport
- **TCP, then TLS 1.3**, both ends with a certificate from the deployment's
CA (mutual TLS, `revamp.md`, "Decided"), at the strongest settings
rustls has: ECDSA P-384 certificates, AES-256-GCM-SHA384, the X25519MLKEM768
key exchange, nothing else offered.
- **Identities:** a certificate's identity extension gives its node's name
and roles. The client's is who it is; the server's is checked by the
certificate alone (the CA's, valid, not revoked, for servers, the name
expected), no host names or IPs. Revoked certificates are in the CA's
CRL: servers check it, and so do clients given it (servers dialing their
peers too).
- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't
BakaShrot doesn't get past the TLS handshake. It isn't versioned.
- **The versions, first:** right after TLS, each end sends its protocol
version, 4 bytes little-endian (`frame::write_version()`), and reads the
other's (`frame::check_version()`). Different versions: both ends
abandon the connection (the client's error is `VersionMismatch`). This
comes before any frame, so it holds whatever later versions change.
- **The server speaks next:** a `Welcome`, saying who the connection is.
Then the client sends requests. A certificate none of whose roles the
server has gets a `RequestRefused` (`NotAllowed`) instead, then the
connection closes.
- **Frames:** every packet is one frame, its size as a 4-byte
little-endian unsigned integer, then the packet (`frame`). A size of 0,
or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it
arrived. The blocking client reads and writes them with `frame::read()`
/ `write()`, the async server with `frame::codec()` (`tokio-util`).
## Packets
A packet is **a MessagePack array of two: its type, then its fields as an
array**, `[type, [field, ...]]`. A struct inside is an array of its fields,
an optional value nil or itself, bytes a binary. The structs in
`crates/bakashrot-proto/src/packets/` are the format: `serde` derives it
(`rmp-serde`'s compact form). Any MessagePack library reads it. For
example `PushMessage { topic: "logs", data: "{}", attachment: None }`:
```
92 array of 2
04 type 4, PushMessage
93 its 3 fields
a4 6c 6f 67 73 "logs"
a2 7b 7d "{}"
c0 nil: no attachment
```
**Decoding checks everything** (`Packet::decode`): the types and number
of fields, each packet's rules (ranges, names, ids in order), and that
nothing follows. Anything wrong is a `DecodeError`: the connection is
aborted. (A struct given as a map of its field names is taken too, a
leniency of `serde`'s derive: nothing writes it, it isn't part of the
format, its values are checked all the same.)
### Values
- **Topics and nodes are names**, everywhere: 1-64 of `A-Z a-z 0-9 _ . -`,
not only digits, compared without case (`names`). A name that isn't one
is malformed (the client libraries check before sending); one the server
doesn't have is refused (`UnknownName`). Ids are each server's own, in
its database, never on the wire.
- **Patterns** (in a `SyncState`): names with `*` (any characters, none
included) and `?` (one).
- **Message ids:** 1 to 2^43 - 1 (`MAX_MESSAGE_ID`), in their topic/node
pair: what a server stores (`storage.md`, "Keys").
- **Times:** milliseconds since 1970-01-01 00:00:00 UTC, 1 to
9999-12-31 23:59:59.999 (`MAX_TIMESTAMP`). Stamped by the server a
message is pushed to, kept by replication.
- **Attachments:** `[size, sha256]`, 1 B to 1 TiB, sent in parts of
1 MiB (`ATTACHMENT_PART_SIZE`), the last one what's left.
### Types
Direction: **C** client, **S** server, **P** peer (a server linked to
another, as its client). Ids are protocol 7's own (6 can't connect); a new
packet takes the next one, none is ever reused.
| Id | Packet | Dir | Fields | Answered by |
|---|---|---|---|---|
| 1 | Welcome | S→C, S→P | `server` name, `node` name (the connection's, from its certificate) | |
| 2 | RequestRefused | S→C, S→P | `code` 1-99 (`error`), `reason` str | |
| 3 | Continue | S→C, S→P | none: send the attachment's parts | |
| 4 | PushMessage | C→S | `topic` name, `data` str (up to `MAX_MESSAGE_SIZE` bytes), `attachment` or nil | MessagePushed / RequestRefused; with an attachment, Continue first |
| 5 | MessagePushed | S→C, S→P | `message_id` | |
| 6 | GetMessages | C→S | `topic`, `node`, `after` (an id, 0 for all) or nil (the last ones), `limit` 1-10000 | Messages / RequestRefused |
| 7 | Messages | S→C | `more` bool, `[[id, pushed_at, data, [size, ready] or nil]...]` (ids strictly increasing, 10000 at most) | |
| 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused |
| 9 | Attachment | S→C | `size`, `sha256` | |
| 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | |
| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes) | NamesList |
| 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | |
| 13 | Query | C→S | `sql` str | QueryResult / RequestRefused |
| 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | |
| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused |
| 16 | SyncState | S→P | `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]`, `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most) | |
| 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused |
| 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused |
## Flows
```
Pushing C: PushMessage S: MessagePushed / RequestRefused
with an C: PushMessage(attachment) S: Continue / RequestRefused
attachment C: AttachmentPart x every part S: MessagePushed / RequestRefused (DataMismatch)
Reading C: GetMessages(after: id) S: Messages, `more` if others follow
the latest C: GetMessages(after: nil, 1) S: Messages (empty if none)
An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest
/ RequestRefused (NotFound, NotReady)
Replicating P: SyncStateRequest S: SyncState
P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
P: ReplicateAttachment x missing S: Continue / RequestRefused
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused
```
- **Parts are streamed:** no request or answer per part, TCP paces them.
A part's index follows from the order, its exact size from the
attachment's size (`Attachment::part_len()`); the receiver checks both,
and the SHA-256 once all came.
- **Once the server said `Continue`**, it reads every part even if storing
them failed, then refuses: the client never has to read while sending.
- **A server failing while it sends parts** closes the connection; the
client asks again `from_part` the next one it needs.
- **Replication:** `SyncState` is all a check-in needs. The peer compares
it with what it has, by name, sends the messages the server lacks in
batches of up to `batch_size` messages and about 1 MiB (a bigger
message alone), then the attachments it listed.
## Rules
The same as protocol 6:
- **One request at a time:** a client sends one, waits for its answer (the
parts of an attachment being part of its request or answer).
- **Refuse or abort:** valid but not allowed or not found (permissions,
unknown names, over a limit, a failed query) is a `RequestRefused` with a
code, the connection stays. Malformed or out of order (a bad frame, a
`DecodeError`, an unexpected packet) aborts it. Clients apply the same
to answers.
- **The identity is the connection's:** requests never say who sends them.
A push picks its topic, never its node.
- **Error codes** (`error`): 1-99 refusals, 100+ the client's own; the
numbers of protocol 6, never renumbered.
## What changed from protocol 6
- **TLS** instead of the sealed Hello, the signed key exchange and the own
cipher: the handshake packets are gone, `Welcome` is new, the identity
comes from the certificate.
- **The version is checked once**, sent by both ends before anything else:
packets lost their magic and version.
- **Names only:** no ids on the wire, no refs. `ResolveName` /
`NameResolved` are gone, answers don't echo ids, `NamesList` is names,
`SyncState` gives its heads by name.
- **No default topic:** a push always names its topic, `Welcome` doesn't
give one (`NoDefaultTopic`, 6, is never sent).
- **Fewer packets, 26 → 18:** `GetMessages` with `after: nil` replaces
`GetLatestMessage`, `Messages` replaces `LatestMessage`; `SyncState`
lists the missing attachments (no `MissingAttachmentsRequest` /
`MissingAttachments`); answers don't echo what was asked.
- **Attachments are streamed in their request:** no upload ids, no uploads
waiting for their push (and no `UploadTimeout`), no request or answer per
part (`UploadStart`, `UploadStarted`, `UploadChunk`, `ChunkStored`,
`AttachmentChunk`, `ReplicateAttachmentChunk` are gone). An upload cut
short starts over (none resumed in protocol 6 either); reads and
replication go on `from_part`.
- **Encoding:** derived with `serde`, `[type, [fields...]]`, booleans and
nil where they belong (were 0/1 and empty values). Nothing may follow a
packet (was ignored).
- **No 4 KB limit before authentication:** TLS has authenticated both ends
before any frame.
+369
View File
@@ -0,0 +1,369 @@
# The server and the client
`crates/bakashrot-server` (a library and the `bakashrot-server` program)
and `crates/bakashrot-client` (the blocking client library the C DLL will
wrap). Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over
the wire: `protocol.md`.
**Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their
attachments, messages, attachments, names, queries, retention,
replication, stopping cleanly. Every request of protocol 7 is answered.
## Running
```
bakashrot-server server.toml
```
The config (`config.md`) gives where to listen, the certificates, the CRL,
the database, the topics and the roles. Decided 2026-11-14
(`../revamp.md`, "Operations"):
- **Stopping:** SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its
console closed on Windows. It stops taking connections and writes
what was queued for the database (`Server::stop`): every push
answered is stored, the ones after are refused (`ServerError`, "the
server is stopping"), then it exits with 0. Nothing else to wait for:
a client whose push wasn't answered pushes it again (at least once).
- **No console commands** (the old `quit`, `restart`, `vacuum`, `names`,
`help`): it needs no console, a service manager runs it as is. `names`
is `bakashrot list`, `restart` a stop and a start. Maybe an admin
channel later.
- **Logs go to the console** (stdout, `tracing`), without colours when
it isn't a terminal: redirect them, or let systemd or Docker keep
them. `BAKASHROT_LOG` sets the level: `error`, `warn`, `info` (the
default), `debug`, `trace`.
- **No Windows service mode:** a tool like NSSM runs it as one, stopping
it with Ctrl+C.
A systemd unit, for example:
```ini
[Service]
ExecStart=/opt/bakashrot/bakashrot-server /etc/bakashrot/server.toml
User=bakashrot
Restart=on-failure
# SIGTERM, then 90 s at most: far more than a stop takes.
```
### In Docker
`docker/Dockerfile` (its comments have the details), the image
`ghcr.io/aziascreations/bakashrot-server` (amd64 and arm64, pushed by CI
on a version tag): the server, with `bakashrot` and `bakashrot-cert`
beside it, on `debian:trixie-slim`, as uid 10001.
- **The config** in `/etc/bakashrot`, read-only: `server.toml`, the
certificates, the server's key (readable by uid 10001: `chown 10001`
it, `bakashrot-cert` writes keys for their owner only). `listen =
"0.0.0.0:7000"`: 127.0.0.1 isn't reachable from outside.
- **The database** in `/var/lib/bakashrot`, a volume: `database =
"/var/lib/bakashrot/bakashrot.sqlite"`.
- **Running it:** `docker/compose.yml` (`docker compose up -d` from
`docker/`, the config in `docker/config/`), or `docker run -d -p
7000:7000 -v ./config:/etc/bakashrot:ro -v
bakashrot-data:/var/lib/bakashrot <image>`. `docker stop` is SIGTERM:
a clean stop. The logs: `docker logs`.
- **The tools:** `docker run --rm <image> bakashrot-cert ...`.
- **Checked** by `docker/test.sh <image>` (CI runs it on both before
pushing): certificates by the image's tool, its server, a push read
back over a Docker network, `docker stop` ending it cleanly.
## Inside the server
| What | Where | How |
|---|---|---|
| Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time |
| Writes | one writer thread | a queue of every write (pushes, uploads and their parts, replicated messages and parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups |
| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused |
| WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) |
| The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays |
| Retention | a task, at start then every `retention_interval` (1 min) | below |
| Replication | a task per server of `push_to` | below: links kept up, a check-in every `sync_interval` (5 s) |
## Retention
`[retention]` (`config.md`) says how long each topic's messages are kept.
At start, then every `retention_interval`, the server goes through every
topic in its database (one no longer in `topics` too) and deletes the
messages pushed before now minus its age, 10,000 per write, so pushes go
on between them. Then the parts of their attachments, 64 MB per write.
Each topic's count is logged ("deleted 3 messages of topic 'logs'").
- **In id order** (`storage.md`, "Retention"): a message stamped earlier
than the one before it (a clock set back) waits for that one.
- **Ids go on:** a stream's last id stays, the next push takes the next.
- **"May be" deleted past its age:** up to `retention_interval` later.
- **Each server its own:** a peer's ages are its own. What a peer sends
already past this server's age isn't stored, but counts as received:
it isn't sent again.
## Replication
Decided in `../revamp.md` ("Replication by address", 2026-11-14).
Each server's config says who it replicates with, by address
(`config.md`, "Peers"): `push_to`, the servers it dials and sends to;
`accept_from`, the servers whose messages it takes (`"*"` for all). A link
carries messages one way, from the server that dials to the one dialed;
the other way is the other server's own `push_to`.
**Sending** (`push_to.rs`): a link to each server of `push_to`, as a
client with this server's certificate; a failed or dropped one is dialed
again after `retry_delay` (10 s), its failure logged once until it
changes. It checks in from the start, then again at once if it sent
something (so it keeps up under load), after `sync_interval` (5 s)
otherwise:
1. `SyncStateRequest`: the other server answers what it takes from this
one (topics and nodes, patterns included), its last id in each topic
and node, and the attachments it lacks (256 at most).
2. **The messages:** for each topic and node here that it takes and that
its roles here may be sent (`send_topics`, `send_nodes`,
`replicated_topics`), and where it's behind, the messages after its
last id, `batch_size` (1000) at a time and about 1 MiB at most (a
bigger one alone), each batch answered before the next. A refusal
leaves that topic and node for the next check-in.
3. **The attachments it lacks:** those this server has ready, from the
part it needs. One it says doesn't match its SHA-256 is read back
here: damaged (a disk, a bug), this server's copy is dropped and asked
for again from its own peers (`replicating`, not served meanwhile),
instead of sent again at every check-in (the old open item 3).
**Receiving** (`accept_from.rs`): replication requests are answered only
if the connection comes from `accept_from` (a hostname looked up at its
first request, `NotAllowed` otherwise), and only for what its roles'
`accept_topics` / `accept_nodes` allow (`NotAllowed`). Messages keep
their ids and `pushed_at`; ones already here are kept as they are; one
past this server's age is only counted. An attachment comes after its
message (`replicating`, `NotReady` to readers), from the part this server
needs, the parts it had read back for the SHA-256; matching, it's ready,
otherwise started over (`DataMismatch`). A stop between its last part
and the check: started over at the next start.
**One server per node** stays the config's rule, as in the old version
(`known-issues.md`): a node pushing to two servers that replicate makes
the same ids with different messages, undetected.
## A connection
1. **TLS:** the client's certificate must be the CA's, valid, not revoked,
with an identity (`certificates.md`). A refused one gets TLS's alert,
then a gentle close: the server shuts down and reads until the client
closes (1 s at most). Closing at once reset the connection (the
client's version bytes unread), which could beat the alert to the
client: `ConnectionLost` instead of `AuthRejected`, about 1 in 10 under
load on Windows.
2. **The versions:** each end sends its own; different ones, the
connection is dropped (the client says `VersionMismatch`).
3. **The roles:** none of the certificate's roles in the config, the
server answers `RequestRefused` (`NotAllowed`, saying which roles) and
closes; otherwise `Welcome` (the server's name, the client's node).
4. **Requests**, one at a time. Before each, the certificate is checked
against the current CRL: revoked since, the connection is dropped.
| Timeout | |
|---|---|
| TLS, versions, welcome | 10 s (the server); the client's connect too |
| Silence between requests | 5 min, then the server closes |
| An answer | 30 s (the client) |
| An attachment's next part | 30 s (the server), then it closes |
## Requests so far
- **`PushMessage`:** the topic must be one of the config's (`UnknownName`),
the roles must allow pushing to it (`NotAllowed`), the message at most
`MAX_MESSAGE_SIZE` (`TooBig`); stored under the client's node, stamped
with the server's time; answered `MessagePushed` once committed.
- **With an attachment:** also at most the config's `max_attachment_size`
(`TooBig`; 0 takes none). The server answers `Continue`, then reads
every part: each written while the next come (4 at most waiting for the
writer, so the client waits through TCP rather than the server holding
them), the SHA-256 computed as they come. All there and matching, the
message is stored with it, ready, in one transaction. A part of the
wrong size (`InvalidRequest`), a wrong SHA-256 (`DataMismatch`), a
failed write: refused once every part came, the connection kept. A
connection that closes, or sends anything else than the next part, is
dropped. Not pushed, the upload goes (`storage.md`, "Attachments").
- **`GetAttachment`:** the roles must allow reading the topic
(`NotAllowed`), the topic must be one of the config's (`UnknownName`).
A message without one, or none of that id: `NotFound`; one still on its
way from a peer: `NotReady`; one this server doesn't keep: `TooBig`.
Then `Attachment` (its size, its SHA-256) and the parts from
`from_part`. A part that can't be read closes the connection.
- **`GetMessages`:** the roles must allow reading the topic
(`NotAllowed`), the topic must be one of the config's and the node one
with messages in any topic, or the client's own (`UnknownName`); a known
topic and node without messages answer none. At most `limit` messages and about 1 MB
(`MESSAGES_BYTES`, a bigger message alone), `more` if others follow.
- **`ListNames`:** topics are the config's, those the roles may push to or
read (every one with `query`, which reads them all anyway); nodes are
every one with messages. `truncated` past 65,536.
- **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL,
refused with SQLite's message (`QueryFailed`, with a hint to add
`is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB
(`TooBig`), never a partial result (`storage.md`, "The query surface").
- **Sizes:** frames up to 16 MB (`MAX_PACKET_SIZE`), a bigger one drops the
connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the
server refusing bigger ones (`TooBig`); the client refuses messages and
queries over it before sending (`InvalidArgument`).
## The client
`Client::connect(address, settings)` (`host:port`, the CA's certificate,
the client's certificate and key, the CRL if any), then `push(topic,
data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`,
`query(sql)`. Blocking, no runtime. The DLL and the bindings over it:
`client.md`.
Attachments: `push_with_attachment(topic, data, source)`, the source any
`Read + Seek` (a `File`, a `Cursor`), read twice: its SHA-256, then its
parts; `get_attachment(topic, node, id, out)` into any `Write`, checked
with its SHA-256 once all came; `save_attachment(topic, node, id, path)`,
written to `path` and `.download` then moved over `path`, so a failed one
leaves no file. A source or a part that fails half-way closes the
connection (the server can't be told to stop); a failing `out` doesn't
(the rest is read, then `FileError`).
Its errors are the protocol's codes: a server's refusal keeps its own
(1-99), the client's are 100 and up (`ConnectFailed`, `AuthRejected` when
the server refused its certificate, `ServerNotVerified` when it refused the
server's, `ConnectionLost`, `ProtocolError`, `InvalidArgument`,
`FileError`, `AttachmentMismatch`, `VersionMismatch`).
## Measured
`push_rate` (`tests/end_to_end.rs`, ignored by default): a whole server on
localhost, 10 clients each its own node (`CLIENTS`), one push at a time
each, 200-byte JSON, 20,000 pushes per client.
| `synchronous` | 10 clients | Slowest push | 1 client |
|---|---|---|---|
| `normal` | 40,400/s | 37 ms | 14,200/s |
| `full` | 9,229/s | 9 ms | 1,920/s |
- With `normal`, the server reaches the storage's own ceiling (about 37k/s
alone, `storage.md`, a slightly different load). Up from 36,000/s once
a connection's revocation check stopped reading its certificate at
every request (its serial is read once, at connect).
- One client waits for each answer: a round trip and a commit per push.
Through Python and the DLL, about 10,700 pushes/s (the old module did
about 9,000), and 140,000 messages/s read.
- With `full`, every group commit waits for the disk's flush (about 1 ms
here): 10 clients make groups of about 10. More clients, bigger groups.
- **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and
down in 0.5 s, the tool's start and the client's hashing included.
- **Built for size** (`opt-level = "s"`, 2026-11-14; the numbers here
were measured before, at 3): `normal` about 5% lower (36,900-38,100/s
against 39,800-40,400), `full` the same (the disk's), attachments and
tool commands the same. The programs and the DLL 25-31% smaller.
### Against the old server (2026-11-14)
The same work on the same machine, release builds, one server on
localhost: the old one (`OldSource/Build/Bench/BenchServer.exe`, its DLL,
`bakashrot.py` and tools) and this one. Pushes and reads through each one's
Python module and DLL (10 clients: 10 processes, the same node), 200-byte
JSON; the rest through the tools.
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` |
|---|---|---|---|---|
| One tool command, connecting included | 8 ms | 12 ms | 8 ms | 11 ms |
| Pushes, 1 client | 1,945/s | 1,954/s | 9,386/s | 11,600-13,100/s |
| Pushes, 10 clients | 9,006/s | 10,072/s | 25,419/s | 56,200-64,300/s |
| Reads, Python | 76,466/s | 130,861/s | 77,526/s | 146,368/s |
| The tool writing 120,000 messages to a file | | | 45.5 s | 0.14 s |
| A 200 MB attachment up, the tool | 3.49 s | 1.15 s | 2.84 s | 1.15 s |
| The same down | 1.57 s | 0.59 s | 1.62 s | 0.67 s |
- **`full`, one client:** both wait for the disk's flush at every push.
- **A command:** the TLS handshake's P-384 signatures and checks, both
ends, cost about 7 ms against the old handshake's X25519; aws-lc's CPU
Jitter Entropy seeding cost 25 ms more per process before it was turned
off (`certificates.md`, "TLS").
- **The old tool's read** printed a line at a time to the console API.
### Replication, against the old server (2026-11-14)
`replication_rate` (`tests/end_to_end.rs`, ignored by default) against
the old `Tests/Bench/Bench-Replication.ps1 -Parts Ramp -Ramp 10x0`: 4
servers in a Y (a hub sending to 3 leaves, each sending to the hub), 10
nodes pushing to each as fast as they're answered for 30 s, 200-byte
JSON, the same machine. The old one's pushers are its PureBasic bench
client, the new one's `bakashrot-client` threads in the test's process.
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` |
|---|---|---|---|---|
| Pushes, all 4 servers | 16,638/s | 16,000-16,300/s | 33,895/s | 35,300-37,500/s |
| Slowest push | 134 ms | 50-57 ms | 854 ms | 420-510 ms |
| Behind when the pushes stop (most of a server) | 9.0 s of pushes | 0 | 11.4 s | 0.3-0.9 s |
| Until every server has everything | 8.8 s | 0.3 s | 14.8 s | 5.3-5.6 s |
- **Keeping up:** a link checks in again at once after sending; before
it waited `sync_interval` after every check-in, as the old one did, and
pushes went faster (19,300/s `full`, 40,200/s `normal`) while the
leaves fell 7-9 s behind and took 10-20 s to catch up.
- **`batch_size` 1000** (was 100, the old `PeerBatchSize`): `normal` went
from 27,500-31,500/s to 35,300-37,500/s, and from 2-2.5 s to under 1 s
behind. Batches stay about 1 MiB at most.
- **The last few seconds** with `normal` are a link's `sync_interval`:
idle once caught up, it looks again 5 s later.
## Tests
`crates/bakashrot-server/tests/end_to_end.rs`, a server on a free port
each:
- pushes and reads back (ids, data, times, another connection);
- runs of messages (`OldSource/Tests/GetMessages-Test.ps1`, the server's
part): from the start, after an id, with a limit, `more`, the last ones,
nothing yet, unknown topics and nodes, names without case, data that
isn't one line of JSON;
- big messages (`BigMessages-Test.ps1`, one server's part): five of 600 KB
and one of the largest size, one per answer, read back whole; one byte
over refused; a query result over 16 MB refused;
- names: topics by role, nodes;
- attachments (`Attachments-Test.ps1`, one server's part): 100 KB, 5 MB +
123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the
messages saying theirs; none, or no such message, refused leaving no
file; another reader, one not allowed; over the server's limit, 0 for
none, empty; the parts stored;
- attachment edges (`AttachmentEdges-Test.ps1`'s, through the client and
a raw connection): a source changed between its SHA-256 and its
sending, one failing half-way (the connection closed, the upload
dropped), a part of the wrong size, a wrong SHA-256, reading from a
part on, something else than a part (closed, dropped);
- queries (`BigMessages-Test.ps1`'s): not allowed, results, a non-JSON row
refused with the hint, errors, writes and two statements refused;
- refusals keeping the connection (not allowed, unknown topic, a bad name
the client catches);
- certificates refused (no known role, with why; another CA's client; a
client trusting another CA; nothing listening);
- revoked certificates (an open connection dropped at its next request, a
new one refused, others going on, a bad CRL refused);
- six connections pushing at once (one id stream per node, none lost or
doubled);
- stopping cleanly: eight nodes pushing flat out, the server stopped
under them: every push answered is there after a restart, the ones
after refused as `ServerError`;
- retention (`Retention-Test.ps1`'s local part): a topic's messages and
their attachment deleted past its age, another topic kept forever, ids
going on, a younger message kept through a pass;
- replication (`Names-Test.ps1`'s replication, `Restart-Test.ps1`,
`AttachmentEdges-Test.ps1`'s corruption): three servers of one CA, a
pushing to b and c. b gets every message by name with its id, time
and data, and the attachment; c, whose `accept_from` hasn't a, gets
nothing; b's own pushes don't go to a. b stopped, a pushes meanwhile
and its copy of an attachment gets damaged; b started again on its
database and address: a links again, sends what b lacks, ids go on;
b refuses the damaged copy, a finds it damaged and asks for it again;
- replication edges (the test as the peer, a raw connection): what
`SyncState` says, ids and last ids kept, a message past its age only
counted, an attachment from the wrong part refused, one cut after its
first part going on from the second (the first read back for the
SHA-256), one not matching refused and asked for from the start, a
certificate whose roles take nothing refused;
- `replication_rate`, ignored by default: the benchmark above (`SYNC`,
`NODES`, `SECONDS`, `BATCH`).
The old tests' tool parts (`--follow`, the output) are the tools' tests
(`client.md`).
+287
View File
@@ -0,0 +1,287 @@
# Storage: schema v9
The server's database: one SQLite file. The code is
`crates/bakashrot-storage`; the schema is
`crates/bakashrot-storage/src/schema_v9.sql`, made in one go. Decided in
`../revamp.md`, "Decided" (2026-11-13).
**Not compatible with v8:** a database of the old server isn't opened
(refused at start, saying so); its data isn't carried over.
## In short
- **By name outside, packed integers inside.** The rest of the code (the
server, the tools) only sees topics, nodes, message ids and times, as on
the wire. Inside, a topic and node pair is a *stream*, and a message's
key packs its stream and its id into one integer. Only this crate packs
and unpacks keys; the `messages` view shows plain columns.
- **One B-tree per kind of data:** messages, attachment parts. A push
writes its message's row and nothing else (no index): about 2.3 times
the pushes of v8's layout, 30% less disk (see "Measured").
- **One writer, many readers** (WAL). Writes go in batches, one
transaction each: a group commit.
## Streams
A **stream** is one node's messages in one topic: `logs` written by
`kitchen` is one, `logs` written by `garage` another. Everything works on
them:
- message ids count per stream, from 1;
- replication compares each stream's `last_id` (`SyncState`'s heads);
- `GetMessages` reads a range of one stream.
`streams` holds each one's id (1 to 2^20 - 1), its topic and node names
(compared without case), and `last_id`: the highest id it ever had.
Deleting messages leaves `last_id`, so ids never go back. A trigger keeps
it, for pushes and replication alike.
There are no `topics` or `nodes` tables: a topic's streams are its rows in
`streams`, the names are listed from there (`Reader::topics()`,
`nodes()`), and the config adds the topics it names.
## Keys
```
data.key = stream_id << 43 | message_id
[0][ stream: 20 bits ][ message id: 43 bits ]
attachment_parts.key = attachment_id << 20 | part
[0][ attachment: 43 bits ][ part: 20 bits ]
```
- `data.key` is the table's own key (`INTEGER PRIMARY KEY`): the messages
are stored ordered by stream, then id. A stream's messages sit together;
"after id 100", "the last 10" are ranges of keys, read in order. No
other index is written when a message is stored.
- **Limits:** 1,048,575 streams per database, message ids up to
2^43 - 1 (8,796,093,022,207) per stream: 278 years at 1,000 messages a
second. `MAX_MESSAGE_ID` (`bakashrot-proto`) is that, so the protocol
can't carry an id a server can't store. Past either, a push is refused
(`TooBig`).
- **Attachment parts** the same way: 2^20 parts of 1 MiB is exactly the
1 TiB limit, an attachment's parts are a range of keys.
- `data` also has `stream_id`, `message_id` and `is_json` as **virtual
columns**: computed when read, never stored (a test checks the schema
unpacks keys as the code does).
Why not v8's three columns with an index? A second B-tree to write at every
push, and reads going through the index then to the row. Measured below.
## Writing
`Database::writer()` gives the one connection that writes;
`Writer::batch(|batch| ...)` runs a closure in one transaction. Every
operation of a `Batch` is all or nothing on its own (a savepoint), so a
batch goes on after one fails: the server queues pushes and stores them
together, one disk flush for all.
| Operation | What |
|---|---|
| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new |
| `start_upload(size, sha256)`, `write_part(id, part, data)`, `push_with_attachment(id, ...)`, `cancel_upload(id)` | a push with an attachment: its parts first, then the message with it |
| `replicate(topic, node, messages, max_attachment_size, skip_before)` | a peer's messages, with their ids; ones already here are kept; ones pushed before `skip_before` (past their age here) only counted in `last_id` |
| `write_part`, `finish_replicated(id, matches)` | a replicated attachment's parts, then ready (or started over) |
| `damaged(id)` | a ready attachment found not matching its SHA-256: its parts dropped, asked for again (`replicating`) |
| `delete_before(topic, cutoff, limit)` | retention |
| `purge_attachments(max_parts)` | deleted messages' attachments |
| `Writer::vacuum()` (outside a batch) | the file shrunk to what it holds: the old server's `vacuum` command |
| `Checkpointer::checkpoint()` (its own connection) | the WAL copied into the database, every second, off the writer's way |
**SHA-256s are the caller's to check:** the server hashes the parts as they
stream by, nothing is read back from the disk. A resumed replicated
attachment's first parts are read back (`Reader::read_part`) to finish its
hash.
## Reading
`Database::reader()` gives a connection that reads, as many as needed; they
read while the writer writes. Answers are the protocol's own types:
| Reader | Gives | How |
|---|---|---|
| `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys |
| `topics()`, `nodes()` | the names with messages | `streams` |
| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` |
| `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys |
| `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) |
| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key |
A topic and node with no messages read as none, unless the node has none
in any topic: `Error::UnknownName`, as the old server refused unknown
nodes. Whether a topic is known is the server's (the config's topics).
## Attachments
One table, a state each:
| State | Meaning | Next |
|---|---|---|
| `uploading` | a push's attachment, parts coming, no message yet (`message_key` NULL) | all parts and the SHA-256 match: the message is stored and the attachment `ready`, one transaction. Cut short: deleted with its parts (and every one left at start) |
| `replicating` | its message came from a peer with its size and SHA-256; parts come after | asked from part `received / 1 MiB` on; all came and match: `ready`, else started over (also at start, all came but not checked) |
| `ready` | all here, checked | readable |
| `too_big` | bigger than this server's `max_attachment_size` | never asked for; its message is kept |
| `deleting` | its message was deleted (a trigger) | parts deleted in batches, then the row |
Readers never see a message whose pushed attachment is missing: the
message is only stored with its complete attachment. A replicated message
can be here before its attachment: `Messages` says `ready: false`.
## Retention
`delete_before(topic, cutoff, limit)` reads each of the topic's streams from
its oldest message and stops at the first it keeps: only what it deletes is
read, nothing indexes `pushed_at`. So messages go **in id order**: one
stamped earlier than the one before it (a server's clock set back) waits for
that one. `last_id` stays. The parts of deleted messages' attachments go
afterwards, `purge_attachments(max_parts)` a batch at a time.
## The query surface
Clients' `Query` runs on `Database::query_runner()`, read-only three ways:
the connection is `query_only`, the statement must be one SQLite says only
reads, and one statement only (more is refused, not ignored). The result is
`{"columns":[...],"rows":[[...]]}`, every value a string or null (blobs in
hex), 10,000 rows and 16 MB at most (`TooBig`). A failing row fails it all,
with SQLite's message: never a partial result. "malformed JSON" (a JSON
function on a row that isn't) gets the old server's hint: add
`is_json = 1` to the WHERE.
The `messages` view, by name:
| Column | |
|---|---|
| `topic`, `node` | names |
| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | as in v8 |
| `attachment_size`, `attachment_state` | NULL without one |
```sql
SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_json = 1
```
- **By topic, or topic and node:** ranges of the table, read in order (a
test checks the plans).
- **Filters on `pushed_at` or `message_id`** read the streams they're in,
whole: a millisecond or two for 10,000 messages per stream, growing with
them (see "Measured"). If that gets slow, a time index is one migration
away ("For later").
- `browse` / `browse_messages`: v8's, for database tools (set `browse`'s
one row, open the view); no dropdowns any more.
## The file
- `PRAGMA application_id` = "BSHT": a BakaShrot database.
- `metadata`: `schema_version` (9), `created_at`, `created_by` (this crate
and its version).
- **Opening** (`Database::open`): an empty file is made a v9 database; a
v9 one is opened; an older one is migrated, a version at a time, each
step one transaction that also sets `schema_version` (none yet); a newer
one, the old server's, or another program's is refused, saying which.
- Every connection: WAL, `synchronous` from the config (`full`: every
commit flushed; `normal`: about once a second), a 5 s busy timeout. No
foreign keys: one writer keeps the tables consistent, `CHECK`s keep the
values valid.
- SQLite is compiled in (`rusqlite`'s `bundled`): the same version
everywhere, no system library.
## Measured
Python's `sqlite3` (SQLite 3.50), 5,000,000 small JSON messages pushed to
500 streams (100 topics x 5 nodes) at random, 100 per transaction, WAL,
`synchronous = NORMAL`, 16 MB page cache:
| | v9 (this) | v9 + a time index | the first draft (v8's layout) |
|---|---|---|---|
| Pushes/s | **23k** | 9-10k | 9k |
| File | **330 MB** | 457 MB | 484 MB |
| Latest 100 of a stream | 0.05 ms | 0.05 ms | 0.19 ms |
| 1000 after an id | 0.53 ms | 0.53 ms | 3.04 ms |
| Retention, 10% of a topic | 5.5 ms | 6.4 ms | 241 ms |
| Query: a node's last hour | 1.65 ms | 0.90 ms | 3.29 ms |
| Query: a topic's last hour | 8.4 ms | 4.7 ms | 16.0 ms |
- A push dirties its stream's page: with pushes spread over many streams,
each costs about a page written to the WAL. Any index per stream (v8's,
a time index) doubles that, and a bigger cache doesn't help (it's writes,
not reads).
- Bigger batches over fewer streams share pages: the server's group commit
helps most when many pushes come at once.
### Against the old storage (2026-11-13)
The same workload on both, each storage layer alone (no network): pushes
over 500 streams picked at random, 100 per transaction, 200-byte JSON;
2000 latest-message reads; 500 reads of 1000 messages after a stream's
middle id; retention of 10% of one topic. The new side is
`compare_with_old` (`tests/storage.rs`, ignored by default:
`PUSHES=1000000 SYNC=normal cargo test --release -p bakashrot-storage --
--ignored --nocapture`). The old side calls `OldSource`'s writer
(`BakaShrot_Writer_WriteJobs()`, its group commit, PureBasic 5.73, SQLite
3.54.1 from `sqlite3.dll`), from a program built outside `OldSource`.
Same machine, NVMe, one run each.
| | Old, 1M | New, 1M | Old, 1M `full` | New, 1M `full` | Old, 5M | New, 5M |
|---|---|---|---|---|---|---|
| Pushes/s, first | **25,874** | 13,803 | **19,976** | 13,205 | **19,558** | 12,184 |
| Pushes/s, step 5's writer | 25,874 | **37,332** | 19,976 | **29,952** | 19,558 | **29,363** |
| File | 276 MB | 249 MB | 276 MB | 249 MB | 1,380 MB | 1,239 MB |
| Latest message | 0.013 ms | 0.017 ms | 0.013 ms | 0.017 ms | 0.014 ms | 0.017 ms |
| 1000 after an id | 4.26 ms | **0.43 ms** | 4.28 ms | **0.43 ms** | 4.32 ms | **0.45 ms** |
| Retention, 10% of a topic | 20 ms | **7 ms** | 23 ms | **9 ms** | 98 ms | **8 ms** |
`normal` unless said. At first, the old writer pushed faster, from code the
new one didn't have, not from the schema; step 5 brought two of them over
(the second row, about 1.5 times the old):
- **checkpoints off the push path:** `Database::checkpointer()`, every
second on its own connection (the server's thread), the writer only
checkpointing itself past 10,000 pages (`WRITER_CHECKPOINT_PAGES`,
SQLite's default is 1,000): 13.8k to 34.7k pushes/s;
- **no savepoint around a push** (a failed one leaves at most its empty
stream): 37.3k;
- **next ids in memory**, left out: an indexed read of the stream's row per
push, not where the time goes.
The new layout reads ranges 10 times faster, deletes faster (and keeps
doing so as the database grows), loses less push speed from 1M to 5M (-12%
against -24%), and makes a file 10% smaller with 200-byte messages (30%
with 45-byte ones: its saving is the indexes, a fixed cost per message).
## Tests
`crates/bakashrot-storage/tests/storage.rs`, on database files in
`target/`: opening (made, reopened, an empty file), refused databases
(another program's, v8, a newer version, no version), pushes and reads
(ids per stream, names without case, after/latest/limit/more, the 1 MiB
cut), uploads (parts in order and of their size, incomplete refused, a
failed operation not spoiling its batch, cancelled and left-over ones
deleted), replication (own ids, kept ones, attachments to ask for, too big,
started over, resumed), retention (limits, id order, heads kept, ids going
on, attachments purged in batches), vacuum (the file shrinks, ids go on),
the limits (no stream, no id left, the highest key), queries (results, every write refused, failing rows, too
big), the view's plans, and readers with two writers at once. In
`src/lib.rs`: the keys, the schema unpacking them the same, the states.
## For later
- **A time index**, if time queries over big streams get slow: a v10
migration adding an index on `(stream_id, pushed_at)` and joining the
view on it too (measured above: twice the write cost).
- **Interrupting long queries** (a time limit): the server's, with
SQLite's interrupt.
- **Attachments as files** next to the database instead of in it, if their
size calls for it.
## What changed from v8
| v8 | v9 |
|---|---|
| `data(topic_id, node_id, message_id, ...)` + 3 indexes | `data(key, pushed_at, message_data)`, no index |
| `topics`, `nodes` with ids and origins | names in `streams` |
| `node_heads` | `streams.last_id` |
| `attachments` + `blobs` (two sets of states), `blob_chunks` | `attachments` (five states), `attachment_parts` |
| uploads waiting for their message, `UploadTimeout` | uploads inside their push |
| `is_json` stored | computed when read |
| no version in the file | `metadata` with `schema_version`; `application_id` |
| foreign keys declared, not checked | none, `CHECK`s |