mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Merge pull request #4 from aziascreations/dev-improvements
Dev improvements
This commit is contained in:
@@ -5,16 +5,11 @@ from authenticated clients, store them in SQLite, and replicate them
|
||||
between peers by name. Clients: a C DLL, CLI tools, a Python module. An
|
||||
**internal tool on trusted machines**.
|
||||
|
||||
**Rewritten in Rust** (since 2026-11-13):
|
||||
|
||||
- `revamp.md`: why, what's decided, what's proposed and open, the plan and
|
||||
its status. Read it first.
|
||||
- `revamp.md`: what's decided, what's proposed and open, the plan and its
|
||||
status. Read it first.
|
||||
- The implementation is the Cargo workspace at the root (`readme.md`:
|
||||
layout, scripts, conventions; `docs/`: designs, `protocol.md` first,
|
||||
`known-issues.md` for what's left).
|
||||
- The old PureBasic implementation was removed on 2026-11-15: it's in git
|
||||
history, `OldSource/` up to commit `68966a8`. Paths starting with
|
||||
`OldSource/` in the code and docs point there.
|
||||
|
||||
## Toolchain
|
||||
|
||||
@@ -24,13 +19,13 @@ between peers by name. Clients: a C DLL, CLI tools, a Python module. An
|
||||
(`rust-toolchain.toml`, 1.100.0, MSVC; Visual Studio 18 has the
|
||||
linker).
|
||||
- `test.ps1` runs what CI runs; it must pass before a step is done
|
||||
(`build.ps1`, `release.ps1`, `clean.ps1` beside it, see `readme.md`).
|
||||
(`build.ps1`, `release.ps1`, `clean.ps1`, `bench.ps1` beside it, see `readme.md`).
|
||||
Run them by absolute path (`-File <repo>\test.ps1`): a relative one
|
||||
fails when the shell's folder differs.
|
||||
|
||||
## Working rules
|
||||
|
||||
- **Commit only when the owner asks**, on a branch (`revamp`), not `master`.
|
||||
- **Commit only when the owner asks**, on a branch, not `master`.
|
||||
- **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its
|
||||
tests pass and its docs are updated, then its status goes in the table.
|
||||
- **Decisions go in `revamp.md`**: moved to "Decided" only when the owner
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Runs the benchmarks, release mode: the tests ignored by default.
|
||||
# push pushes through one server, 10 clients (end_to_end.rs, push_rate)
|
||||
# replication 4 servers in a Y, pushed to flat out (end_to_end.rs, replication_rate)
|
||||
# storage the storage alone, pushes then reads (storage.rs, storage_rate)
|
||||
# docs/server.md and docs/storage.md have the numbers measured so far.
|
||||
# Usage: powershell -ExecutionPolicy Bypass -File bench.ps1 [-Only push,replication,storage] [-Sync full|normal]
|
||||
# -Sync sets SQLite's synchronous for all of them (otherwise each one's
|
||||
# default: full for push and replication, normal for storage). The tests'
|
||||
# other variables are taken from the environment as they are: PUSHES and
|
||||
# CLIENTS (push), NODES, SECONDS and BATCH (replication), PUSHES (storage).
|
||||
param(
|
||||
[ValidateSet("push", "replication", "storage")]
|
||||
[string[]]$Only = @("push", "replication", "storage"),
|
||||
[ValidateSet("full", "normal")]
|
||||
[string]$Sync
|
||||
)
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# rustup's folder isn't always on the PATH (it isn't in every shell here).
|
||||
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
|
||||
$env:PATH = (Join-Path $env:USERPROFILE ".cargo\bin") + [IO.Path]::PathSeparator + $env:PATH
|
||||
}
|
||||
|
||||
# What -Only names, in this order: the package, the test file, the test.
|
||||
$benches = [ordered]@{
|
||||
push = @("bakashrot-server", "end_to_end", "push_rate")
|
||||
replication = @("bakashrot-server", "end_to_end", "replication_rate")
|
||||
storage = @("bakashrot-storage", "storage", "storage_rate")
|
||||
}
|
||||
|
||||
$oldSync = $env:SYNC
|
||||
if ($Sync) { $env:SYNC = $Sync }
|
||||
Push-Location $PSScriptRoot
|
||||
try {
|
||||
foreach ($name in $benches.Keys) {
|
||||
if ($Only -notcontains $name) { continue }
|
||||
$package, $file, $test = $benches[$name]
|
||||
"== $name ($test)"
|
||||
cargo test --locked --release -p $package --test $file $test -- --ignored --exact --nocapture
|
||||
if ($LASTEXITCODE -ne 0) { "FAILED: $name"; exit 1 }
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
$env:SYNC = $oldSync
|
||||
}
|
||||
"Benchmarks done"
|
||||
exit 0
|
||||
@@ -70,8 +70,8 @@ ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key);
|
||||
|
||||
/**
|
||||
* Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
|
||||
* or the path of a file holding it; null or empty for none. Before
|
||||
* connecting.
|
||||
* or the path of a file holding it (one that isn't there is a
|
||||
* `FileError`); null or empty for none. Before connecting.
|
||||
*/
|
||||
ptrdiff_t BakaShrot_SetCrlA(const char *crl);
|
||||
|
||||
|
||||
@@ -34,16 +34,8 @@
|
||||
; call, BakaShrot_GetLastError() tells why: the codes and what to do about
|
||||
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below),
|
||||
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says
|
||||
; why in words.
|
||||
;
|
||||
; Changed from the PureBasic DLL (protocol 6): certificates instead of keys
|
||||
; and a node (BakaShrot_SetCaCertificate(), _SetCertificate(),
|
||||
; _SetPrivateKey() now a PEM key, _SetCrl()); a push always names its topic
|
||||
; (BakaShrot_PushMessage() is gone); no ids (_GetLatestMessage(TopicId,
|
||||
; NodeId), _SetNodeId(), _GetMessageTopicId/NodeId(), _ResolveTopic/Node(),
|
||||
; _GetResolvedName() are gone); _GetNamesList() is
|
||||
; {"kind":"topic","names":[...],"truncated":false}. New: _GetNode().
|
||||
; Attachments: the same six as before, by names.
|
||||
; why in words. _GetNamesList() is
|
||||
; {"kind":"topic","names":[...],"truncated":false}.
|
||||
; ============================================================================
|
||||
|
||||
XIncludeFile "BakaShrot_ErrorCodes.pbi"
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
;
|
||||
; What BakaShrot_GetLastError() returns after a failed call of the client DLL
|
||||
; (bakashrot.dll), and the code a server sends with each refusal (protocol 7,
|
||||
; crates/bakashrot-proto/src/error.rs, the same numbers as protocol 6).
|
||||
; crates/bakashrot-proto/src/error.rs).
|
||||
; The Python client has them in bakashrot.ErrorCode. Shipped next to
|
||||
; BakaShrot_Client_Prototypes.pbi, which includes it.
|
||||
;
|
||||
@@ -58,8 +58,6 @@
|
||||
; A message, attachment or query result over a limit, or an attachment
|
||||
; bigger than this server keeps.
|
||||
#BakaShrot_Refused_TooBig = 5
|
||||
; Protocol 6's (a push without a topic): never sent any more.
|
||||
#BakaShrot_Refused_NoDefaultTopic = 6
|
||||
; A request that doesn't fit: an attachment's parts not matching its size,
|
||||
; a part that doesn't exist...
|
||||
#BakaShrot_Refused_InvalidRequest = 7
|
||||
@@ -117,7 +115,6 @@ Procedure.s BakaShrot_ErrorName(Code.l)
|
||||
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
|
||||
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
|
||||
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
|
||||
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
|
||||
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
|
||||
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
|
||||
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
|
||||
|
||||
@@ -83,7 +83,6 @@ class ErrorCode(enum.IntEnum):
|
||||
NOT_FOUND = 3 # no such message or attachment
|
||||
NOT_READY = 4 # the attachment isn't on this server yet: retry later
|
||||
TOO_BIG = 5 # over a limit, or more than this server keeps
|
||||
NO_DEFAULT_TOPIC = 6 # protocol 6's, never sent any more
|
||||
INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...)
|
||||
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
|
||||
QUERY_FAILED = 9 # the SQL failed
|
||||
@@ -326,8 +325,8 @@ class Client:
|
||||
@classmethod
|
||||
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client":
|
||||
"""From a client.toml (server, ca, certificate, key, crl), the tools'
|
||||
too; paths in it are relative to its folder. Needs Python 3.11+
|
||||
(tomllib)."""
|
||||
too; paths in it are relative to its folder, a crl whose file isn't
|
||||
there yet is none. Needs Python 3.11+ (tomllib)."""
|
||||
import tomllib
|
||||
|
||||
try:
|
||||
@@ -351,7 +350,10 @@ class Client:
|
||||
value = get(key, required)
|
||||
return os.path.join(folder, value) if value else None
|
||||
|
||||
return cls(get("server"), file("ca"), file("certificate"), file("key"), file("crl", False), dll_path)
|
||||
# No CRL file yet: nothing revoked, as with the tools and the server.
|
||||
crl = file("crl", False)
|
||||
crl = crl if crl and os.path.exists(crl) else None
|
||||
return cls(get("server"), file("ca"), file("certificate"), file("key"), crl, dll_path)
|
||||
|
||||
# --- Connection --------------------------------------------------------
|
||||
|
||||
|
||||
@@ -227,6 +227,15 @@ check("None of its roles allowed: AuthError, NOT_ALLOWED", ok, detail)
|
||||
missing = Client(f"{kitchen.host}:{kitchen.port}", os.path.join(folder, "missing.crt"), *pem[1:], dll_path=dll_path)
|
||||
ok, detail = raises(missing.connect, BakaShrotError, "missing.crt", ErrorCode.FILE_ERROR)
|
||||
check("A certificate file that isn't there: FILE_ERROR", ok, detail)
|
||||
missing = Client(f"{kitchen.host}:{kitchen.port}", *pem, crl=os.path.join(folder, "missing.crl"), dll_path=dll_path)
|
||||
ok, detail = raises(missing.connect, BakaShrotError, "missing.crl", ErrorCode.FILE_ERROR)
|
||||
check("A CRL file given that isn't there: FILE_ERROR", ok, detail)
|
||||
with open(os.path.join(folder, "kitchen.toml")) as settings:
|
||||
no_crl_yet = settings.read() + '\ncrl = "missing.crl"\n'
|
||||
with open(os.path.join(folder, "no-crl-yet.toml"), "w") as settings:
|
||||
settings.write(no_crl_yet)
|
||||
with Client.from_file(os.path.join(folder, "no-crl-yet.toml"), dll_path) as again:
|
||||
check("A client.toml's CRL file not there yet: none, connected", again.connected, again.crl)
|
||||
with Client(f"{kitchen.host}:{kitchen.port}", *pem, dll_path=dll_path) as again:
|
||||
check("The same identity from PEM text: connected", again.connected and again.node == "kitchen", again.node)
|
||||
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# BakaShrot - Building
|
||||
|
||||
## Compilation
|
||||
Requires [rustup](https://rustup.rs) (it installs the pinned toolchain, [rust-toolchain.toml](rust-toolchain.toml),
|
||||
by itself; on Windows, Visual Studio's C++ tools for the linker) and Python 3.11+ for releases.
|
||||
|
||||
From the repository's root, on Windows (`powershell -ExecutionPolicy Bypass -File <script>`):
|
||||
|
||||
| Script | What it does |
|
||||
|---|---|
|
||||
| `build.ps1` | Builds everything, release mode, into `target\release\` |
|
||||
| `test.ps1` | What CI runs: formatting, clippy (warnings are errors), the tests, the docs |
|
||||
| `release.ps1` | A release for this platform, smoke-tested (`release.py`, below); `-SkipTest` |
|
||||
| `clean.ps1` | Deletes `target\` (builds and releases) |
|
||||
| `bench.ps1` | The benchmarks, release mode: pushes, replication, storage (`docs/server.md`, "Measured"); `-Only`, `-Sync full` or `normal` |
|
||||
|
||||
Elsewhere, the same with cargo: `cargo build --release`, `cargo test`, `python release.py`, `cargo clean`;
|
||||
the benchmarks are ignored tests (`cargo test --release -- --ignored`).
|
||||
Generated keys and certificates never go in git.
|
||||
|
||||
|
||||
## Layout
|
||||
A Cargo workspace:
|
||||
|
||||
```
|
||||
Cargo.toml the workspace: shared lints, release profile
|
||||
rust-toolchain.toml the pinned toolchain (1.100.0)
|
||||
build.ps1, test.ps1, release.ps1, clean.ps1, bench.ps1
|
||||
release.py a release for this platform: build, package, smoke test
|
||||
docs/ designs across crates: protocol.md, certificates.md, oid.md, config.md,
|
||||
storage.md, server.md, client.md, known-issues.md, lab.md (a test lab, step by step)
|
||||
crates/
|
||||
bakashrot-proto/ packets, frames, names, limits, error codes, shared by everything
|
||||
bakashrot-pki/ certificates: issuing, identities, CRLs, the TLS setup
|
||||
bakashrot-config/ the server's config (TOML): retention, replication, roles
|
||||
bakashrot-storage/ SQLite, schema v9: the writer, reads, attachments, queries
|
||||
bakashrot-server/ the server: TLS, identities, requests, the writer thread (and its program)
|
||||
bakashrot-client/ the client library, Rust API, blocking
|
||||
bakashrot-capi/ the C DLL over bakashrot-client: the BakaShrot_* exports (bakashrot.dll)
|
||||
bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert
|
||||
bindings/
|
||||
c/ bakashrot.h, generated from bakashrot-capi
|
||||
purebasic/ the prototypes and error codes
|
||||
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py
|
||||
.cargo/config.toml the C runtime linked statically on Windows
|
||||
docker/ the server's image: Dockerfile, compose.yml, test.sh
|
||||
```
|
||||
|
||||
Dependencies only point downward: `proto`, `pki`, `config` and `storage` don't open sockets and are tested
|
||||
on their own; `server` and `client` use them; the DLL and the tools only use `client`.
|
||||
|
||||
|
||||
## Releases
|
||||
`python release.py` (or `release.ps1`) on Windows or Linux, x64 or ARM64, builds that platform's release into
|
||||
`target/dist/bakashrot-<version>-<platform>/` and its archive (`.zip`, `.tar.gz`):
|
||||
the server, `bakashrot`, `bakashrot-cert`, the client library with its C header and PureBasic prototypes,
|
||||
`bakashrot.py` and a wheel with the library in it (`bindings/python/make_wheel.py`), the example configs,
|
||||
`docs/`, a `README.txt`, the licenses (`THIRD-PARTY.txt`: every crate built in, from `cargo metadata`).
|
||||
|
||||
Then it checks it, in the folder's `_test/`: a CA and certificates, the server on a free port,
|
||||
the tool pushing (an attachment too), reading back, listing and querying, Python through the library
|
||||
and the wheel installed by pip, the server stopped by SIGTERM (Ctrl+Break on Windows),
|
||||
which must end cleanly (`_test/` kept if not). `--skip-test` skips it.
|
||||
|
||||
CI ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on a version tag (`v*`) or by hand: `test.ps1`'s checks
|
||||
on Windows and Linux, then a release on each of Windows x64 and ARM64, Linux x64 and ARM64, each on its own
|
||||
kind of machine (so its smoke test runs there), its archive kept as the run's artifact. The Linux ones build
|
||||
in a manylinux 2.28 container, so they run with glibc 2.28 and later.
|
||||
The version is the workspace's (`Cargo.toml`), and `bindings/python/bakashrot.py`'s `__version__` must be the same.
|
||||
|
||||
The server's Docker image: `docker build -f docker/Dockerfile -t bakashrot-server .`, or CI's for amd64
|
||||
and arm64, checked by `docker/test.sh`, then pushed to `ghcr.io/aziascreations/bakashrot-server` on a tag
|
||||
(`<version>`, and `latest` unless it's a pre-release: `v0.2.0-test2` doesn't move it). Running it: `docs/server.md`, "In Docker". The package was first pushed by hand, so the
|
||||
workflow may push to it only with the repository given write access in its settings on GitHub
|
||||
("Manage Actions access"), once; the package made public there too.
|
||||
|
||||
Publishing:
|
||||
* **The wheel** to Gitea's registry, with twine 6.1+ (for the license metadata) and a token with `write:package`:
|
||||
`twine upload --repository-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi -u aziascreations <wheel>`
|
||||
* **On GitHub** (no Python registry), the archives and the wheels on a release:
|
||||
`gh release create v<version> --repo aziascreations/BakaShrot --title <version> <files>`
|
||||
(`gh release upload` for one that exists).
|
||||
|
||||
|
||||
## Conventions
|
||||
* LF line endings (`.gitattributes`; `.ps1` CRLF), rustfmt's defaults.
|
||||
* Every public item documented (`missing_docs`), no `unsafe` outside the C API crate.
|
||||
* A crate's root docs say what it does; designs that span crates go in `docs/`, updated with the code.
|
||||
* Use existing crates rather than reimplementing (MessagePack is `rmp-serde`).
|
||||
* Protocol changes update `docs/protocol.md`; error codes are never renumbered, packet ids never reused.
|
||||
@@ -3,7 +3,7 @@
|
||||
//! Python (ctypes) and anything that loads a DLL. `docs/client.md`
|
||||
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file.
|
||||
//!
|
||||
//! The conventions, the old DLL's:
|
||||
//! The conventions:
|
||||
//!
|
||||
//! - **One connection per process:** set the certificates, connect, send
|
||||
//! requests, one at a time (calls from several threads wait for each
|
||||
@@ -288,8 +288,8 @@ pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize {
|
||||
}
|
||||
|
||||
/// Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
|
||||
/// or the path of a file holding it; null or empty for none. Before
|
||||
/// connecting.
|
||||
/// or the path of a file holding it (one that isn't there is a
|
||||
/// `FileError`); null or empty for none. Before connecting.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize {
|
||||
unsafe { set::<Utf8>(crl.cast(), "CRL", true, |state| &mut state.crl) }
|
||||
|
||||
@@ -85,6 +85,9 @@ fn exports() {
|
||||
BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()),
|
||||
1
|
||||
);
|
||||
// A CRL file asked for is needed (client.toml's may be missing).
|
||||
assert_eq!(BakaShrot_SetCrlW(w(&file("missing.crl")).as_ptr()), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::FileError));
|
||||
assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1);
|
||||
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
|
||||
@@ -25,6 +25,11 @@ database = "bakashrot.sqlite"
|
||||
# second or so. ("off" isn't allowed.)
|
||||
synchronous = "full"
|
||||
|
||||
# Replication cut partway through an attachment resumes once the peer has
|
||||
# read back and hashed what it already has, in 30 s at most: up to about
|
||||
# 4 GB received on a hard disk, 15 GB on a SATA SSD, 30-60 GB on NVMe
|
||||
# (estimates). Past that, resuming fails at every retry: keep attachments
|
||||
# well under it (more than a few GB is a lot for this anyway).
|
||||
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
|
||||
retention_interval = "1m" # how often old messages are deleted
|
||||
|
||||
@@ -42,14 +47,16 @@ logs = "30d"
|
||||
push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"]
|
||||
retry_delay = "10s"
|
||||
sync_interval = "5s"
|
||||
sync_interval = "5s" # keep it under 5 min: a link idle that long is closed
|
||||
batch_size = 1000 # messages per packet, 1-10000
|
||||
|
||||
# What certificates with a role may do. A certificate gets everything its
|
||||
# roles allow; one without any role listed here is refused. Every key is
|
||||
# optional: an empty list allows nothing. The topics are only named here:
|
||||
# one exists from its first message, pushed (push_topics) or replicated
|
||||
# (accept_topics).
|
||||
# (accept_topics). A database holds 1,048,575 topic and node pairs at
|
||||
# most, all topics together, never freed: patterns like "*" in
|
||||
# push_topics let clients make as many as they like.
|
||||
[roles.sensor]
|
||||
push_topics = ["sensors.*"] # always as its own node (its name)
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ pub struct Server {
|
||||
pub certificate: PathBuf,
|
||||
/// The server's key.
|
||||
pub key: PathBuf,
|
||||
/// The CA's CRL, watched; none: nothing revoked.
|
||||
/// The CA's CRL, watched; none, or no such file: nothing revoked.
|
||||
#[serde(default)]
|
||||
pub crl: Option<PathBuf>,
|
||||
/// The SQLite database; `bakashrot.sqlite` by default.
|
||||
|
||||
@@ -235,12 +235,6 @@ fn refusals() {
|
||||
("", "missing field `server`"),
|
||||
(&with("lsiten = \"x\"\n"), "unknown field `lsiten`"),
|
||||
(&with("[other]\n"), "unknown field `other`"),
|
||||
// The old ini's keys.
|
||||
(&with("PrivateKey = \"x\"\n"), "unknown field `PrivateKey`"),
|
||||
(
|
||||
&with("[roles.sensor]\nAllowWrite = 1\n"),
|
||||
"unknown field `AllowWrite`",
|
||||
),
|
||||
(
|
||||
&with("[roles.sensor]\ndefault_topic = \"x\"\n"),
|
||||
"unknown field `default_topic`",
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//! The error codes: what a server sends with each refusal (1-99, in a
|
||||
//! `RequestRefused`), and the client's own (100 and up, what the DLL's
|
||||
//! `BakaShrot_GetLastError()` returns). The same numbers as protocol 6
|
||||
//! (`OldSource/Client/BakaShrot_ErrorCodes.pbi`): never renumber one, only
|
||||
//! add new ones.
|
||||
//! `BakaShrot_GetLastError()` returns). Never renumber one, only add new
|
||||
//! ones; 6 is retired, never reuse it.
|
||||
//!
|
||||
//! What to do about each:
|
||||
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
|
||||
//! `ConnectionLost`, `ProtocolError` (the connection is closed);
|
||||
//! - retry later: `NotReady`, `ServerError`;
|
||||
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
|
||||
//! `NotAllowed`, `UnknownName`, `NoDefaultTopic`;
|
||||
//! `NotAllowed`, `UnknownName`;
|
||||
//! - update one end: `VersionMismatch`;
|
||||
//! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`,
|
||||
//! `QueryFailed`, `FileError`;
|
||||
@@ -71,7 +70,6 @@ error_codes! {
|
||||
NotFound = 3, "No such message or attachment.";
|
||||
NotReady = 4, "The attachment isn't on this server yet (still being replicated).";
|
||||
TooBig = 5, "A message, attachment or query result over a limit, or an attachment bigger than this server keeps.";
|
||||
NoDefaultTopic = 6, "Protocol 6's: a push without a topic and no default one. Protocol 7 pushes always name their topic: never sent, kept so the number isn't reused.";
|
||||
InvalidRequest = 7, "A request that doesn't fit: an attachment's parts not matching its size, a part that doesn't exist...";
|
||||
DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped.";
|
||||
QueryFailed = 9, "The SQL of a query failed (its error in the reason).";
|
||||
@@ -131,14 +129,13 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_numbers_of_protocol_6() {
|
||||
fn the_numbers_never_change() {
|
||||
let expected: &[(u32, &str)] = &[
|
||||
(1, "NotAllowed"),
|
||||
(2, "UnknownName"),
|
||||
(3, "NotFound"),
|
||||
(4, "NotReady"),
|
||||
(5, "TooBig"),
|
||||
(6, "NoDefaultTopic"),
|
||||
(7, "InvalidRequest"),
|
||||
(8, "DataMismatch"),
|
||||
(9, "QueryFailed"),
|
||||
@@ -164,6 +161,8 @@ mod tests {
|
||||
assert_eq!(known.is_refusal(), *code < 100);
|
||||
assert!(!known.description().is_empty());
|
||||
}
|
||||
// Retired: never given to another code.
|
||||
assert_eq!(ErrorCode::from_code(6), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! waiting for the rest. An empty one is too (as a frame here, as a packet
|
||||
//! that doesn't decode with [`codec()`]).
|
||||
//!
|
||||
//! Over TLS, which takes care of the encryption: unlike protocol 6, frames
|
||||
//! carry packets as they are.
|
||||
//! Over TLS, which takes care of the encryption: frames carry packets as
|
||||
//! they are.
|
||||
//!
|
||||
//! Before any frame, right after TLS, each end sends its protocol version
|
||||
//! (4 bytes, little-endian) and reads the other's: [`write_version()`],
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! through `serde` and `rmp-serde`.
|
||||
//!
|
||||
//! - [`limits`]: the protocol's numbers (sizes, counts, the version).
|
||||
//! - [`error`]: the error codes, the same numbers as protocol 6.
|
||||
//! - [`error`]: the error codes, never renumbered.
|
||||
//! - [`names`]: topic and node names, wildcards.
|
||||
//! - [`frame`]: frames, a 4-byte size then a packet.
|
||||
//! - [`packets`]: every packet, and [`Packet`] to encode and decode them.
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
|
||||
/// The protocol's version. Both ends must have the same: they tell each
|
||||
/// other first thing (`frame::write_version()`), and abandon the
|
||||
/// connection if it differs. 6 was the last PureBasic one (`OldSource/`);
|
||||
/// 7 runs over TLS.
|
||||
/// connection if it differs.
|
||||
pub const PROTOCOL_VERSION: u32 = 7;
|
||||
|
||||
/// The ALPN protocol name both ends offer during the TLS handshake: what
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Topic and node names, and wildcards: the rules of protocol 6
|
||||
//! (`OldSource/Commons/Networking/Names.pbi`), without its ids.
|
||||
//! Topic and node names, and wildcards.
|
||||
//!
|
||||
//! Topics and nodes go by name everywhere on the wire: a server's ids for
|
||||
//! them are its own business, in its database.
|
||||
|
||||
@@ -93,8 +93,7 @@ pub trait Body: Serialize + DeserializeOwned + Check + Into<Packet> {
|
||||
}
|
||||
|
||||
// The one table of packets: their names (the struct's and the variant's)
|
||||
// and ids. Protocol 7's own: protocol 6's ids don't apply (the versions are
|
||||
// checked before any packet).
|
||||
// and ids (the versions are checked before any packet).
|
||||
macro_rules! packets {
|
||||
($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => {
|
||||
/// The type of a packet: its first value.
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Replication, between servers: at each check-in a peer (P) asks the
|
||||
//! server (S) what it takes and has, then sends what it's missing,
|
||||
//! messages first, then attachments (`OldSource/Design/Packets.md`,
|
||||
//! "Replication"). Servers only ever send each other names: each has its
|
||||
//! own ids.
|
||||
//! messages first, then attachments. Servers only ever send each other
|
||||
//! names: each has its own ids.
|
||||
|
||||
use super::rules;
|
||||
use super::{Attachment, Check, DecodeError};
|
||||
|
||||
@@ -12,7 +12,46 @@ use bakashrot_proto::packets::{
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, PoisonError};
|
||||
use tracing::warn;
|
||||
|
||||
/// A replicated attachment being received over one connection: another
|
||||
/// asking for it is refused until this is dropped (finished, refused,
|
||||
/// the connection gone).
|
||||
struct Receiving<'a> {
|
||||
shared: &'a Shared,
|
||||
key: (String, String, u64),
|
||||
}
|
||||
|
||||
impl<'a> Receiving<'a> {
|
||||
/// None when it's being received already. Names without case, as
|
||||
/// everywhere ("Logs" is "logs").
|
||||
fn claim(shared: &'a Shared, topic: &str, node: &str, message_id: u64) -> Option<Self> {
|
||||
let key = (
|
||||
topic.to_ascii_lowercase(),
|
||||
node.to_ascii_lowercase(),
|
||||
message_id,
|
||||
);
|
||||
let claimed = shared
|
||||
.receiving
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.clone());
|
||||
// Made only when claimed, the lock let go: dropping one releases it.
|
||||
claimed.then(|| Receiving { shared, key })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Receiving<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut receiving = self
|
||||
.shared
|
||||
.receiving
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
receiving.remove(&self.key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `address` is in `accept_from`: `*`, an address as written, or
|
||||
/// a hostname resolving to it (looked up now).
|
||||
@@ -152,6 +191,16 @@ pub(crate) async fn replicate_attachment(
|
||||
return Ok(refusal);
|
||||
}
|
||||
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id);
|
||||
// One peer at a time per attachment, until this returns (or the
|
||||
// connection goes): two at once would both be refused a part.
|
||||
let Some(_receiving) =
|
||||
Receiving::claim(shared, &request.topic, &request.node, request.message_id)
|
||||
else {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotReady,
|
||||
format!("{message}: being received from another server"),
|
||||
));
|
||||
};
|
||||
let ReplicateAttachment {
|
||||
topic,
|
||||
node,
|
||||
@@ -175,8 +224,22 @@ pub(crate) async fn replicate_attachment(
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let next = stored.received / ATTACHMENT_PART_SIZE;
|
||||
if from_part != next || stored.received == stored.size {
|
||||
// Every part came but nobody is checking them (finishing it failed):
|
||||
// started over, it's never taken unchecked.
|
||||
let mut received = stored.received;
|
||||
if received == stored.size {
|
||||
warn!("{message}: its attachment came whole but wasn't checked, asked for again");
|
||||
let restart = Write::FinishReplicated {
|
||||
attachment: stored.id as u64,
|
||||
matches: false,
|
||||
};
|
||||
if let Err(refusal) = shared.pushes.send(restart).await {
|
||||
return Ok(refusal.into());
|
||||
}
|
||||
received = 0;
|
||||
}
|
||||
let next = received / ATTACHMENT_PART_SIZE;
|
||||
if from_part != next {
|
||||
return Ok(refused(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{message}: part {next} is the next one here, not {from_part}"),
|
||||
|
||||
@@ -28,6 +28,7 @@ use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -66,12 +67,16 @@ struct Shared {
|
||||
readers: Mutex<Vec<Reader>>,
|
||||
/// Query connections not in use.
|
||||
queries: Mutex<Vec<QueryRunner>>,
|
||||
/// The replicated attachments being received (topic, node, message
|
||||
/// id): one peer at a time each (`accept_from.rs`).
|
||||
receiving: Mutex<HashSet<(String, String, u64)>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Reads the server's certificates and CRL, opens its database, starts
|
||||
/// its writer. Errors say which file and why.
|
||||
pub fn start(config: Config) -> Result<Server, String> {
|
||||
check_clock(SystemTime::now())?;
|
||||
let server = &config.server;
|
||||
let ca = read(&server.ca)?;
|
||||
let certificate = read(&server.certificate)?;
|
||||
@@ -107,6 +112,7 @@ impl Server {
|
||||
pushes,
|
||||
readers: Mutex::new(Vec::new()),
|
||||
queries: Mutex::new(Vec::new()),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
}),
|
||||
})
|
||||
@@ -252,7 +258,7 @@ impl Shared {
|
||||
|
||||
/// Checkpoints the WAL every second, on a thread and a connection of its
|
||||
/// own, so the writer doesn't do it in the middle of a commit (2.5 times
|
||||
/// the pushes: `docs/storage.md`, "Against the old storage").
|
||||
/// the pushes: `docs/storage.md`, "The benchmark").
|
||||
fn start_checkpoints(database: &Database) -> Result<(), String> {
|
||||
let checkpointer = database.checkpointer().map_err(|error| error.to_string())?;
|
||||
std::thread::Builder::new()
|
||||
@@ -294,14 +300,28 @@ fn read(path: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// The CRL file's revocations; none without one (no file, or not set).
|
||||
/// The CRL file's revocations; none without one (not set, or no file:
|
||||
/// warned, a CRL deleted by mistake would revoke nothing silently).
|
||||
fn load_revocations(path: Option<&Path>, ca: &str) -> Result<Revocations, String> {
|
||||
let Some(path) = path.filter(|path| path.exists()) else {
|
||||
let Some(path) = path else {
|
||||
return Ok(Revocations::none());
|
||||
};
|
||||
if !path.exists() {
|
||||
warn!("{}: no such file, nothing revoked", path.display());
|
||||
return Ok(Revocations::none());
|
||||
}
|
||||
Revocations::load(&read(path)?, ca).map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// Refuses a clock before 1970: messages would be stamped `pushed_at` 0,
|
||||
/// which readers refuse.
|
||||
fn check_clock(now: SystemTime) -> Result<(), String> {
|
||||
match now.duration_since(UNIX_EPOCH) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("the system's clock is before 1970: set it right first".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Now, in ms since 1970 UTC: when a message is pushed.
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
@@ -314,3 +334,17 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
|
||||
let metadata = std::fs::metadata(path).ok()?;
|
||||
Some((metadata.modified().ok()?, metadata.len()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_clock_before_1970_is_refused() {
|
||||
assert!(check_clock(UNIX_EPOCH).is_ok());
|
||||
assert!(check_clock(SystemTime::now()).is_ok());
|
||||
let before = UNIX_EPOCH - Duration::from_secs(1);
|
||||
let error = check_clock(before).unwrap_err();
|
||||
assert!(error.contains("before 1970"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -429,8 +429,7 @@ fn ids(messages: &Messages) -> Vec<u64> {
|
||||
messages.messages.iter().map(|message| message.id).collect()
|
||||
}
|
||||
|
||||
/// `OldSource/Tests/GetMessages-Test.ps1`, the server's part (the tool's
|
||||
/// is step 8).
|
||||
/// Runs of messages: after an id, limits, `more`, the latest.
|
||||
#[test]
|
||||
fn runs_of_messages() {
|
||||
let running = Running::start("runs");
|
||||
@@ -515,8 +514,7 @@ fn runs_of_messages() {
|
||||
assert_eq!(run(&mut kitchen, None, 1).messages[0].data, text);
|
||||
}
|
||||
|
||||
/// `OldSource/Tests/BigMessages-Test.ps1`, one server's part (replicating
|
||||
/// them is step 11): up to the limit, answers split at about 1 MB.
|
||||
/// Big messages: up to the limit, answers split at about 1 MB.
|
||||
#[test]
|
||||
fn big_messages() {
|
||||
let running = Running::start("big");
|
||||
@@ -628,7 +626,7 @@ fn names() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The query parts of `OldSource/Tests/BigMessages-Test.ps1`.
|
||||
/// Queries: allowed or not, results, refusals.
|
||||
#[test]
|
||||
fn queries() {
|
||||
let running = Running::start("queries");
|
||||
@@ -1157,8 +1155,7 @@ fn retention() {
|
||||
assert_eq!(latest.messages[0].id, 4);
|
||||
}
|
||||
|
||||
/// Replication flat out, as the old `Tests/Bench/Bench-Replication.ps1`
|
||||
/// (`-Parts Ramp -Ramp 10x0`): 4 servers in a Y (a hub pushing to 3
|
||||
/// Replication flat out: 4 servers in a Y (a hub pushing to 3
|
||||
/// leaves, each pushing to the hub), `NODES` nodes (10) pushing to each
|
||||
/// as fast as they're answered for `SECONDS` (30), then how far behind
|
||||
/// each server is and how long until every one has every message. Run
|
||||
@@ -1582,3 +1579,140 @@ fn replication_edges() {
|
||||
});
|
||||
other.refused(ErrorCode::NotAllowed);
|
||||
}
|
||||
|
||||
/// Message `id`'s attachment in `running`'s database: its state and
|
||||
/// how much of it came.
|
||||
fn attachment_row(running: &Running, id: u64) -> (String, u64) {
|
||||
let raw = rusqlite::Connection::open(running.folder.join("bakashrot.sqlite")).unwrap();
|
||||
raw.query_row(
|
||||
"SELECT a.state, a.received FROM attachments a \
|
||||
JOIN data d ON d.key = a.message_key WHERE d.message_id = ?1",
|
||||
[id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_peers_one_attachment() {
|
||||
// The test plays two peers having the same attachments.
|
||||
let running = Running::start_with(
|
||||
"two-peers",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
|
||||
);
|
||||
let x = running.issue("server-x", &["peer"]);
|
||||
let mut a = Raw::connect(&running, &x);
|
||||
let mut b = Raw::connect(&running, &running.issue("server-y", &["peer"]));
|
||||
let small = bytes(MIB + 10, 7);
|
||||
let whole = bytes(2 * MIB, 8);
|
||||
let message = |id, file: &[u8]| ReplicatedMessage {
|
||||
id,
|
||||
pushed_at: 1_800_000_000_000,
|
||||
data: format!("m{id}"),
|
||||
attachment: Some(Attachment {
|
||||
size: file.len() as u64,
|
||||
sha256: sha256(file),
|
||||
}),
|
||||
};
|
||||
a.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(1, &small), message(2, &small), message(3, &whole)],
|
||||
});
|
||||
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
|
||||
let ask = |raw: &mut Raw, topic: &str, message_id, from_part| {
|
||||
raw.send(ReplicateAttachment {
|
||||
topic: topic.into(),
|
||||
node: "far".into(),
|
||||
message_id,
|
||||
from_part,
|
||||
})
|
||||
};
|
||||
let send_parts = |raw: &mut Raw, file: &[u8]| {
|
||||
for part in file.chunks(MIB) {
|
||||
raw.send(AttachmentPart {
|
||||
data: part.to_vec(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let mut reader = running
|
||||
.connect(&running.issue("watcher", &["reader"]))
|
||||
.unwrap();
|
||||
let mut got = |id| {
|
||||
let mut out = Vec::new();
|
||||
reader.get_attachment("logs", "far", id, &mut out).unwrap();
|
||||
out
|
||||
};
|
||||
|
||||
// One peer at a time: the other is refused before any part (in any
|
||||
// case of the names), the first one finishes it.
|
||||
ask(&mut a, "logs", 1, 0);
|
||||
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
|
||||
ask(&mut b, "logs", 1, 0);
|
||||
b.refused(ErrorCode::NotReady);
|
||||
ask(&mut b, "LOGS", 1, 0);
|
||||
b.refused(ErrorCode::NotReady);
|
||||
send_parts(&mut a, &small);
|
||||
assert_eq!(a.receive(), Some(MessagePushed { message_id: 1 }.into()));
|
||||
assert!(got(1) == small);
|
||||
ask(&mut b, "logs", 1, 0);
|
||||
b.refused(ErrorCode::NotFound);
|
||||
|
||||
// A peer gone partway: the next one takes it from there.
|
||||
ask(&mut a, "logs", 2, 0);
|
||||
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
|
||||
a.send(AttachmentPart {
|
||||
data: small[..MIB].to_vec(),
|
||||
});
|
||||
wait_for("the first part", || {
|
||||
attachment_row(&running, 2).1 == MIB as u64
|
||||
});
|
||||
drop(a);
|
||||
wait_for("the attachment let go", || {
|
||||
ask(&mut b, "logs", 2, 1);
|
||||
match b.receive() {
|
||||
Some(Packet::Continue(_)) => true,
|
||||
Some(Packet::RequestRefused(refused)) => {
|
||||
assert_eq!(refused.code, ErrorCode::NotReady.code(), "{refused:?}");
|
||||
false
|
||||
}
|
||||
other => panic!("expected Continue or NotReady, got {other:?}"),
|
||||
}
|
||||
});
|
||||
send_parts(&mut b, &small[MIB..]);
|
||||
assert_eq!(b.receive(), Some(MessagePushed { message_id: 2 }.into()));
|
||||
assert!(got(2) == small);
|
||||
|
||||
// Whole but never checked (finishing it failed): asked for from the
|
||||
// first part, not past its last; started over, never taken unchecked.
|
||||
let mut a = Raw::connect(&running, &x);
|
||||
ask(&mut a, "logs", 3, 0);
|
||||
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
|
||||
send_parts(&mut a, &whole);
|
||||
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
|
||||
let raw = rusqlite::Connection::open(running.folder.join("bakashrot.sqlite")).unwrap();
|
||||
raw.execute(
|
||||
"UPDATE attachments SET state = 'replicating' \
|
||||
WHERE message_key = (SELECT key FROM data WHERE message_id = 3)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
attachment_row(&running, 3),
|
||||
("replicating".into(), whole.len() as u64)
|
||||
);
|
||||
let missing: Vec<_> = sync_state(&mut a)
|
||||
.missing
|
||||
.iter()
|
||||
.map(|missing| (missing.message_id, missing.next_part))
|
||||
.collect();
|
||||
assert_eq!(missing, [(3, 0)], "not part 2: then it's never asked for");
|
||||
ask(&mut a, "logs", 3, 2);
|
||||
a.refused(ErrorCode::InvalidRequest);
|
||||
assert_eq!(attachment_row(&running, 3), ("replicating".into(), 0));
|
||||
ask(&mut a, "logs", 3, 0);
|
||||
assert!(matches!(a.receive(), Some(Packet::Continue(_))));
|
||||
send_parts(&mut a, &whole);
|
||||
assert_eq!(a.receive(), Some(MessagePushed { message_id: 3 }.into()));
|
||||
assert!(got(3) == whole);
|
||||
}
|
||||
|
||||
@@ -36,18 +36,6 @@ impl Writer {
|
||||
batch.transaction.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Gives the space of deleted messages back to the disk: rewrites the
|
||||
/// database (`VACUUM`), then empties the WAL. SQLite reuses that space
|
||||
/// by itself; this only shrinks the file. Slow on a big database, and
|
||||
/// every other write waits meanwhile: the old server's `vacuum`
|
||||
/// command.
|
||||
pub fn vacuum(&mut self) -> Result<()> {
|
||||
self.connection.execute_batch("VACUUM")?;
|
||||
self.connection
|
||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What's written in one transaction ([`Writer::batch`]). Names come
|
||||
|
||||
@@ -28,8 +28,7 @@ const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000;
|
||||
|
||||
/// Copies the WAL into the database on a connection of its own, so the
|
||||
/// writer doesn't do it in the middle of a commit (the old server's way:
|
||||
/// `OldSource/Server/Storage/Writer.pbi`).
|
||||
/// writer doesn't do it in the middle of a commit.
|
||||
#[derive(Debug)]
|
||||
pub struct Checkpointer {
|
||||
connection: Connection,
|
||||
@@ -74,7 +73,10 @@ impl Database {
|
||||
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
|
||||
)?;
|
||||
} else if application_id != APPLICATION_ID {
|
||||
return Err(Error::Unusable(unusable(&transaction, path)?));
|
||||
return Err(Error::Unusable(format!(
|
||||
"{}: not a BakaShrot database",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let mut version = schema_version(&transaction)?;
|
||||
if version > SCHEMA_VERSION {
|
||||
@@ -184,20 +186,3 @@ fn schema_version(connection: &Connection) -> Result<i64> {
|
||||
};
|
||||
version.ok_or_else(|| Error::Unusable("a BakaShrot database without its schema version".into()))
|
||||
}
|
||||
|
||||
/// Why a database that isn't ours can't be opened, in words.
|
||||
fn unusable(connection: &Connection, path: &Path) -> Result<String> {
|
||||
let old: bool = connection.query_row(
|
||||
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'node_heads'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(if old {
|
||||
format!(
|
||||
"{}: made by the old server (schema v8), which this one doesn't read: start a new database",
|
||||
path.display()
|
||||
)
|
||||
} else {
|
||||
format!("{}: not a BakaShrot database", path.display())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! and hands out connections.
|
||||
//! - [`Writer`]: the one connection that writes. Everything is written in
|
||||
//! a [`Batch`], one transaction: pushes, replication, attachments,
|
||||
//! retention. Many pushes in one batch is a group commit. And
|
||||
//! [`Writer::vacuum`], to shrink the file.
|
||||
//! retention. Many pushes in one batch is a group commit.
|
||||
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
|
||||
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
|
||||
//!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Clients' read-only SQL (`Query`), as the old server ran it.
|
||||
//! Clients' read-only SQL (`Query`).
|
||||
//!
|
||||
//! Read-only three ways: the connection has `query_only` on (SQLite
|
||||
//! refuses any write), the statement must be one SQLite says only reads
|
||||
@@ -6,8 +6,8 @@
|
||||
//! error, not ignored). PRAGMAs are refused as they're prepared
|
||||
//! (`Database::query_runner`'s authorizer): some would change the
|
||||
//! connection, `query_only` included, before the statement is looked
|
||||
//! at. The result is JSON, every value a string or null
|
||||
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
|
||||
//! at. The result is JSON, every value a string or null:
|
||||
//! `{"columns":[...],"rows":[[...],...]}`.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
|
||||
@@ -77,7 +77,7 @@ impl QueryRunner {
|
||||
}
|
||||
}
|
||||
|
||||
/// SQLite's error, with a hint where the old server gave one.
|
||||
/// SQLite's error, with a hint where one helps.
|
||||
fn explain(why: String) -> String {
|
||||
if why.contains("malformed JSON") {
|
||||
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
|
||||
|
||||
@@ -190,17 +190,23 @@ impl Reader {
|
||||
pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> {
|
||||
self.connection
|
||||
.prepare_cached(
|
||||
"SELECT s.topic, s.node, d.message_id, a.received FROM attachments a \
|
||||
"SELECT s.topic, s.node, d.message_id, a.received, a.size FROM attachments a \
|
||||
JOIN data d ON d.key = a.message_key \
|
||||
JOIN streams s ON s.stream_id = d.stream_id \
|
||||
WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1",
|
||||
)?
|
||||
.query_map([limit as i64], |row| {
|
||||
let (received, size): (u64, u64) = (row.get(3)?, row.get(4)?);
|
||||
Ok(MissingAttachment {
|
||||
topic: row.get(0)?,
|
||||
node: row.get(1)?,
|
||||
message_id: row.get(2)?,
|
||||
next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE,
|
||||
// Whole but not checked: it starts over from the first.
|
||||
next_part: if received == size {
|
||||
0
|
||||
} else {
|
||||
received / ATTACHMENT_PART_SIZE
|
||||
},
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
-- keys below are packed integers, on purpose, and only bakashrot-storage
|
||||
-- packs and unpacks them.
|
||||
--
|
||||
-- Not compatible with v8 (OldSource/Server/Storage/db_schema_v8.dbml): a
|
||||
-- database of the old server isn't opened, its data isn't carried over.
|
||||
-- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate.
|
||||
--
|
||||
-- Run once, in one transaction, on an empty database (Database::open).
|
||||
@@ -128,7 +126,7 @@ FROM streams s
|
||||
JOIN data d ON d.key BETWEEN (s.stream_id << 43) AND (s.stream_id << 43) + 8796093022207
|
||||
LEFT JOIN attachments a ON a.message_key = d.key;
|
||||
|
||||
-- What to browse with a database tool (v8's): set topic, and node or NULL
|
||||
-- What to browse with a database tool: set topic, and node or NULL
|
||||
-- for all, in its one row, open browse_messages. Never written by the
|
||||
-- server.
|
||||
CREATE TABLE browse (
|
||||
|
||||
@@ -84,10 +84,6 @@ fn refused_databases() {
|
||||
}
|
||||
};
|
||||
refused("CREATE TABLE other (x);", "not a BakaShrot database");
|
||||
refused(
|
||||
"CREATE TABLE data (x); CREATE TABLE node_heads (y);",
|
||||
"made by the old server (schema v8)",
|
||||
);
|
||||
refused(
|
||||
"PRAGMA application_id = 1112754260; CREATE TABLE x (y);",
|
||||
"without its schema version",
|
||||
@@ -580,36 +576,6 @@ fn retention() {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vacuum() {
|
||||
let (database, path) = open("vacuum");
|
||||
let mut writer = database.writer().unwrap();
|
||||
let big = "x".repeat(10_000);
|
||||
writer
|
||||
.batch(|b| {
|
||||
for _ in 0..1000 {
|
||||
b.push("logs", "kitchen", 1, &big)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
writer.vacuum().unwrap();
|
||||
let full = std::fs::metadata(&path).unwrap().len();
|
||||
writer
|
||||
.batch(|b| b.delete_before("logs", u64::MAX, 10_000))
|
||||
.unwrap();
|
||||
writer.vacuum().unwrap();
|
||||
let emptied = std::fs::metadata(&path).unwrap().len();
|
||||
assert!(emptied * 10 < full, "{full} -> {emptied}");
|
||||
// Still the same database: ids go on.
|
||||
assert_eq!(
|
||||
writer
|
||||
.batch(|b| b.push("logs", "kitchen", 2, "{}"))
|
||||
.unwrap(),
|
||||
1001
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits() {
|
||||
let (database, path) = open("limits");
|
||||
@@ -829,8 +795,7 @@ fn readers_while_writing() {
|
||||
assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000);
|
||||
}
|
||||
|
||||
/// The same workload as the old storage's benchmark
|
||||
/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes
|
||||
/// The storage alone, flat out (`docs/storage.md`, "The benchmark"): pushes
|
||||
/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte
|
||||
/// JSON; 2000 latest-message reads, 500 reads of 1000 messages after the
|
||||
/// middle id, the file's size, retention of 10% of one topic. Not run by
|
||||
@@ -838,7 +803,7 @@ fn readers_while_writing() {
|
||||
/// bakashrot-storage -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn compare_with_old() {
|
||||
fn storage_rate() {
|
||||
use std::time::Instant;
|
||||
let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap());
|
||||
let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into());
|
||||
@@ -847,7 +812,7 @@ fn compare_with_old() {
|
||||
} else {
|
||||
Synchronous::Normal
|
||||
};
|
||||
let path = path("compare");
|
||||
let path = path("rate");
|
||||
let database = Database::open(&path, synchronous).unwrap();
|
||||
let mut writer = database.writer().unwrap();
|
||||
|
||||
@@ -858,7 +823,7 @@ fn compare_with_old() {
|
||||
let nodes: Vec<String> = (0..5).map(|n| format!("node{n}")).collect();
|
||||
|
||||
// Checkpoints every second on their own connection, as the server's
|
||||
// (and the old server's) thread does.
|
||||
// thread does.
|
||||
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let checkpoints = {
|
||||
let checkpointer = database.checkpointer().unwrap();
|
||||
@@ -932,7 +897,7 @@ fn compare_with_old() {
|
||||
let retention = start.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
println!(
|
||||
"new {sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
|
||||
"{sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
|
||||
count as f64 / pushing,
|
||||
size as f64 / 1e6
|
||||
);
|
||||
|
||||
@@ -99,8 +99,12 @@ fn run(command: Command) -> Result<(), String> {
|
||||
match command {
|
||||
Command::Ca { name, days, out } => {
|
||||
let ca = Ca::create(&name, days).map_err(|e| e.to_string())?;
|
||||
write_new(&out.join("ca.crt"), &ca.certificate, false)?;
|
||||
write_new(&out.join("ca.key"), &ca.key, true)?;
|
||||
write_pair(
|
||||
&out.join("ca.crt"),
|
||||
&ca.certificate,
|
||||
&out.join("ca.key"),
|
||||
&ca.key,
|
||||
)?;
|
||||
}
|
||||
Command::Issue {
|
||||
name,
|
||||
@@ -118,8 +122,12 @@ fn run(command: Command) -> Result<(), String> {
|
||||
.issue(&identity, usage, days)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let file = file.unwrap_or(name);
|
||||
write_new(&out.join(format!("{file}.crt")), &issued.certificate, false)?;
|
||||
write_new(&out.join(format!("{file}.key")), &issued.key, true)?;
|
||||
write_pair(
|
||||
&out.join(format!("{file}.crt")),
|
||||
&issued.certificate,
|
||||
&out.join(format!("{file}.key")),
|
||||
&issued.key,
|
||||
)?;
|
||||
}
|
||||
Command::Revoke {
|
||||
certificates,
|
||||
@@ -159,8 +167,28 @@ fn write_new(path: &Path, text: &str, private: bool) -> Result<(), String> {
|
||||
.open(path)
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
file.write_all(text.as_bytes())
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
println!("Wrote {}", path.display());
|
||||
.map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// Writes a certificate and its key, both or neither: nothing is written
|
||||
/// when either is there already, the certificate is removed again when
|
||||
/// its key can't be written.
|
||||
fn write_pair(certificate: &Path, pem: &str, key: &Path, key_pem: &str) -> Result<(), String> {
|
||||
for path in [certificate, key] {
|
||||
if path.exists() {
|
||||
return Err(format!(
|
||||
"{}: already there, nothing written",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
write_new(certificate, pem, false)?;
|
||||
if let Err(error) = write_new(key, key_pem, true) {
|
||||
let _ = fs::remove_file(certificate);
|
||||
return Err(format!("{error}, nothing written"));
|
||||
}
|
||||
println!("Wrote {}", certificate.display());
|
||||
println!("Wrote {}", key.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! `bakashrot`: pushes messages, reads them and their attachments, runs
|
||||
//! queries and lists names from the command line, connecting with a
|
||||
//! `client.toml`. The old `BakaShrot*` tools in one program; see
|
||||
//! `docs/client.md`, "The tools".
|
||||
//! `client.toml`; see `docs/client.md`, "The tools".
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
@@ -316,9 +315,11 @@ fn connect(config: &Path) -> Result<Client, String> {
|
||||
let ca = pem("CA's certificate", &settings.ca)?;
|
||||
let certificate = pem("certificate", &settings.certificate)?;
|
||||
let key = pem("key", &settings.key)?;
|
||||
// No CRL file yet: nothing revoked, as on the server.
|
||||
let crl = settings
|
||||
.crl
|
||||
.as_deref()
|
||||
.filter(|path| folder.join(path).exists())
|
||||
.map(|path| pem("CRL", path))
|
||||
.transpose()?;
|
||||
let pems = Settings {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `bakashrot` end to end against a server on a free port: the old suites'
|
||||
//! tool checks (GetMessages, Names, BigMessages).
|
||||
//! `bakashrot` end to end against a server on a free port: messages,
|
||||
//! pushes and refusals, big messages, attachments, queries, lists.
|
||||
|
||||
use bakashrot_client::{Client, Settings};
|
||||
use bakashrot_config::Config;
|
||||
@@ -550,7 +550,11 @@ fn settings() {
|
||||
format!("{kitchen}crl = \"none.crl\"\n"),
|
||||
)
|
||||
.unwrap();
|
||||
run(folder, "crl", &["list"], None).fails(1, "Can't read the CRL");
|
||||
// No CRL file yet: nothing revoked. One that isn't a CRL is refused.
|
||||
let none = run(folder, "crl", &["list", "topics"], None);
|
||||
assert_eq!(none.ok().out, "Topics (0):\n");
|
||||
fs::write(folder.join("none.crl"), "not a CRL").unwrap();
|
||||
run(folder, "crl", &["list"], None).fails(1, "the CRL");
|
||||
let closed = kitchen.replace(&server.port.to_string(), "1");
|
||||
fs::write(folder.join("closed.toml"), closed).unwrap();
|
||||
run(folder, "closed", &["list"], None)
|
||||
|
||||
@@ -121,6 +121,20 @@ fn nothing_is_overwritten_or_mixed_up() {
|
||||
assert!(!ok, "{text}");
|
||||
assert_eq!(read(&folder, "ca.key"), key, "the CA's key is still there");
|
||||
|
||||
// Half of a pair there already: refused, the other half not written.
|
||||
let half = folder.join("half");
|
||||
fs::create_dir_all(&half).unwrap();
|
||||
fs::write(half.join("ca.key"), "kept").unwrap();
|
||||
let (ok, text) = cert(&half, &["ca", "--name", "Half"]);
|
||||
assert!(!ok && text.contains("nothing written"), "{text}");
|
||||
assert!(!half.join("ca.crt").exists());
|
||||
assert_eq!(read(&half, "ca.key"), "kept");
|
||||
fs::write(folder.join("porch.key"), "kept").unwrap();
|
||||
let (ok, text) = cert(&folder, &["issue", "--name", "porch"]);
|
||||
assert!(!ok && text.contains("nothing written"), "{text}");
|
||||
assert!(!folder.join("porch.crt").exists());
|
||||
assert_eq!(read(&folder, "porch.key"), "kept");
|
||||
|
||||
assert!(cert(&folder, &["issue", "--name", "kitchen"]).0);
|
||||
assert!(
|
||||
!cert(&folder, &["issue", "--name", "kitchen"]).0,
|
||||
|
||||
+11
-8
@@ -29,9 +29,7 @@ is a CRL file from the CA, pushed to the servers.
|
||||
only digits), 64 roles at most. Roles mean nothing to the certificates:
|
||||
the server's config says what each may do.
|
||||
- **Its OID is `1.3.6.1.4.1.67681.1.1`** (`IDENTITY_OID`), under
|
||||
NibblePoker's own PEN (67681), since 0.3.0. Certificates made before
|
||||
(a placeholder OID) aren't read: issue them again. The branches:
|
||||
`oid.md`.
|
||||
NibblePoker's own PEN (67681). The branches: `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
|
||||
@@ -77,9 +75,12 @@ connected, `peer_identity()` gives the other end's `Identity`.
|
||||
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.
|
||||
the revocations (`Revocations::none()` without a CRL, or when the
|
||||
server's config or `client.toml` names a CRL file that isn't there
|
||||
yet: never blocking, the server warns in its log; a path given to
|
||||
the DLL is a `FileError`). 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
|
||||
@@ -103,8 +104,10 @@ 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
|
||||
another certificate of the same name, `--file server-1b`). Files are
|
||||
PEM. Nothing is ever written over an existing certificate or key, and a
|
||||
certificate and its key are written both or neither (one of them there
|
||||
already: nothing written); keys are readable by their owner only on
|
||||
Unix. `revoke` only takes certificates the CA issued.
|
||||
|
||||
## Tests
|
||||
|
||||
+14
-36
@@ -5,9 +5,9 @@ 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 |
|
||||
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `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 |
|
||||
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes |
|
||||
| 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` |
|
||||
|
||||
@@ -35,12 +35,12 @@ 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
|
||||
crl = "ca.crl" # optional; a file not there yet: none
|
||||
```
|
||||
|
||||
## The DLL
|
||||
|
||||
The old DLL's conventions, kept:
|
||||
Its conventions:
|
||||
|
||||
- **One connection per process.** Calls from several threads wait for each
|
||||
other.
|
||||
@@ -82,25 +82,9 @@ The old DLL's conventions, kept:
|
||||
|
||||
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,
|
||||
`bindings/python/bakashrot.py`: `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,
|
||||
@@ -118,15 +102,15 @@ wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
|
||||
|
||||
`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
|
||||
the `W` exports without their suffix, `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).
|
||||
with an attachment, reading both back (run by hand against a server;
|
||||
not in CI, which has no PureBasic).
|
||||
|
||||
## The tools
|
||||
|
||||
`bakashrot`, the old `BakaShrot*` tools in one program (`bakashrot-cert`,
|
||||
`bakashrot`, one program to push, read, query and list (`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): ...`,
|
||||
@@ -158,14 +142,10 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
|
||||
- **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`
|
||||
11 ms, connecting included; `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".
|
||||
1.5 s). More: `server.md`, "Measured".
|
||||
|
||||
## Tests
|
||||
|
||||
@@ -176,12 +156,10 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen"
|
||||
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+.
|
||||
- `python.rs`: runs `bindings/python/check_bakashrot.py` 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`.
|
||||
messages (`--follow` too), pushes and refusals, big messages,
|
||||
attachments, queries, lists, `client.toml`.
|
||||
|
||||
+3
-19
@@ -15,7 +15,7 @@ Decided in `../revamp.md`, "Decided".
|
||||
| `[replication]` | the servers it sends to and takes from, 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.
|
||||
Unknown keys are refused, so a typo is caught.
|
||||
|
||||
## Who's who: certificates, then roles
|
||||
|
||||
@@ -100,27 +100,11 @@ 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` |
|
||||
| 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), the topic lists that are gone, 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),
|
||||
folder, and the refusals, each with its line: TOML errors, unknown keys,
|
||||
every value that's wrong, names twice (without case),
|
||||
unquoted dotted names.
|
||||
|
||||
+33
-38
@@ -1,8 +1,7 @@
|
||||
# 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/`).
|
||||
What's known to be wrong or missing, what's left as it is and why, and
|
||||
ideas for later.
|
||||
|
||||
## Threat model
|
||||
|
||||
@@ -36,19 +35,27 @@ network**, not exposed to the internet. So:
|
||||
- **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
|
||||
- **Peers are trusted with what they replicate:** 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`,
|
||||
- **One connection per process in the DLL** (`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.
|
||||
- **1,048,575 topic and node pairs per database** (2^20 - 1,
|
||||
`MAX_STREAMS`, `bakashrot-storage/src/lib.rs`), for all topics
|
||||
together, and 2^43 - 1 message ids per pair (`MAX_MESSAGE_ID`): the
|
||||
20 and 43 bits of a message's packed key (`storage.md`, "Keys"). Past
|
||||
the first, a new pair is refused from anyone, pushed or replicated;
|
||||
pairs aren't freed when their messages are deleted. Enough for now
|
||||
(the owner, 2026-11-16). Raising it means another key layout, so a
|
||||
new schema version.
|
||||
|
||||
## Found by reading the code, not reproduced
|
||||
|
||||
@@ -58,29 +65,22 @@ Reproduce one before fixing it, and move it up (or drop it) once known.
|
||||
- **`sync_interval` over 5 min.** The server dialed closes the idle link
|
||||
(`IDLE_TIMEOUT`), so every check-in fails once ("closed the link",
|
||||
warned), then the link is dialed again after `retry_delay`. Nothing
|
||||
in the config caps `sync_interval`. Fix: cap it under the idle
|
||||
timeout, or have an idle link ask its `SyncState` more often.
|
||||
in the config caps `sync_interval`. Left as it is (the owner,
|
||||
2026-11-16): replicating every 5 min or more isn't a real use, the
|
||||
example config says to keep it under. Fix if needed: cap it under the
|
||||
idle timeout, or have an idle link ask its `SyncState` more often.
|
||||
- **Resuming a big replicated attachment.** Before answering `Continue`,
|
||||
the receiver reads back and hashes every part it already has
|
||||
(`accept_from.rs`, `replicate_attachment`, `hash_parts`), while the
|
||||
sender waits 30 s for that answer (`push_to.rs`, `ANSWER_TIMEOUT`). On
|
||||
a slow disk, hundreds of parts may take longer: the link drops, and
|
||||
the same happens at every retry. Fix: a longer wait for that answer,
|
||||
sender waits 30 s for that answer (`push_to.rs`, `ANSWER_TIMEOUT`).
|
||||
Past what the disk reads and hashes in 30 s (estimated: about 4 GB
|
||||
on a hard disk, 15 GB on a SATA SSD, 30-60 GB on NVMe), the link
|
||||
drops, and the same happens at every retry. Left as it is (the
|
||||
owner, 2026-11-16): attachments over a few GB are excessive for this;
|
||||
the example config says so by `max_attachment_size` (1 GiB by
|
||||
default). Fix if needed: a wait scaled to the parts already received,
|
||||
or the hash's state kept with the attachment.
|
||||
- **Two peers sending the same attachment at once.** Both can be
|
||||
answered `Continue` for the same `from_part` (the check and the first
|
||||
part written aren't one step). Their parts then interleave in the
|
||||
writer's queue: each part is stored once, from whichever came first,
|
||||
and each sender has one refused (`InvalidRequest`). With few parts (4
|
||||
or fewer in flight, `PARTS_IN_FLIGHT`), all of them can be stored
|
||||
while both senders were refused: neither sends `FinishReplicated`,
|
||||
and the attachment stays `replicating` with `received = size`, asked
|
||||
for and refused at every check-in until a restart (`clean_up` starts
|
||||
it over). Needs two parts at least and a narrow timing: servers that
|
||||
take from two others having the same attachment. Fix: finish it
|
||||
whenever the last part is stored, or one receiver at a time per
|
||||
attachment.
|
||||
- **`SyncState` in one packet** (old item 9). Every head the peer may
|
||||
- **`SyncState` in one packet.** Every head the peer may
|
||||
send goes in one frame of 16 MiB at most: with very many topic and
|
||||
node pairs (hundreds of thousands) it doesn't fit, the packet can't
|
||||
be sent and replication stops. Fix: heads in several packets, or only
|
||||
@@ -123,27 +123,22 @@ Reproduce one before fixing it, and move it up (or drop it) once known.
|
||||
`GetMessages` answers `UnknownName` for a node without messages
|
||||
anywhere and none for one with messages in another topic
|
||||
(`reader.rs`, `messages`). Fix: none in both cases.
|
||||
- **A CRL file that isn't there.** The server takes it as nothing
|
||||
revoked (`load_revocations`, `bakashrot-server/src/lib.rs`), the
|
||||
`bakashrot` tool refuses to start when `client.toml`'s `crl` names a
|
||||
missing file. Either may be right (a server that starts before its
|
||||
first CRL; a client that must not skip the check): choose one and
|
||||
say it in the docs. A server whose CRL file was deleted by mistake
|
||||
revokes nothing, silently.
|
||||
- **No limits per client.** Any number of connections (each a task and
|
||||
its buffers), any amount pushed: an allowed client can fill the disk
|
||||
or the server's memory. Fine for the threat model; first thing to
|
||||
add if it changes (a cap on connections, a quota per node).
|
||||
- **Small ones:** the client's connect timeout is per socket
|
||||
operation, not for the whole connection; `bakashrot-cert ca` writes
|
||||
`ca.crt` before failing when only `ca.key` is there already; a
|
||||
server whose clock is before 1970 stamps `pushed_at` 0, which
|
||||
readers refuse when decoding.
|
||||
- **A clock set before 1970 while running.** The server refuses to
|
||||
start with one (`check_clock`, `bakashrot-server/src/lib.rs`), but
|
||||
isn't checked again: set back that far afterwards, pushes are stamped
|
||||
`pushed_at` 0 (`now()`), which readers refuse when decoding. Fix if
|
||||
ever needed: refuse pushes (`ServerError`) while the clock is before
|
||||
1970.
|
||||
- **A small one:** the client's connect timeout is per socket
|
||||
operation, not for the whole connection.
|
||||
|
||||
## Ideas for later
|
||||
|
||||
From the old benchmarks and suggestions (`OldSource/Design/Suggestions.md`),
|
||||
worth it only when a use calls for them:
|
||||
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:
|
||||
|
||||
+1
-2
@@ -6,8 +6,7 @@ machine, 2026-11-15, Windows): the outputs shown are what came back.
|
||||
|
||||
Get a release (CI's artifacts, or `release.ps1` / `python release.py`):
|
||||
the programs, `bakashrot.dll` / `libbakashrot.so`, the wheel, the
|
||||
example configs. Certificates made before 0.3.0 had a placeholder
|
||||
identity OID (`oid.md`) and aren't read any more: issue them again.
|
||||
example configs.
|
||||
|
||||
| Machine | What runs there | Files it gets |
|
||||
|---|---|---|
|
||||
|
||||
+1
-13
@@ -1,7 +1,6 @@
|
||||
# The identity extension's OID
|
||||
|
||||
`IDENTITY_OID = 1.3.6.1.4.1.67681.1.1` (`crates/bakashrot-pki/src/lib.rs`),
|
||||
since 0.3.0 (2026-11-16).
|
||||
`IDENTITY_OID = 1.3.6.1.4.1.67681.1.1` (`crates/bakashrot-pki/src/lib.rs`).
|
||||
|
||||
## The branches
|
||||
|
||||
@@ -29,17 +28,6 @@ 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.
|
||||
|
||||
## Before 0.3.0: a placeholder
|
||||
|
||||
Up to 0.2.0 the OID was `1.3.6.1.4.1.32473.1.1`, under PEN 32473, "Example
|
||||
Enterprise Number for Documentation Use" (RFC 5612), and `bakashrot-cert`
|
||||
warned whenever it made a certificate. **Those certificates aren't read
|
||||
any more** ("no BakaShrot identity"): make the CA's again or keep it (a
|
||||
CA has no identity extension), issue every server's and node's again.
|
||||
|
||||
`OldSource/`'s UUID arc (`2.25.2320...0981`) couldn't be used: `rcgen`
|
||||
writes OID parts of 64 bits at most, a UUID is 128.
|
||||
|
||||
## Changing the registration
|
||||
|
||||
The registry lists the organization, the contact's name and the contact's
|
||||
|
||||
+4
-36
@@ -1,10 +1,7 @@
|
||||
# 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).
|
||||
The code is `crates/bakashrot-proto`; this describes it.
|
||||
|
||||
**Status (2026-11-13):** packets, frames, names and error codes are written
|
||||
and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`,
|
||||
@@ -123,6 +120,7 @@ An attachment C: GetAttachment(from_part) S: Attachment, then Attachme
|
||||
Replicating P: SyncStateRequest S: SyncState
|
||||
P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
|
||||
P: ReplicateAttachment x missing S: Continue / RequestRefused
|
||||
(NotReady: another peer sending it)
|
||||
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused
|
||||
```
|
||||
|
||||
@@ -141,8 +139,6 @@ Replicating P: SyncStateRequest S: SyncState
|
||||
|
||||
## 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,
|
||||
@@ -152,33 +148,5 @@ The same as protocol 6:
|
||||
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.
|
||||
- **Error codes** (`error`): 1-99 refusals, 100+ the client's own, never
|
||||
renumbered.
|
||||
|
||||
+61
-60
@@ -16,8 +16,9 @@ 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"):
|
||||
the database, the topics and the roles. A system clock before 1970
|
||||
is refused at start (messages are stamped with it, `pushed_at`).
|
||||
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
|
||||
@@ -25,10 +26,9 @@ the database, the topics and the roles. Decided 2026-11-14
|
||||
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.
|
||||
- **No console commands:** it needs no console, a service manager runs
|
||||
it as is. Listing names is `bakashrot list`, restarting 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
|
||||
@@ -77,7 +77,7 @@ beside it, on `debian:trixie-slim`, as uid 10001.
|
||||
| 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 |
|
||||
| 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; no file: nothing revoked, warned |
|
||||
| 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) |
|
||||
|
||||
@@ -127,7 +127,7 @@ otherwise:
|
||||
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).
|
||||
instead of sent again at every check-in.
|
||||
|
||||
**Receiving** (`accept_from.rs`): replication requests are answered only
|
||||
if the connection comes from `accept_from` (a hostname looked up at its
|
||||
@@ -141,8 +141,15 @@ 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
|
||||
- **One peer at a time per attachment** (2026-11-16): another asking for
|
||||
the same one meanwhile is refused (`NotReady`) and offers it again at
|
||||
its next check-in. Two at once could both be refused a part while
|
||||
every part got stored, the attachment left whole and never checked.
|
||||
- **Never taken unchecked:** one whole but not checked (finishing it
|
||||
failed) is listed in `SyncState` from its first part and started over
|
||||
when a peer asks for it, warned in the log.
|
||||
|
||||
**One server per node** stays the config's rule (`known-issues.md`): a node pushing to two servers that replicate makes
|
||||
the same ids with different messages, undetected.
|
||||
|
||||
## A connection
|
||||
@@ -238,6 +245,9 @@ server's, `ConnectionLost`, `ProtocolError`, `InvalidArgument`,
|
||||
|
||||
## Measured
|
||||
|
||||
`bench.ps1` at the root runs these benchmarks (`-Only push,replication`,
|
||||
`-Sync full|normal`; the variables below from the environment).
|
||||
|
||||
`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.
|
||||
@@ -252,8 +262,8 @@ each, 200-byte JSON, 20,000 pushes per client.
|
||||
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.
|
||||
Through Python and the DLL, about 10,700 pushes/s, 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
|
||||
@@ -263,52 +273,47 @@ each, 200-byte JSON, 20,000 pushes per client.
|
||||
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)
|
||||
### Through the DLL, Python and the tools (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
|
||||
Release builds, one server on localhost. Pushes and reads through
|
||||
Python and the 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` | `normal` |
|
||||
|---|---|---|
|
||||
| One tool command, connecting included | 12 ms | 11 ms |
|
||||
| Pushes, 1 client | 1,954/s | 11,600-13,100/s |
|
||||
| Pushes, 10 clients | 10,072/s | 56,200-64,300/s |
|
||||
| Reads, Python | 130,861/s | 146,368/s |
|
||||
| The tool writing 120,000 messages to a file | | 0.14 s |
|
||||
| A 200 MB attachment up, the tool | 1.15 s | 1.15 s |
|
||||
| The same down | 0.59 s | 0.67 s |
|
||||
|
||||
- **`full`, one client:** both wait for the disk's flush at every push.
|
||||
- **`full`, one client:** it waits 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.
|
||||
ends, cost about 7 ms; aws-lc's CPU Jitter Entropy seeding cost 25 ms
|
||||
more per process before it was turned off (`certificates.md`, "TLS").
|
||||
|
||||
### Replication, against the old server (2026-11-14)
|
||||
### Replication (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
|
||||
`replication_rate` (`tests/end_to_end.rs`, ignored by default): 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.
|
||||
JSON, the same machine, the pushers `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 |
|
||||
| | `full` | `normal` |
|
||||
|---|---|---|
|
||||
| Pushes, all 4 servers | 16,000-16,300/s | 35,300-37,500/s |
|
||||
| Slowest push | 50-57 ms | 420-510 ms |
|
||||
| Behind when the pushes stop (most of a server) | 0 | 0.3-0.9 s |
|
||||
| Until every server has everything | 0.3 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
|
||||
it waited `sync_interval` after every check-in, 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
|
||||
- **`batch_size` 1000** (was 100): `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`:
|
||||
@@ -320,25 +325,21 @@ client, the new one's `bakashrot-client` threads in the test's process.
|
||||
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,
|
||||
- runs of messages: 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
|
||||
- big messages: 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
|
||||
- attachments: 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
|
||||
- attachment edges (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
|
||||
- queries: 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);
|
||||
@@ -351,12 +352,9 @@ each:
|
||||
- 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
|
||||
- retention: 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
|
||||
- replication: 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
|
||||
@@ -368,8 +366,11 @@ each:
|
||||
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;
|
||||
- two peers, one attachment (two raw connections): the second refused
|
||||
while the first sends it (names in any case), the first finishing it;
|
||||
one gone partway, the other going on from there; one whole but never
|
||||
checked asked for from its first part and started over;
|
||||
- `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`).
|
||||
The tool's own (`--follow`, the output): `client.md`.
|
||||
|
||||
+40
-74
@@ -5,9 +5,6 @@ The server's database: one SQLite file. The code 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
|
||||
@@ -17,7 +14,7 @@ The server's database: one SQLite file. The code is
|
||||
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").
|
||||
the pushes of a layout with an index, 30% less disk (see "Measured").
|
||||
- **One writer, many readers** (WAL). Writes go in batches, one
|
||||
transaction each: a group commit.
|
||||
|
||||
@@ -65,8 +62,8 @@ attachment_parts.key = attachment_id << 20 | part
|
||||
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.
|
||||
Why no index? A second B-tree to write at every push, and reads going
|
||||
through the index then to the row. Measured below.
|
||||
|
||||
## Writing
|
||||
|
||||
@@ -85,7 +82,6 @@ together, one disk flush for all.
|
||||
| `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
|
||||
@@ -108,8 +104,7 @@ read while the writer writes. Answers are the protocol's own types:
|
||||
| `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. A topic is never unknown: it's allowed or not, by the roles.
|
||||
in any topic: `Error::UnknownName`. A topic is never unknown: it's allowed or not, by the roles.
|
||||
|
||||
## Attachments
|
||||
|
||||
@@ -148,7 +143,7 @@ connection's next queries (found 2026-11-15). 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
|
||||
function on a row that isn't) gets a hint: add
|
||||
`is_json = 1` to the WHERE.
|
||||
|
||||
The `messages` view, by name:
|
||||
@@ -156,7 +151,7 @@ The `messages` view, by name:
|
||||
| Column | |
|
||||
|---|---|
|
||||
| `topic`, `node` | names |
|
||||
| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | as in v8 |
|
||||
| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | the message's |
|
||||
| `attachment_size`, `attachment_state` | NULL without one |
|
||||
|
||||
```sql
|
||||
@@ -170,7 +165,7 @@ SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_js
|
||||
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
|
||||
- `browse` / `browse_messages`: for database tools (set `browse`'s
|
||||
one row, open the view); no dropdowns any more.
|
||||
|
||||
## The file
|
||||
@@ -181,7 +176,7 @@ SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_js
|
||||
- **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.
|
||||
one 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
|
||||
@@ -195,74 +190,58 @@ 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 |
|
||||
| | v9 (this) | v9 + a time index |
|
||||
|---|---|---|
|
||||
| Pushes/s | **23k** | 9-10k |
|
||||
| File | **330 MB** | 457 MB |
|
||||
| Latest 100 of a stream | 0.05 ms | 0.05 ms |
|
||||
| 1000 after an id | 0.53 ms | 0.53 ms |
|
||||
| Retention, 10% of a topic | 5.5 ms | 6.4 ms |
|
||||
| Query: a node's last hour | 1.65 ms | 0.90 ms |
|
||||
| Query: a topic's last hour | 8.4 ms | 4.7 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,
|
||||
each costs about a page written to the WAL. Any index per stream (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 benchmark (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:
|
||||
`storage_rate` (`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.
|
||||
--ignored --nocapture`, or `bench.ps1 -Only storage`): the 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. 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** |
|
||||
| | 1M | 1M `full` | 5M |
|
||||
|---|---|---|---|
|
||||
| Pushes/s | 37,332 | 29,952 | 29,363 |
|
||||
| File | 249 MB | 249 MB | 1,239 MB |
|
||||
| Latest message | 0.017 ms | 0.017 ms | 0.017 ms |
|
||||
| 1000 after an id | 0.43 ms | 0.43 ms | 0.45 ms |
|
||||
| Retention, 10% of a topic | 7 ms | 9 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).
|
||||
`normal` unless said. Most of the push speed is the writer's: checkpoints
|
||||
off the push path (`Database::checkpointer()`, every second on its own
|
||||
connection, the writer only checkpointing itself past 10,000 pages,
|
||||
`WRITER_CHECKPOINT_PAGES`), and no savepoint around a push (a failed one
|
||||
leaves at most its empty stream).
|
||||
|
||||
## 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
|
||||
(another program's, 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),
|
||||
on, attachments purged in batches),
|
||||
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.
|
||||
@@ -276,16 +255,3 @@ big), the view's plans, and readers with two writers at once. In
|
||||
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 |
|
||||
|
||||
+15
-7
@@ -15,7 +15,7 @@ Create a blank one and all the following sections.
|
||||
|
||||
### Server's base config
|
||||
```toml
|
||||
# All paths are relative to CWD unless they're absolute.
|
||||
# All paths are relative to this file's folder unless they're absolute.
|
||||
[server]
|
||||
listen = "0.0.0.0:7000" # Used when binding.
|
||||
|
||||
@@ -24,7 +24,8 @@ certificate = "server-1.crt"
|
||||
key = "server-1.key"
|
||||
|
||||
# The watched CA's CRL.
|
||||
# The CRL checks will be disabled if not given, the program will exit if given and non-existent.
|
||||
# Not given: no CRL checks. Given but not there yet: nothing revoked (a warning is logged),
|
||||
# and it's picked up once it appears.
|
||||
#crl = "ca.crl"
|
||||
|
||||
database = "bakashrot.sqlite"
|
||||
@@ -34,6 +35,11 @@ database = "bakashrot.sqlite"
|
||||
# second or so. ("off" isn't allowed.)
|
||||
synchronous = "full"
|
||||
|
||||
# Replication cut partway through an attachment resumes once the peer has
|
||||
# read back and hashed what it already has, in 30 s at most: up to about
|
||||
# 4 GB received on a hard disk, 15 GB on a SATA SSD, 30-60 GB on NVMe
|
||||
# (estimates). Past that, resuming fails at every retry: keep attachments
|
||||
# well under it (more than a few GB is a lot for this anyway).
|
||||
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
|
||||
retention_interval = "1m" # how often old messages are deleted
|
||||
```
|
||||
@@ -47,17 +53,19 @@ retention_interval = "1m" # how often old messages are deleted
|
||||
push_to = [] # Servers we'll actively connect to.
|
||||
# Example: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
|
||||
accept_from = [] # Connecting servers must have these origins, otherwise we abort.µ
|
||||
accept_from = [] # Connecting servers must have these origins, otherwise we abort.
|
||||
# Example: ["10.0.0.2", "server-2.lan"], or ["*"]
|
||||
|
||||
retry_delay = "10s"
|
||||
sync_interval = "5s"
|
||||
sync_interval = "5s" # keep it under 5 min: a link idle that long is closed
|
||||
batch_size = 1000 # messages per packet, 1-10000
|
||||
```
|
||||
|
||||
|
||||
### Roles section
|
||||
```toml
|
||||
# A database holds 1,048,575 topic and node pairs at most, all topics together,
|
||||
# never freed: patterns like "*" in push_topics let clients make as many as they like.
|
||||
[roles.sensor]
|
||||
push_topics = ["sensors.*"] # always as its own node (its name)
|
||||
read_topics = ["*"]
|
||||
@@ -69,8 +77,8 @@ list_topics = false # true: lists every topic (query does too)
|
||||
list_nodes = false # true: lists every node (query does too)
|
||||
|
||||
# Only relevant when replicating.
|
||||
send_nodes = ["*"] # Replicates all known topics (Default)
|
||||
accept_nodes = ["*"] # Accepts al foreign topics (Default)
|
||||
send_nodes = ["*"] # Replicates every node's messages (Default)
|
||||
accept_nodes = ["*"] # Accepts every foreign node's messages (Default)
|
||||
```
|
||||
|
||||
#### Remarks:
|
||||
@@ -86,7 +94,7 @@ accept_nodes = ["*"] # Accepts al foreign topics (Default)
|
||||
|
||||
> **Log Processor:**
|
||||
> ```toml
|
||||
> [roles.sensor]
|
||||
> [roles.log-processor]
|
||||
> push_topics = ["alerts.sensors.*"]
|
||||
> read_topics = ["sensors.*"]
|
||||
> ```
|
||||
|
||||
+1
-1
@@ -20,4 +20,4 @@ key = "node-viewer.key"
|
||||
|
||||
* `server`: the server's IP or hostname, and its `listen` port.
|
||||
* `bakashrot.exe` reads `client.toml` from the current folder, `-c viewer.toml` for another one.
|
||||
* Optional: `crl = "ca.crl"`, to refuse a revoked server.
|
||||
* Optional: `crl = "ca.crl"`, to refuse a revoked server (a file not there yet revokes nothing).
|
||||
|
||||
@@ -1,121 +1,69 @@
|
||||
# BakaShrot
|
||||
A message store with replication.
|
||||
A vibe-coded and opinionated message store built on SQLite, with replication between servers.
|
||||
|
||||
Servers take messages (usually JSON) per topic and node from authenticated clients,
|
||||
store them in SQLite, and replicate them to other servers by topic and node name.
|
||||
|
||||
> [!NOTE]
|
||||
> Meant as an internal tool on trusted machines and networks.
|
||||
BakaShort allows applications and scripts to push/read data and files and let them replicate over an entire mesh regardless of whether the links are up or reliable. \
|
||||
It also allows to sleep easy knowing each client is strongly authenticated by using certificates over public networks.
|
||||
|
||||
|
||||
## Features
|
||||
* TLS 1.3 connections, both ends proving who they are with certificates from your own CA (`bakashrot-cert`)
|
||||
* Replication between servers, by topic and node names
|
||||
* Attachments, one per message, 1 GB by default
|
||||
* Per-topic retention
|
||||
* Read-only SQL queries on the stored messages
|
||||
|
||||
* Cert-based authentication with TLS 1.3 connections
|
||||
* Easy tools provided to manage it and CRL-based revocations.
|
||||
* Role-based scoping of push and reads baked into certificates.
|
||||
* Directional replication between servers, either complete or by topic and node names.
|
||||
* File replication, one per message, up to 1 GiB by default with resumable replication.
|
||||
* Per-topic and per-server retention of messages and files.
|
||||
* Edge can be configured to minutes while internal can hold years independently.
|
||||
* Read-only SQL queries on stored JSON messages.
|
||||
* Every push flushed to disk before it's answered, or about twice the pushes with `synchronous = "normal"`
|
||||
* Supports Windows and Linux, both on x64 and ARM64.
|
||||
* Clients:
|
||||
* A C library (`bakashrot.dll`, `libbakashrot.so`), with a C header and PureBasic prototypes
|
||||
* A CLI tool to push, read, query and list
|
||||
* A Python module over the library, without dependencies, as a wheel with the library in it
|
||||
|
||||
See [revamp.md](revamp.md) for why it was rewritten in Rust, what was decided, and the plan.
|
||||
The PureBasic version it replaced (protocol 6) is in the git history: `OldSource/`, up to commit `68966a8`.
|
||||
|
||||
## Limitations
|
||||
The main ones, all in [docs/known-issues.md](docs/known-issues.md) with what's left as it is and why:
|
||||
|
||||
* No replication consensus. *(See [Why not something else](#why-not-something-else))*
|
||||
* Peers are trusted with what they replicate, and clients only scope restrictions based on their role.
|
||||
* Only 1,048,575 topic and node pairs can exist per database.
|
||||
* Clients poll for new messages themselves.
|
||||
|
||||
|
||||
## Building
|
||||
Requires [rustup](https://rustup.rs) (it installs the pinned toolchain, [rust-toolchain.toml](rust-toolchain.toml),
|
||||
by itself; on Windows, Visual Studio's C++ tools for the linker) and Python 3.11+ for releases.
|
||||
## Quick Start
|
||||
All instructions to setup a BakaShrot network can be found in [guides/](guides/).
|
||||
|
||||
From the repository's root, on Windows (`powershell -ExecutionPolicy Bypass -File <script>`):
|
||||
|
||||
| Script | What it does |
|
||||
|---|---|
|
||||
| `build.ps1` | Builds everything, release mode, into `target\release\` |
|
||||
| `test.ps1` | What CI runs: formatting, clippy (warnings are errors), the tests, the docs |
|
||||
| `release.ps1` | A release for this platform, smoke-tested (`release.py`, below); `-SkipTest` |
|
||||
| `clean.ps1` | Deletes `target\` (builds and releases) |
|
||||
|
||||
Elsewhere, the same with cargo: `cargo build --release`, `cargo test`, `python release.py`, `cargo clean`.
|
||||
Generated keys and certificates never go in git.
|
||||
It should take you 5-10 minutes if you test without docker, and maybe 10-15 minutes if you use a dockerized server.
|
||||
|
||||
|
||||
## Layout
|
||||
A Cargo workspace:
|
||||
## Why not something else
|
||||
|
||||
```
|
||||
Cargo.toml the workspace: shared lints, release profile
|
||||
rust-toolchain.toml the pinned toolchain (1.100.0)
|
||||
build.ps1, test.ps1, release.ps1, clean.ps1
|
||||
release.py a release for this platform: build, package, smoke test
|
||||
docs/ designs across crates: protocol.md, certificates.md, oid.md, config.md,
|
||||
storage.md, server.md, client.md, known-issues.md, lab.md (a test lab, step by step)
|
||||
crates/
|
||||
bakashrot-proto/ packets, frames, names, limits, error codes, shared by everything
|
||||
bakashrot-pki/ certificates: issuing, identities, CRLs, the TLS setup
|
||||
bakashrot-config/ the server's config (TOML): retention, replication, roles
|
||||
bakashrot-storage/ SQLite, schema v9: the writer, reads, attachments, queries
|
||||
bakashrot-server/ the server: TLS, identities, requests, the writer thread (and its program)
|
||||
bakashrot-client/ the client library, Rust API, blocking
|
||||
bakashrot-capi/ the C DLL over bakashrot-client: the BakaShrot_* exports (bakashrot.dll)
|
||||
bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert
|
||||
bindings/
|
||||
c/ bakashrot.h, generated from bakashrot-capi
|
||||
purebasic/ the prototypes and error codes, as the PureBasic version's
|
||||
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py
|
||||
.cargo/config.toml the C runtime linked statically on Windows
|
||||
docker/ the server's image: Dockerfile, compose.yml, test.sh
|
||||
```
|
||||
### Replicated SQL/SQLite DB
|
||||
Projects like [rqlite](https://github.com/rqlite/rqlite) and [dqlite](https://github.com/canonical/dqlite) could have been perfect for what BakaShrot tries to accomplish. \
|
||||
They require a leader, a constant S2S connection, and do not support split networks by design.
|
||||
|
||||
Dependencies only point downward: `proto`, `pki`, `config` and `storage` don't open sockets and are tested
|
||||
on their own; `server` and `client` use them; the DLL and the tools only use `client`.
|
||||
In contrast, BakaShrot moves trust off the server mesh itself and assumes you properly set up each node with a unique name and cert to prevent conflicts.
|
||||
|
||||
This prevents you from properly load-balancing, letting untrusted users push messages, and whatnot. \
|
||||
But you gain the ability to host a message-server network over unreliable links without losing a single bit of data.
|
||||
|
||||
## Releases
|
||||
`python release.py` (or `release.ps1`) on Windows or Linux, x64 or ARM64, builds that platform's release into
|
||||
`target/dist/bakashrot-<version>-<platform>/` and its archive (`.zip`, `.tar.gz`):
|
||||
the server, `bakashrot`, `bakashrot-cert`, the client library with its C header and PureBasic prototypes,
|
||||
`bakashrot.py` and a wheel with the library in it (`bindings/python/make_wheel.py`), the example configs,
|
||||
`docs/`, a `README.txt`, the licenses (`THIRD-PARTY.txt`: every crate built in, from `cargo metadata`).
|
||||
### MQTT Brokers
|
||||
[Mosquitto](https://mosquitto.org) and other MQTT brokers handle the topic-based messaging in a near-perfect way, but they only deliver messages to whoever is subscribed at that moment, and have limited archival options. \
|
||||
BakaShrot keeps every message, and allows you to re-read them days or years later.
|
||||
<!-- And compared to mosquitto, you won't want to jump off a bridge while setting it up. -->
|
||||
|
||||
Then it checks it, in the folder's `_test/`: a CA and certificates, the server on a free port,
|
||||
the tool pushing (an attachment too), reading back, listing and querying, Python through the library
|
||||
and the wheel installed by pip, the server stopped by SIGTERM (Ctrl+Break on Windows),
|
||||
which must end cleanly (`_test/` kept if not). `--skip-test` skips it.
|
||||
### Other message stores
|
||||
Projects like **Kafka, NATS JetStream** are a good alternative to BakaShrot if you have the infrastructure and resources to host them.
|
||||
|
||||
CI ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on a version tag (`v*`) or by hand: `test.ps1`'s checks
|
||||
on Windows and Linux, then a release on each of Windows x64 and ARM64, Linux x64 and ARM64, each on its own
|
||||
kind of machine (so its smoke test runs there), its archive kept as the run's artifact. The Linux ones build
|
||||
in a manylinux 2.28 container, so they run with glibc 2.28 and later.
|
||||
The version is the workspace's (`Cargo.toml`), and `bindings/python/bakashrot.py`'s `__version__` must be the same.
|
||||
|
||||
The server's Docker image: `docker build -f docker/Dockerfile -t bakashrot-server .`, or CI's for amd64
|
||||
and arm64, checked by `docker/test.sh`, then pushed to `ghcr.io/aziascreations/bakashrot-server` on a tag
|
||||
(`<version>`, and `latest` unless it's a pre-release: `v0.2.0-test2` doesn't move it). Running it: `docs/server.md`, "In Docker". The package was first pushed by hand, so the
|
||||
workflow may push to it only with the repository given write access in its settings on GitHub
|
||||
("Manage Actions access"), once; the package made public there too.
|
||||
|
||||
Publishing:
|
||||
* **The wheel** to Gitea's registry, with twine 6.1+ (for the license metadata) and a token with `write:package`:
|
||||
`twine upload --repository-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi -u aziascreations <wheel>`
|
||||
* **On GitHub** (no Python registry), the archives and the wheels on a release:
|
||||
`gh release create v<version> --repo aziascreations/BakaShrot --title <version> <files>`
|
||||
(`gh release upload` for one that exists).
|
||||
|
||||
|
||||
## Conventions
|
||||
* LF line endings (`.gitattributes`; `.ps1` CRLF), rustfmt's defaults.
|
||||
* Every public item documented (`missing_docs`), no `unsafe` outside the C API crate.
|
||||
* A crate's root docs say what it does; designs that span crates go in `docs/`, updated with the code.
|
||||
* Use existing crates rather than reimplementing (MessagePack is `rmp-serde`).
|
||||
* Protocol changes update `docs/protocol.md`; error codes are never renumbered, packet ids never reused.
|
||||
* `OldSource/` paths in comments and docs: the PureBasic version, in git history up to commit `68966a8`.
|
||||
However, I don't have heaps of RAM to piss away on running a JVM or other stuff. \
|
||||
And BakaShrot, while simpler in all other aspect, takes less than 50 MB to run and can share any 1-2$ VPS with other applications very easily.
|
||||
|
||||
|
||||
## Cloning
|
||||
```
|
||||
git clone https://github.com/aziascreations/BakaShrot.git
|
||||
git clone https://git.nibblepoker.lu/aziascreations/BakaShrot.git
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -1,43 +1,18 @@
|
||||
# BakaShrot revamp
|
||||
|
||||
Started 2026-11-13: what it should change, what's decided, what's still
|
||||
open, and the plan. Steps 0 to 12 of the plan are done (the workspace,
|
||||
open, and the plan. Every step of the plan is done (the workspace,
|
||||
`bakashrot-proto`, `bakashrot-pki` and `bakashrot-cert`,
|
||||
`bakashrot-config`, `bakashrot-storage`, `bakashrot-server` and
|
||||
`bakashrot-client` answering every request, attachments included, the C
|
||||
DLL with its C, PureBasic and Python bindings, the `bakashrot` tool,
|
||||
retention, replication, operations and releases), see "Plan".
|
||||
|
||||
- **Old implementation:** PureBasic, protocol 6, schema v8. Removed on
|
||||
2026-11-15 ("The PureBasic version removed"): it's in git history,
|
||||
`OldSource/` up to commit `68966a8`, which the `OldSource/` paths here
|
||||
and in the code point to. What of its notes still holds:
|
||||
`docs/known-issues.md`.
|
||||
- **New implementation:** the Cargo workspace at the root (in `Source/`
|
||||
until 2026-11-15, so the paths below are relative to the root now),
|
||||
see `readme.md`.
|
||||
|
||||
## Why
|
||||
|
||||
The old code works and is well tested, but every new need costs a lot in
|
||||
PureBasic, which has no libraries for it:
|
||||
|
||||
- The connections' security is a custom protocol (sealed Hello, key
|
||||
exchange, signed transcript, own cipher framing,
|
||||
`OldSource/Design/Cryptography.md`), on libsodium.
|
||||
- The client auth rework needs X.509 certificates: that took writing a DER
|
||||
reader/writer and an X.509 layer by hand (`OldSource/Commons/Cryptography/Der.pbi`,
|
||||
`X509.pbi`, `OldSource/Design/Certificates.md`), and TLS would still be
|
||||
missing.
|
||||
- Threading traps (lists shared between threads, a listener racing client
|
||||
threads, item 21), compiler quirks (5.73's `Goto` out of a `Select`),
|
||||
single-pass includes: see `OldSource/CLAUDE.md`, "Traps".
|
||||
retention, replication, operations and releases, then the finish: one
|
||||
test runner, CI, Docker, `bench.ps1`), see "Plan".
|
||||
|
||||
## Decided
|
||||
|
||||
1. **Rust**, for the server, the client library and DLL, and the tools: one
|
||||
Cargo workspace (in `Source/`, at the root since 2026-11-15). Built in
|
||||
the order of "Plan" below.
|
||||
Cargo workspace at the root. Built in the order of "Plan" below.
|
||||
2. **A C-compatible client DLL**, usable from any language as today: the
|
||||
same kind of exports (`BakaShrot_*A/W`, cdecl), the same conventions
|
||||
(strings copied into the caller's buffers, the size needed returned,
|
||||
@@ -97,8 +72,7 @@ Also decided (2026-11-13):
|
||||
- Cipher suite: **TLS13_AES_256_GCM_SHA384** only.
|
||||
- Key exchange: **X25519MLKEM768** only, the X25519 + ML-KEM hybrid
|
||||
(holds against quantum computers too).
|
||||
- Crypto backend: **aws-lc-rs**, the one with ML-KEM (its Windows build
|
||||
to check at step 2: it may want CMake and NASM).
|
||||
- Crypto backend: **aws-lc-rs**, the one with ML-KEM.
|
||||
- The client's certificate is encrypted too: watchers still don't learn
|
||||
who connects. Peers the same way, one certificate each instead of a
|
||||
peer section plus a client section on the other server.
|
||||
@@ -109,9 +83,7 @@ Also decided (2026-11-13):
|
||||
roles are free strings with the name rules, their meaning in the
|
||||
server's config. Only the server reads it. Its OID is
|
||||
`1.3.6.1.4.1.67681.1.1`, under NibblePoker's PEN (2026-11-16,
|
||||
`docs/oid.md`; a placeholder until then; the UUID arc of
|
||||
`OldSource/` can't be used: `rcgen` writes OID parts of 64 bits at
|
||||
most);
|
||||
`docs/oid.md`);
|
||||
- the name again as the subject's CN, for people (`openssl x509 -text`,
|
||||
logs); the server only trusts the extension;
|
||||
- extended key usage `clientAuth` for clients, `serverAuth` and
|
||||
@@ -135,14 +107,20 @@ Also decided (2026-11-13):
|
||||
drops the connections whose certificate it now revokes;
|
||||
- a new file that doesn't verify is refused, the previous one kept and
|
||||
the refusal logged; no file means nothing revoked;
|
||||
- **a CRL file that isn't there** (2026-11-16): nothing revoked, on
|
||||
both ends, never blocking, where it's a setting: the server's
|
||||
config (warned in its log: a CRL deleted by mistake) and
|
||||
`client.toml` (the tool, Python's `from_file()`). A path given
|
||||
to the DLL's `SetCrl` or Python's `Client(crl=...)` is asked for
|
||||
explicitly: missing, it's a `FileError`. `bakashrot-cert revoke`
|
||||
needs no file to start from (it writes the first one). A file
|
||||
that's there but can't be read or isn't the CA's is refused;
|
||||
- clients check it too when given one (`client_config()` takes the
|
||||
same revocations): a server dialing its peer is a client, so servers
|
||||
block each other whichever end dials;
|
||||
- revoked by certificate, not by name: each certificate has its own key
|
||||
and serial number, so two servers of the same name each have theirs,
|
||||
revoked one at a time (`bakashrot-cert issue --file`);
|
||||
- optionally, a node blocked by name in the config, whatever certificate
|
||||
it has (emergencies, a node taken down).
|
||||
revoked one at a time (`bakashrot-cert issue --file`).
|
||||
- **The server's config is TOML** (2026-11-13), `docs/config.md`:
|
||||
- `[server]`, `[retention]`, `[replication]`, `[roles.<name>]`; unknown
|
||||
keys refused; names only (no ids, pins or ranges);
|
||||
@@ -156,8 +134,7 @@ Also decided (2026-11-13):
|
||||
- **no peer sections:** peers are roles too (replicating with a server
|
||||
whose certificate has a role with `send_topics` / `accept_topics`,
|
||||
whichever end dials); the config only lists the addresses it dials
|
||||
(`[replication] peers`; `push_to` and `accept_from` since 2026-11-14,
|
||||
"Replication by address" below);
|
||||
(`[replication] push_to`, "Replication by address" below);
|
||||
- **no default topic** (dropped from the protocol too, 2026-11-13): a
|
||||
push always names its topic;
|
||||
- **the roles are the only lists of topics** (2026-11-16): `[server]
|
||||
@@ -168,9 +145,7 @@ Also decided (2026-11-13):
|
||||
and is read, listed (`ListNames`: the topics with messages) and
|
||||
sent on by the roles that name it. So a topic that only came from a
|
||||
peer is read like any other, and a push to a topic nobody names is
|
||||
`NotAllowed` (`UnknownName` is only for nodes now). Before: `topics`
|
||||
since 2026-11-13, `replicated_topics` to filter on edge nodes (now
|
||||
their peers' `send_topics`);
|
||||
`NotAllowed` (`UnknownName` is only for nodes now);
|
||||
- **`list_topics` and `list_nodes`** (2026-11-16), two booleans of a
|
||||
role, for a tool that browses a server: listing answers every topic,
|
||||
every node with messages. Without them (or `query`, which gives
|
||||
@@ -298,72 +273,40 @@ Also decided (2026-11-13):
|
||||
|
||||
## Proposed, to confirm
|
||||
|
||||
Nothing at the moment.
|
||||
|
||||
Noted, not planned (dropped 2026-11-13): **typed query results**, numbers as
|
||||
numbers in `QueryResult`'s JSON instead of protocol 6's strings. Messages
|
||||
come back as text either way; only what SQL computes would gain
|
||||
(`COUNT(*)`, ids, `data->>'$.x'`). Query results stay strings, as before.
|
||||
- **A GUI explorer** (2026-11-16, set aside for later): likely **egui**
|
||||
(`eframe`), the owner leaning to it. One exe in the workspace over
|
||||
`bakashrot-client`, Windows and Linux, MIT/Apache (Slint's GPLv3 or
|
||||
attribution license weighed against the CC0 project; a Win32 `.rc`
|
||||
dialog would be Windows only). To start it: a short spec from the
|
||||
owner (goal, connecting, a layout sketch, now / later / never,
|
||||
details such as times and paging, done when).
|
||||
|
||||
## Open questions
|
||||
|
||||
- **A handle-based DLL API** (several connections per process, old open item
|
||||
10): later maybe, the owner's call (one connection per process for now).
|
||||
|
||||
## Kept: the behaviour to carry over
|
||||
|
||||
Described in the old version's `OldSource/Notes.md` and
|
||||
`OldSource/Design/`, tested by `OldSource/Tests/` (git history, see the
|
||||
top):
|
||||
|
||||
- Topics and nodes by name, each server with its own ids (now in its
|
||||
database only), wildcards, `PushTopics` / `ReadTopics`, `SendTopics` /
|
||||
`AcceptTopics`, `SendNodes` / `AcceptNodes` (`Packets.md`, "Topics and
|
||||
nodes").
|
||||
- Requests: push (JSON or not, `is_json`), latest, runs of messages after
|
||||
an id (one request now), list names, read-only SQL (`Packets.md`, "Client
|
||||
requests"; the three read-only guards).
|
||||
- Replication by name: sync state, batches of ~64 KB, only what's named on
|
||||
both sides, then attachments (`Packets.md`, "Replication").
|
||||
- `pushed_at` stamped on arrival, carried by replication; retention per
|
||||
topic and server (`Notes.md`, "pushed times, retention").
|
||||
- Attachments: one per message, 1 MB parts, SHA-256, replicated after
|
||||
their message (`Design/Attachments.md`); streamed inside the push now.
|
||||
- Limits: 16 MB messages, the reply batch sizes, 1 G attachments by default.
|
||||
- Error codes: the same numbers and meanings
|
||||
(`OldSource/Client/BakaShrot_ErrorCodes.pbi`); refuse vs abort; at least
|
||||
once delivery, nothing reconnects by itself.
|
||||
- Storage: one writer, WAL, `Synchronous = FULL` by default, `node_heads`
|
||||
so ids never go back, the `messages` and `browse` views
|
||||
(`Design/StorageConcurrency.md`).
|
||||
- Docker image, release zip, Python wheel (`Design/Release.md`,
|
||||
`OldSource/Docker/`). Not the console commands (dropped 2026-11-14,
|
||||
"Operations").
|
||||
|
||||
## The old open items
|
||||
|
||||
From `OldSource/Notes.md`, "Open items":
|
||||
The PureBasic version's, still not fixed:
|
||||
|
||||
- **Gone by design:** the custom crypto and its small issues (items 15-16),
|
||||
keys in plain-text inis as the identity (13, partly: private keys still
|
||||
sit in files), the console requirement (1: signals, no console commands), the list and
|
||||
threading traps, the 5.73 quirks.
|
||||
- **To carry over and fix:** a corrupted stored attachment re-sent forever
|
||||
(3, the proposed fix is written there); gaps in a pair's ids not detected
|
||||
(6); the sync state in one packet (9); warn once about dropped names; a
|
||||
leading BOM dropped from messages (22): store the bytes as sent; a NUL
|
||||
cutting a message in Python (23): pass lengths, not C strings.
|
||||
- **Still true:** peers trusted with what they replicate (12), unless
|
||||
messages get signed by their origin; rotation (14) becomes reissuing
|
||||
certificates.
|
||||
- **Gaps in a topic and node's ids** aren't detected on replication (6),
|
||||
and **`SyncState` is one packet** (9): `docs/known-issues.md`.
|
||||
- **Peers are trusted with what they replicate** (12), unless messages
|
||||
get signed by their node: `docs/known-issues.md`.
|
||||
- **Names left out of replication aren't warned about:** a topic or
|
||||
node one side doesn't take is skipped silently. Warn once per peer
|
||||
and name, again only when that changes (a log line at every check-in
|
||||
would spam).
|
||||
- **A NUL cuts a message from Python** (23): `push()` passes it to
|
||||
`PushMessageToA` as a C string, `"a\x00b"` is stored as `a`. Refuse
|
||||
it in `push()`, or pass a length.
|
||||
|
||||
## Plan
|
||||
|
||||
Decided 2026-11-13. The crates without networking first, each tested on
|
||||
its own; then one thin path through all of them; then one feature at a
|
||||
time, through every layer at once, with its tests and docs. The old suites,
|
||||
ported, say when a step is done; `OldSource/` stayed runnable to compare
|
||||
until step 13 (removed 2026-11-15).
|
||||
time, through every layer at once, with its tests and docs.
|
||||
|
||||
Dependencies only point downward:
|
||||
|
||||
@@ -375,416 +318,27 @@ proto pki config storage no networking, tested on their own
|
||||
capi (DLL) tools thin layers over client
|
||||
```
|
||||
|
||||
Error codes, limits and name rules live in `proto` only; the C, PureBasic
|
||||
and Python constants get generated from it (protocol 6 had them copied by
|
||||
hand in each).
|
||||
Error codes, limits and name rules live in `proto` only. The C header is
|
||||
generated from the DLL; the PureBasic and Python constants are written
|
||||
by hand.
|
||||
|
||||
| # | Step | What | Done when | Decide first | Status |
|
||||
|---|---|---|---|---|---|
|
||||
| 0 | Workspace | Cargo workspace, pinned toolchain, `test.ps1`, CI (fmt, clippy, test, doc) | The crates build, the checks pass | Crate names | Done 2026-11-13 |
|
||||
| 1 | `bakashrot-proto` | Names, error codes, limits, every packet, frames | Round trips, refusals, random input never panics | The packet format | Done 2026-11-13, simplified the same day |
|
||||
| 2 | `bakashrot-pki` + certificate tool | CA, server, client, peer certificates (P-384, the identity extension); name and roles read; the TLS setup (AES-256-GCM, X25519MLKEM768, the fixed server name); CRLs and their reload | `openssl verify` takes the tool's certificates; a TLS test accepts and refuses the right ones, a revoked one dropped | Decided 2026-11-13 | Done 2026-11-13 |
|
||||
| 3 | `bakashrot-config` | Server config: topics, roles to permissions, peers, retention, clear errors | `schema.ini`'s cases, the configs `Names-Test` refuses | TOML, roles (decided 2026-11-13) | Done 2026-11-13 |
|
||||
| 3 | `bakashrot-config` | Server config: topics, roles to permissions, peers, retention, clear errors | Every setting and refusal tested, each with its line | TOML, roles (decided 2026-11-13) | Done 2026-11-13 |
|
||||
| 4 | `bakashrot-storage` | Schema v9, one writer, reads, names, attachments' states, query guards | Every request's SQL tested; concurrent writes; an old database refused | v9 (decided 2026-11-13) | Done 2026-11-13 |
|
||||
| 5 | First path end to end | Server: TLS, identity from the certificate, `Welcome`, push and latest. Client library: the same | A Rust test pushes and reads back over TLS, a server on a free port | Decided 2026-11-13 | Done 2026-11-13 |
|
||||
| 6 | The other requests | Runs of messages, names, queries, refusals with codes, 16 MB limits | `GetMessages-Test`, `BigMessages-Test`, ported | | Done 2026-11-13 |
|
||||
| 7 | C DLL | The old exports over the client library, PureBasic prototypes, C header, `bakashrot.py` | `check_bakashrot.py` passes on it | Decided 2026-11-13 | Done 2026-11-13 |
|
||||
| 8 | Tools | push, get, get-messages `--follow`, query, list (resolve is gone: names only), reading `client.toml` | The tools' parts of the old suites | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 9 | Attachments | Every layer: packets, storage, upload and download, client, DLL, tools | `Attachments-Test`, `AttachmentEdges-Test` | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 10 | Retention | Background deletion, `node_heads` kept, attachments cleaned up | `Retention-Test`'s local checks | | Done 2026-11-14 |
|
||||
| 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | `Names-Test` (replication), `Restart-Test`; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 6 | The other requests | Runs of messages, names, queries, refusals with codes, 16 MB limits | Their end-to-end tests | | Done 2026-11-13 |
|
||||
| 7 | C DLL | The `BakaShrot_*` exports over the client library, PureBasic prototypes, C header, `bakashrot.py` | `check_bakashrot.py` passes on it | Decided 2026-11-13 | Done 2026-11-13 |
|
||||
| 8 | Tools | push, get, get-messages `--follow`, query, list (resolve is gone: names only), reading `client.toml` | The tools' end-to-end tests | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 9 | Attachments | Every layer: packets, storage, upload and download, client, DLL, tools | Every size and edge case, end to end | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 10 | Retention | Background deletion, `node_heads` kept, attachments cleaned up | Retention's end-to-end test | | Done 2026-11-14 |
|
||||
| 11 | Replication | Peer links, sync state, batches by name, wildcards, attachments, skipping on arrival | Three servers end to end, a restart; the corrupted-attachment fix | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 12 | Operations | Signals and a clean stop, logs, release, wheel | Runs unattended, stops cleanly, the release's smoke test | Decided 2026-11-14 | Done 2026-11-14 |
|
||||
| 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed against the old ~17,000 msg/s (4 servers, measured 2026-11-14: `docs/server.md`) | | |
|
||||
| 13 | Finish | One test runner (the Rust tests, decided 2026-11-15), end-to-end tests in CI, the bench, Docker | Push speed with 4 servers replicating (`docs/server.md`, "Measured") | | Done 2026-11-16 (`bench.ps1`) |
|
||||
|
||||
Each step ends with its tests passing and its docs updated (the crate's
|
||||
docs, `docs/`, this file's status), then a commit when the owner
|
||||
asks. Open questions get settled at the step that needs them.
|
||||
|
||||
### Done: steps 0 and 1 (2026-11-13)
|
||||
|
||||
- **Workspace** (`Source/`): `Cargo.toml` (edition 2024, shared lints:
|
||||
`unsafe_code` denied, docs required, clippy's defaults; release profile
|
||||
with LTO, `panic = "unwind"` for the DLL's `catch_unwind`),
|
||||
`rust-toolchain.toml` (1.100.0, rustfmt, clippy), `.gitattributes` (LF),
|
||||
`test.ps1` (fmt, clippy with warnings as errors, tests, docs),
|
||||
`../.github/workflows/ci.yml` (the same on Windows and Linux, Gitea
|
||||
Actions reads it too; not run yet, nothing pushed).
|
||||
- **`bakashrot-proto`**, on `serde`, `rmp-serde` and `serde_bytes`
|
||||
(first written over `rmp` with hand-written packets, then simplified the
|
||||
same day: names only, derived packets, 18 of them, streamed attachments;
|
||||
the packets' code about half of what it was):
|
||||
- `limits`, `error` (the protocol 6 numbers, one table for the enum,
|
||||
names and descriptions), `names` (names and wildcards: the old rules,
|
||||
tested case by case);
|
||||
- `frame`: blocking `read()` / `write()` for the DLL, and `codec()`
|
||||
(feature `tokio`): `tokio-util`'s codec set to the same frames, for the
|
||||
server (it replaced an own `Decoder`);
|
||||
- `packets`: one table for the 18 types, the `Packet` enum and its
|
||||
`serde` form, each packet's struct with its `Check`; decoding reads
|
||||
with buffers that grow with the data (never from an announced
|
||||
length), checks every rule and that nothing follows.
|
||||
- 25 tests: round trips of a sample of every type, golden bytes, every
|
||||
truncation and trailing byte refused, wrong shapes and types, ranges,
|
||||
ids in order, names everywhere, a 4 GiB binary announced, and 250,000
|
||||
random or mutated packets that never make it panic (0.4 s), the
|
||||
codec's frames the same as the blocking ones.
|
||||
- Reviewed once more: one text per error code, empty `Check`s by
|
||||
default, `Attachment::part_count()` / `part_len()` for the receivers,
|
||||
ALPN tied to the version by a test; the batch sizes (~1 MiB per
|
||||
`Messages`, ~64 KiB per `ReplicateMessages`) left the protocol crate,
|
||||
they're the server's to set (steps 6 and 11).
|
||||
- **`docs/protocol.md`**: protocol 7, every packet, the flows, what
|
||||
changed from 6.
|
||||
- **Left for later steps:** the TLS side of the protocol (ALPN, `Welcome`
|
||||
sent first: steps 2 and 5); generating the C, PureBasic and Python
|
||||
constants from `error` (step 7); a `cargo fuzz` target, if the random
|
||||
test ever misses something.
|
||||
|
||||
### Done: step 2 (2026-11-13)
|
||||
|
||||
`docs/certificates.md` has all of it.
|
||||
|
||||
- **`bakashrot-pki`**, on `rcgen`, `rustls` (aws-lc), `x509-parser`
|
||||
(`verify-aws`, the same aws-lc) and `yasna`:
|
||||
- `Identity`: the extension read and written, names and roles checked;
|
||||
- `Ca`: a new CA, loading one (refused if the key isn't its
|
||||
certificate's), issuing client and server certificates, `issued()`,
|
||||
CRLs; `summarize()` for people;
|
||||
- `Revocations`: a CRL's serial numbers, only taken if it's the CA's
|
||||
(issuer and signature checked); shared with the server's TLS setup, so
|
||||
replacing it takes effect at the next handshake;
|
||||
- `tls`: the server's and the client's rustls configurations at the
|
||||
strongest settings, rustls' own verifiers (the server's wrapped to
|
||||
check revocation and the identity), `peer_identity()`.
|
||||
- The server name is fixed (`bakashrot-server`, in every server's
|
||||
certificate) instead of a verifier of our own: rustls' checks it all.
|
||||
- **`bakashrot-tools`**: `bakashrot-cert` (`ca`, `issue`, `revoke`,
|
||||
`show`), never writing over a certificate or key, a CRL written aside
|
||||
then moved in place, revoking only the CA's certificates.
|
||||
- **18 tests:** handshakes in memory (the strongest settings negotiated,
|
||||
identities both ways, servers as their peers' clients; refused: another
|
||||
CA's client or server, a client posing as a server, a revoked client and
|
||||
taken again once the CRL changes, no identity, another protocol
|
||||
version), certificates and CRLs, OpenSSL agreeing (`verify` for clients
|
||||
and servers, the CRL, a revoked one; Git's OpenSSL found), the tool end
|
||||
to end.
|
||||
- **`aws-lc-rs` builds as it is** here (no CMake or NASM to install).
|
||||
- **Then (2026-11-13):** clients check the CRL too when given one, so
|
||||
servers block each other both ways; ALPN `bakashrot` with the versions
|
||||
exchanged right after TLS (`frame::write_version()` / `check_version()`,
|
||||
error `VersionMismatch`); `--file` for a second certificate of the same
|
||||
name. 47 tests in the workspace.
|
||||
- **Left:** the placeholder OID (a PEN, see "Open questions");
|
||||
`AllowedServerNames` (noted above); exchanging the versions, watching the
|
||||
CRL file and dropping revoked connections (step 5).
|
||||
- **Simplified (2026-11-13):** reading PEM and certificates in one place
|
||||
(`lib.rs`), the EKU through x509-parser's accessor. The verifiers'
|
||||
delegation stays: rustls' own CRL support would mean a new TLS
|
||||
configuration per CRL change, and still `Revocations` for open
|
||||
connections.
|
||||
|
||||
### Done: step 3 (2026-11-13)
|
||||
|
||||
`docs/config.md` has all of it; every key with its default:
|
||||
`crates/bakashrot-config/example.toml`.
|
||||
|
||||
- **`bakashrot-config`**, on `toml` and `serde` (`indexmap` for the
|
||||
file's order): `Config::load()` (paths from the config's folder) and
|
||||
`parse()`, checked in one go: TOML errors with their line, unknown keys,
|
||||
names, durations, sizes, addresses, ranges, things given twice (without
|
||||
case), `synchronous = "off"` refused as before.
|
||||
- `Config::permissions(roles)`: what a certificate's roles allow together,
|
||||
`None` when none is known; `Permissions::can_push / can_read /
|
||||
can_query / sends / accepts / replicates`. `Retention::age(topic)`.
|
||||
- **11 tests** (58 in the workspace): the example, defaults, every
|
||||
setting, retention's order, permissions, `replicated_topics`, paths, the
|
||||
refusals, each with its line (the old ini's keys among them).
|
||||
- **Simplified the same day:** values checked as serde reads them
|
||||
(`deserialize_with`, `try_from`) instead of raw structs checked after:
|
||||
one set of structs, and every refusal has its line.
|
||||
- **`upload_timeout` removed (2026-11-13):** protocol 7 streams an
|
||||
attachment inside its push, nothing waits for its message any more; a cut
|
||||
upload goes when its connection ends (schema v9).
|
||||
- **Left for the server (step 5 on):** loading the certificate files,
|
||||
refusing a push to a topic it doesn't have, `[replication] peers`
|
||||
dialed; one server per node (see "Open questions") and the default
|
||||
topic, for later.
|
||||
- **The default topic left the protocol too (2026-11-13):** `Welcome` has
|
||||
none, a push always names its topic (`NoDefaultTopic`, 6, never sent).
|
||||
|
||||
### Done: step 4 (2026-11-13)
|
||||
|
||||
`docs/storage.md` has all of it (the layout, why, the numbers).
|
||||
|
||||
- **`bakashrot-storage`**, on `rusqlite` (SQLite bundled):
|
||||
- `Database::open`: makes a v9 database, opens one, refuses the old
|
||||
server's, a newer one's or another program's, migrates (none yet),
|
||||
deletes left-over uploads;
|
||||
- `Writer::batch`: one transaction, each operation all or nothing (a
|
||||
savepoint): pushes, uploads, replication, retention, purging
|
||||
attachments;
|
||||
- `Reader`: messages (after an id, the last ones, about 1 MiB per
|
||||
answer), names, heads, missing attachments, attachments and parts, as
|
||||
the protocol's types;
|
||||
- `QueryRunner`: read-only SQL, three guards, results as strings;
|
||||
- `Writer::vacuum()`: the old `vacuum` command.
|
||||
- **The schema** moved into the crate (`src/schema_v9.sql`); the keys'
|
||||
layout is checked against it by a test.
|
||||
- **15 tests** (73 in the workspace): every operation, the limits, refused
|
||||
databases, queries, the view's plans, readers with two writers at once;
|
||||
and `compare_with_old` (ignored by default): the same workload as the
|
||||
old storage, for comparing.
|
||||
- **Measured before deciding** (Python, 5M messages): the packed layout
|
||||
23k pushes/s against 9k for v8's, 330 MB against 484 MB; a time index
|
||||
costs half the pushes, whatever the cache.
|
||||
- **Simplified:** the protocol's types as answers (no copies), one stream
|
||||
lookup, the states typed both ways, `u64`s checked by `rusqlite`, fixed
|
||||
SQL for reads (the key's layout only in `lib.rs` and the schema).
|
||||
- **Left for the server:** hashing parts as they stream (SHA-256), which
|
||||
topics exist (the config), retention's pace, a time limit on queries.
|
||||
- **Against the old storage** (same workload, storage alone; `storage.md`,
|
||||
"Against the old storage"): pushes 13.8k/s against the old 25.9k at 1M,
|
||||
12.2k against 19.6k at 5M; reading 1000 messages 10 times faster,
|
||||
retention 3 to 12 times. The old writer's speed is its code (checkpoints
|
||||
in a background thread, next ids in memory, no savepoint per push), not
|
||||
its schema: two of those brought over at step 5.
|
||||
|
||||
### Done: step 5 (2026-11-13)
|
||||
|
||||
`docs/server.md` has all of it.
|
||||
|
||||
- **`bakashrot-server`**: TLS with `bakashrot-pki`'s settings, the versions,
|
||||
the identity and its roles (refused with `NotAllowed` when none is
|
||||
known), `Welcome`; pushes (topic known, allowed, not too big) through
|
||||
one writer thread doing group commits; messages through a pool of read
|
||||
connections; the CRL file polled and reloaded, a revoked connection
|
||||
dropped at its next request; the other requests refused until their
|
||||
steps. The program: `bakashrot-server <config.toml>`, `tracing` logs,
|
||||
Ctrl+C.
|
||||
- **`bakashrot-client`**: blocking; connects (TLS, ALPN checked, the
|
||||
versions, `Welcome`), `push`, `get_messages`; errors as the protocol's
|
||||
codes.
|
||||
- **5 end-to-end tests** (and `push_rate`, ignored): pushes and reads back,
|
||||
refusals keeping the connection, refused certificates (each with its
|
||||
code), revoked ones dropped, six connections at once.
|
||||
- **Then optimized:** checkpoints on their own thread and connection (the
|
||||
writer only past 10,000 pages): 13.8k to 34.7k pushes/s, storage alone;
|
||||
no savepoint around a push: 37.3k (the old storage: 25.9k). Next ids in
|
||||
memory left out: one indexed read per push, not where the time goes.
|
||||
The whole server, 10 clients over TLS: 36k pushes/s with `normal`, 9.2k
|
||||
with `full` (a disk flush per group).
|
||||
|
||||
### Done: step 6 (2026-11-13)
|
||||
|
||||
`docs/server.md`, "Requests so far".
|
||||
|
||||
- **`GetMessages`** refuses an unknown topic (not the config's) or node
|
||||
(no messages in any topic) with `UnknownName`, as the old server did; a
|
||||
known pair without messages answers none.
|
||||
- **`ListNames`:** the config's topics the roles may push to or read
|
||||
(all with `query`), every node with messages.
|
||||
- **`Query`** on a pool of `query_only` connections; "malformed JSON"
|
||||
gets the old hint (`is_json = 1`).
|
||||
- **The client:** `list_names`, `query`; messages and queries over
|
||||
`MAX_MESSAGE_SIZE` refused before sending.
|
||||
- **4 more end-to-end tests:** runs of messages and big messages (the old
|
||||
suites' server parts: the tools' parts are step 8, replication's step
|
||||
11), names, queries.
|
||||
|
||||
### Done: step 7 (2026-11-13)
|
||||
|
||||
`docs/client.md` has all of it.
|
||||
|
||||
- **`bakashrot-capi`** builds `bakashrot.dll` / `libbakashrot.so`: the old
|
||||
exports over `bakashrot-client` (A and W, buffers, `GetLastError`, the
|
||||
same codes), certificates set from PEM or files, one connection per
|
||||
process, panics caught, the C runtime static on Windows (the release DLL
|
||||
imports system DLLs only).
|
||||
- **Bindings:** `bindings/c/bakashrot.h` generated by cbindgen (a test
|
||||
keeps it current), `bindings/purebasic/` (prototypes, error codes, an
|
||||
example run by hand against a server), `bindings/python/bakashrot.py`
|
||||
(certificates, `Client.from_file("client.toml")`, names only).
|
||||
- **Small changes under it:** the client checks `GetMessages`' limit and
|
||||
`after` before sending, and says whether the server closed the
|
||||
connection (`is_open`); the server knows a client's own node before its
|
||||
first push (none, not `UnknownName`).
|
||||
- **Tests:** the exports called directly (`exports.rs`),
|
||||
`check_bakashrot.py` ported (43 checks) run on the DLL (`python.rs`),
|
||||
the header. The attachment checks come back with step 9.
|
||||
|
||||
### Done: step 8 (2026-11-14)
|
||||
|
||||
`docs/client.md`, "The tools".
|
||||
|
||||
- **`bakashrot`** (`bakashrot-tools`): `push <topic> <message>`, `latest
|
||||
<topic> <node>`, `messages <topic> <node>` (`--after <id|latest>`,
|
||||
`--limit`, `--follow`, `--interval`, `--time`), `query <sql>`, `list
|
||||
[topics|nodes|all] [--json]`, connecting with `client.toml` (`-c`). The
|
||||
old tools' output, without the ids; errors on stderr.
|
||||
- **Gone:** `ResolveIds` (no ids), `GenerateKeyPairs` (`bakashrot-cert`),
|
||||
the default topic (`push` names its topic). `GetAttachment` and `push
|
||||
-a` come with step 9.
|
||||
- **Tests** (`tests/bakashrot.rs`, 5): the GetMessages suite's checks
|
||||
(defaults, `--after`, `--limit`, `latest`, another reader, refusals,
|
||||
data as stored, big messages, `--follow` taking only new ones and failing
|
||||
once the server is gone), Names' and BigMessages' tool checks (pushes,
|
||||
refusals, the size limit, `latest`, `list`), queries, `client.toml`
|
||||
(relative paths, a typo, an unreachable server).
|
||||
|
||||
### Done: step 9 (2026-11-14)
|
||||
|
||||
`docs/server.md` ("Requests"), `client.md`.
|
||||
|
||||
- **The server:** a push with an attachment is checked (topic, roles,
|
||||
sizes, the server's `max_attachment_size`), answered `Continue`, then
|
||||
every part read, written while the next ones come (4 at most waiting
|
||||
for the writer), the SHA-256 checked as they come; the message is
|
||||
stored with it once all of it matches. A wrong part, a wrong SHA-256, a
|
||||
failed write: refused once all parts came, the upload dropped. A cut
|
||||
connection drops it too. `GetAttachment` sends the size and SHA-256,
|
||||
then the parts from `from_part` (`NotFound`, `NotReady`, `TooBig` for
|
||||
one this server doesn't keep). The writer's queue takes every write
|
||||
now, not only pushes.
|
||||
- **The client:** `push_with_attachment(topic, data, source)` (anything
|
||||
`Read + Seek`: read twice, its SHA-256 first), `get_attachment(..., out)`
|
||||
checked with its SHA-256 (`AttachmentMismatch`), `save_attachment(...,
|
||||
path)` written aside then moved, so a failed one leaves no file.
|
||||
- **The DLL, Python, the tool, PureBasic:** as decided; the PureBasic
|
||||
example pushes an attachment and reads it back (run by hand, 5.73).
|
||||
- **Tests:** the server's (`attachments`: the Attachments suite's sizes, 1
|
||||
byte to 5 MB + 123 and exactly 2 MB, read back and saved, none or
|
||||
missing refused, no file left, the limit, 0 for none, not allowed; and
|
||||
`attachment_edges`: a source changed between its SHA-256 and its
|
||||
sending, one failing in the middle, a part of the wrong size, a wrong
|
||||
SHA-256, reading from a part on, something else than a part; uploads
|
||||
dropped each time), the DLL's exports, `check_bakashrot.py`'s
|
||||
attachment checks back (52 checks), the tool's.
|
||||
- **Measured** (release, local, `normal`): a 200 MB attachment up in 1.3 s
|
||||
and down in 0.5 s through the tool, its start included.
|
||||
- **Left for replication (step 11):** replicated attachments
|
||||
(`replicating`, `too_big`), the corrupted-attachment fix, resuming from
|
||||
a part.
|
||||
|
||||
### Done: step 10 (2026-11-14)
|
||||
|
||||
`docs/server.md` ("Retention").
|
||||
|
||||
- **The server:** a task (`retention.rs`, `Server::apply_retention()`):
|
||||
at start, then every `retention_interval`, every topic in the database
|
||||
by its name, its age from `[retention]`, its messages before now minus
|
||||
it deleted through the writer's queue (10,000 per write, so pushes go
|
||||
on between them), then the deleted messages' attachment parts (64 per
|
||||
write); each topic's count logged. As the old server did, except that
|
||||
uploads left behind are dropped at once (protocol 7), not on a timeout.
|
||||
- **Tests:** `end_to_end.rs`'s `retention`: a topic kept 2 s, checked
|
||||
every second, its messages and attachment gone, another topic kept,
|
||||
ids going on, a younger message kept through a pass.
|
||||
- **Left for replication (step 11):** the peer keeping its own copies,
|
||||
and what arrives already past its age (counted as received, not
|
||||
stored).
|
||||
|
||||
### Done: step 11 (2026-11-14)
|
||||
|
||||
`docs/server.md` ("Replication"), `config.md` ("Peers").
|
||||
|
||||
- **The config:** `[replication] push_to` (was `peers`) and
|
||||
`accept_from` (IPs or hostnames, `"*"`), as decided.
|
||||
- **Sending** (`push_to.rs`): a link per server of `push_to`, dialed
|
||||
again after `retry_delay`, failures logged once until they change;
|
||||
a check-in (again at once after sending, after `sync_interval` when
|
||||
idle): `SyncState`, then the messages it
|
||||
lacks by name (`batch_size`, about 1 MiB a batch), then the attachments
|
||||
it lacks from their part. The corrupted-attachment fix (old open item
|
||||
3): a copy the other server says doesn't match is read back, and if
|
||||
damaged dropped and asked for again from this server's peers, instead
|
||||
of sent at every check-in.
|
||||
- **Receiving** (`accept_from.rs`): only from `accept_from` (hostnames
|
||||
looked up at a connection's first replication request), only what the
|
||||
roles' `accept_*` allow; ids and times kept, ones past their age only
|
||||
counted; attachments resumed from their part (the parts here read back
|
||||
for the SHA-256), started over when they don't match.
|
||||
- **Storage:** `replicate(..., skip_before)`, `to_replicate()`,
|
||||
`damaged()`; a replicated attachment all of whose parts came but that
|
||||
wasn't checked (a stop in between) starts over at the next start.
|
||||
- **Tests:** `end_to_end.rs`'s `replication` (three servers: by name,
|
||||
ids, times and attachments; not from outside `accept_from`; one way;
|
||||
a server stopped and started again on its database, ids going on; a
|
||||
damaged copy caught) and `replication_edges` (the test as the peer);
|
||||
storage's `replication` (skipped on arrival, `to_replicate`,
|
||||
`damaged`); the config's (`push_to`, `accept_from`, `peers` refused,
|
||||
`accepted()`).
|
||||
- **Measured** (`docs/server.md`, "Replication, against the old
|
||||
server"): 4 servers in a Y, 10 nodes each flat out: 16,000-16,300
|
||||
pushes/s with `full` (old: 16,638), 35,300-37,500 with `normal` (old:
|
||||
33,895), and the servers keeping up while pushing (under 1 s behind,
|
||||
the old ones 9-11 s), a link checking in again at once after sending;
|
||||
`batch_size` 1000 by default (was 100).
|
||||
- **Not done:** `SyncState`'s 256 missing attachments are the oldest
|
||||
ones, whichever peer can send them: with several peers, ones none of
|
||||
them has can hold back newer ones. Gaps in a pair's ids (old item 6)
|
||||
still not detected.
|
||||
|
||||
### Done: step 12 (2026-11-14)
|
||||
|
||||
`docs/server.md` ("Running"), `readme.md` ("Releases").
|
||||
|
||||
- **Stopping:** `bakashrot-server` waits for SIGTERM or SIGINT (Linux),
|
||||
Ctrl+C, Ctrl+Break or its console closed (Windows), stops taking
|
||||
connections, then `Server::stop()`: the writer's thread commits what
|
||||
was queued before (so every push answered is stored), refuses what
|
||||
comes after (`ServerError`, "the server is stopping"), and it exits
|
||||
with 0.
|
||||
- **Logs:** the console, no colour codes when redirected,
|
||||
`BAKASHROT_LOG` for the level. No console commands.
|
||||
- **The release:** `release.py`, for the platform it runs on:
|
||||
builds, packages into `target/dist/bakashrot-0.2.0-<platform>/` (the
|
||||
three programs, the library, `bakashrot.h`, the PureBasic files,
|
||||
`bakashrot.py` and its wheel, the example configs, the docs, a
|
||||
`README.txt`, `LICENSE.txt`, `THIRD-PARTY.txt` from `cargo metadata`),
|
||||
smoke-tests it, archives it (`.zip`, `.tar.gz`). The smoke test: a CA
|
||||
and certificates by `bakashrot-cert`, the server on a free port, the
|
||||
tool's push (and a 3 MB attachment), `latest`, `attachment`,
|
||||
`messages`, `list`, `query`; Python through the library; the wheel
|
||||
installed by pip, used with no path; the server stopped by Ctrl+Break
|
||||
(SIGTERM on Linux), exiting cleanly. Passes on Windows (9.6 MB zip).
|
||||
- **The wheel:** `bindings/python/make_wheel.py`, as the old one (only
|
||||
the standard library, the same inputs giving the same wheel):
|
||||
`win_amd64`, or `manylinux_<glibc>_x86_64` from the glibc it's built
|
||||
against; the licenses in it.
|
||||
- **CI** (`.github/workflows/ci.yml`): a `release` job on a `v*` tag
|
||||
or by hand, Windows and Linux (in `manylinux_2_28`), keeping the
|
||||
archives.
|
||||
- **The version:** 0.2.0, the workspace's; `release.py` checks
|
||||
`bakashrot.py`'s is the same.
|
||||
- **Size:** the release profile optimizes for size (`opt-level = "s"`,
|
||||
with LTO, one codegen unit, stripped): the server 6.6 MB to 4.7 MB,
|
||||
`bakashrot` 3.9 to 2.8, `bakashrot-cert` 2.5 to 1.7, the DLL 3.4 to
|
||||
2.6 (Windows). About 5% fewer pushes with `normal`, the same with
|
||||
`full`, attachments and tool commands. Tried too: `"z"` (2-4% smaller
|
||||
still), the C code apart at 3 (1.2 MB more, no faster), `/Gy /Gw` for
|
||||
the C (100 KB). Not tried: `panic = "abort"` (the DLL catches panics,
|
||||
and a panic in one connection's task would end the server).
|
||||
- **Tests:** `end_to_end.rs`'s `stops_cleanly` (eight nodes pushing flat
|
||||
out, stopped under them: every answered push there after a restart);
|
||||
`restart_after()` stops as the program does.
|
||||
- **Not done:** the Linux release hadn't run here (no Linux machine);
|
||||
CI ran on GitHub after the push (2026-11-15). Docker: step 13.
|
||||
|
||||
### For step 13: what the old Docker image did
|
||||
|
||||
From `OldSource/Docker/` (git history), kept in `docker/` (the config
|
||||
in `/etc/bakashrot`, the database in a volume, the source label, a user
|
||||
of its own; the image is an index now, its annotations hold the label):
|
||||
|
||||
- A multi-stage build, the final image only the server and what it
|
||||
needs; `docker compose up -d --build` with the config in a mounted
|
||||
folder.
|
||||
- The label `org.opencontainers.image.source` set to the GitHub
|
||||
repository, which links the package to it on ghcr.io; built with
|
||||
`--provenance=false`, or the image is an index and GitHub doesn't see
|
||||
the label.
|
||||
- Pushed to both registries, with the version and as `latest`:
|
||||
`git.nibblepoker.lu/aziascreations/bakashrot-server` and
|
||||
`ghcr.io/aziascreations/bakashrot-server` (a token with
|
||||
`write:packages`); the package then linked and made public in its
|
||||
settings on GitHub.
|
||||
|
||||
Reference in New Issue
Block a user