mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added replication, Added clean stops, logs and releases (0.2.0)
Step 11: the servers replicate by name (push_to and accept_from), their messages and attachments, damaged copies asked for again. Step 12: the server stops cleanly on SIGTERM/SIGINT (Ctrl+C, Ctrl+Break and the console closing on Windows), committing what was queued; logs go to the console, BAKASHROT_LOG sets the level. release.py builds a release per platform (the programs, the DLL, a Python wheel with the library, THIRD-PARTY.txt) and smoke-tests it; CI runs it on v* tags. Built for size (opt-level "s"): 25-31% smaller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,17 @@
|
||||
# The new sources (Source/): the same checks as Source/check.ps1, on Windows
|
||||
# and Linux. Gitea Actions runs this file too.
|
||||
# and Linux; a release of each (Source/release.py) on a version tag or when
|
||||
# run by hand. Gitea Actions runs this file too.
|
||||
name: Source
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
# Tags aren't filtered by paths.
|
||||
tags: ["v*"]
|
||||
paths: ["Source/**", ".github/workflows/source.yml"]
|
||||
pull_request:
|
||||
paths: ["Source/**", ".github/workflows/source.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
@@ -28,3 +33,39 @@ jobs:
|
||||
- run: cargo doc --workspace --no-deps --all-features
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
|
||||
release:
|
||||
# Build, package, smoke test: target/dist/'s archive, kept as an
|
||||
# artifact. Linux builds in manylinux 2.28 (glibc 2.28): the programs,
|
||||
# the .so and the wheel run on systems that old.
|
||||
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
|
||||
needs: check
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: windows-latest
|
||||
python: python
|
||||
- os: ubuntu-latest
|
||||
container: quay.io/pypa/manylinux_2_28_x86_64
|
||||
python: /opt/python/cp312-cp312/bin/python
|
||||
runs-on: ${{ matrix.os }}
|
||||
container: ${{ matrix.container }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: Source
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- if: matrix.container
|
||||
run: |
|
||||
curl --proto '=https' -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain none
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- run: rustup toolchain install
|
||||
- run: ${{ matrix.python }} release.py
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: bakashrot-${{ matrix.os }}
|
||||
path: |
|
||||
Source/target/dist/*.zip
|
||||
Source/target/dist/*.tar.gz
|
||||
|
||||
Generated
+9
-8
@@ -123,7 +123,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-capi"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bakashrot-client",
|
||||
"bakashrot-config",
|
||||
@@ -137,7 +137,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-client"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"bakashrot-pki",
|
||||
@@ -147,7 +147,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-config"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bakashrot-proto",
|
||||
"indexmap",
|
||||
@@ -157,7 +157,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-pki"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bakashrot-proto",
|
||||
"rcgen",
|
||||
@@ -169,7 +169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-proto"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"rmp-serde",
|
||||
@@ -180,7 +180,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-server"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"bakashrot-client",
|
||||
@@ -190,6 +190,7 @@ dependencies = [
|
||||
"bakashrot-storage",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"rusqlite",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
@@ -199,7 +200,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-storage"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bakashrot-config",
|
||||
"bakashrot-proto",
|
||||
@@ -209,7 +210,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bakashrot-tools"
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bakashrot-client",
|
||||
"bakashrot-config",
|
||||
|
||||
+7
-1
@@ -6,7 +6,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.100"
|
||||
license = "CC0-1.0"
|
||||
@@ -24,6 +24,12 @@ missing_docs = "warn"
|
||||
all = { level = "warn", priority = -1 }
|
||||
|
||||
[profile.release]
|
||||
# Optimized for size: 25-31% smaller programs and DLL (the server 6.6 MB
|
||||
# to 4.7 MB), about 5% fewer pushes with `normal` (none with `full`, the
|
||||
# disk's), the same handshakes and attachments. Measured 2026-11-14;
|
||||
# "z" is barely smaller, the C (aws-lc, SQLite) kept at 3 adds 1.2 MB for
|
||||
# nothing measurable.
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
strip = true
|
||||
|
||||
+22
-1
@@ -13,6 +13,7 @@ Source/
|
||||
Cargo.toml the workspace: shared lints, release profile
|
||||
rust-toolchain.toml the pinned toolchain (1.100.0)
|
||||
check.ps1 what CI runs: fmt, clippy, tests, docs
|
||||
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
|
||||
crates/
|
||||
@@ -27,7 +28,7 @@ Source/
|
||||
bindings/
|
||||
c/ bakashrot.h, generated from bakashrot-capi
|
||||
purebasic/ the prototypes and error codes, as OldSource/Client/'s
|
||||
python/ bakashrot.py over the DLL, check_bakashrot.py (its wheel: 12)
|
||||
python/ bakashrot.py over the DLL, check_bakashrot.py, make_wheel.py
|
||||
.cargo/config.toml the C runtime linked statically on Windows
|
||||
tests/ (13) end-to-end suites across processes
|
||||
```
|
||||
@@ -45,6 +46,26 @@ them; the DLL and the tools only use `client`.
|
||||
- Output in `target/` (git-ignored). Generated keys and certificates never
|
||||
go in git.
|
||||
|
||||
## Releases
|
||||
|
||||
`python release.py` (Python 3.11+) on Windows x64 or Linux x86-64 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`.
|
||||
|
||||
CI runs it on a version tag (`v*`) or by hand, keeping the archives: the
|
||||
Linux one in a manylinux 2.28 container, so it runs 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.
|
||||
|
||||
## Conventions
|
||||
|
||||
- LF line endings (`.gitattributes`), rustfmt's defaults.
|
||||
|
||||
@@ -58,7 +58,7 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Iterator, Optional, Union
|
||||
|
||||
__version__ = "0.0.1"
|
||||
__version__ = "0.2.0"
|
||||
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NamesList",
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Builds the bakashrot wheel: bakashrot.py with the client library in it,
|
||||
so `pip install` is all a Python app needs, nothing to compile.
|
||||
|
||||
python make_wheel.py <library> <out_dir> [license files...]
|
||||
|
||||
<library> is bakashrot.dll (Windows x64) or libbakashrot.so (Linux x86-64),
|
||||
from `cargo build --release`; the license files go in the wheel's
|
||||
dist-info/licenses/ (release.py gives LICENSE and THIRD-PARTY.txt). Prints
|
||||
the wheel's path.
|
||||
|
||||
The wheel is bakashrot-<version>-py3-none-<platform>.whl, the version
|
||||
being bakashrot.py's __version__ (release.py checks it's the workspace's):
|
||||
win_amd64, or manylinux_<glibc>_x86_64 with the glibc it was built
|
||||
against (a Rust library only needs libc, libm and libgcc_s, which
|
||||
manylinux allows). Inside, bakashrot.py is bakashrot/__init__.py with the
|
||||
library next to it, where it looks first. Only the standard library, and
|
||||
the same inputs give the same wheel (fixed timestamps).
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
NAME = "bakashrot"
|
||||
# Zip entries' timestamp, so the wheel only changes when its content does.
|
||||
FIXED_TIME = (2026, 1, 1, 0, 0, 0)
|
||||
|
||||
DESCRIPTION = """\
|
||||
# bakashrot
|
||||
|
||||
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
|
||||
servers: push messages and attachments, read them back, list names, query.
|
||||
|
||||
The client library is included: nothing else to install or build. 64-bit
|
||||
Python 3.8+ (`Client.from_file()` needs 3.11+). The server must speak the
|
||||
same protocol: use the release this package comes from.
|
||||
|
||||
```python
|
||||
from bakashrot import Client
|
||||
|
||||
with Client.from_file("client.toml") as client:
|
||||
message_id = client.push({"temperature": 21.5}, "logs")
|
||||
for message in client.get_messages("logs", "kitchen", after=0).messages:
|
||||
print(message.id, message.data)
|
||||
```
|
||||
|
||||
See the module's docstring (`help(bakashrot)`) for the rest.
|
||||
"""
|
||||
|
||||
|
||||
def version():
|
||||
with open(os.path.join(HERE, "bakashrot.py"), encoding="utf-8") as file:
|
||||
match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE)
|
||||
if not match:
|
||||
sys.exit("No __version__ in bakashrot.py")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def platform_tag(library):
|
||||
"""The wheel's platform, from the library's kind."""
|
||||
with open(library, "rb") as file:
|
||||
magic = file.read(4)
|
||||
if magic[:2] == b"MZ":
|
||||
return "win_amd64", "Operating System :: Microsoft :: Windows"
|
||||
if magic == b"\x7fELF":
|
||||
libc, glibc = platform.libc_ver()
|
||||
if libc != "glibc":
|
||||
sys.exit("Built against another libc than glibc: no manylinux tag")
|
||||
major, minor = glibc.split(".")[:2]
|
||||
return f"manylinux_{major}_{minor}_x86_64", "Operating System :: POSIX :: Linux"
|
||||
sys.exit(f"{library}: neither a Windows DLL nor a Linux shared object")
|
||||
|
||||
|
||||
def record_line(path, data):
|
||||
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode("ascii")
|
||||
return f"{path},sha256={digest},{len(data)}"
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
sys.exit(__doc__)
|
||||
library, out_dir, licenses = sys.argv[1], sys.argv[2], sys.argv[3:]
|
||||
tag, classifier = platform_tag(library)
|
||||
tag = f"py3-none-{tag}"
|
||||
dist_info = f"{NAME}-{version()}.dist-info"
|
||||
|
||||
def read(path):
|
||||
with open(path, "rb") as file:
|
||||
return file.read()
|
||||
|
||||
files = [
|
||||
(f"{NAME}/__init__.py", read(os.path.join(HERE, "bakashrot.py"))),
|
||||
(f"{NAME}/{os.path.basename(library)}", read(library)),
|
||||
]
|
||||
# Metadata 2.4 (PEP 639): the license files, no expression (the
|
||||
# library bundles its dependencies' code, THIRD-PARTY.txt lists them).
|
||||
metadata = "\n".join([
|
||||
"Metadata-Version: 2.4",
|
||||
f"Name: {NAME}",
|
||||
f"Version: {version()}",
|
||||
"Summary: Python client for BakaShrot servers, with the client library included",
|
||||
"Author: Herwin Bozet (NibblePoker)",
|
||||
] + [f"License-File: {os.path.basename(path)}" for path in licenses] + [
|
||||
"Project-URL: GitHub, https://github.com/aziascreations/BakaShrot",
|
||||
f"Classifier: {classifier}",
|
||||
"Classifier: Programming Language :: Python :: 3",
|
||||
"Requires-Python: >=3.8",
|
||||
"Description-Content-Type: text/markdown",
|
||||
"",
|
||||
DESCRIPTION,
|
||||
])
|
||||
files.append((f"{dist_info}/METADATA", metadata.encode("utf-8")))
|
||||
wheel = f"Wheel-Version: 1.0\nGenerator: BakaShrot make_wheel.py\nRoot-Is-Purelib: false\nTag: {tag}\n"
|
||||
files.append((f"{dist_info}/WHEEL", wheel.encode("utf-8")))
|
||||
for path in licenses:
|
||||
files.append((f"{dist_info}/licenses/{os.path.basename(path)}", read(path)))
|
||||
record = [record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""]
|
||||
files.append((f"{dist_info}/RECORD", "\n".join(record).encode("utf-8")))
|
||||
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
wheel_path = os.path.join(out_dir, f"{NAME}-{version()}-{tag}.whl")
|
||||
with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for path, data in files:
|
||||
info = zipfile.ZipInfo(path, FIXED_TIME)
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.external_attr = (0o755 if path.endswith(".so") else 0o644) << 16
|
||||
archive.writestr(info, data)
|
||||
print(wheel_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -39,14 +39,17 @@ logs = "30d"
|
||||
"sensors.*" = "12h"
|
||||
"*" = "forever"
|
||||
|
||||
# Who this server replicates with, by address. A link carries messages
|
||||
# one way: the server that dials sends, the one dialed takes them.
|
||||
[replication]
|
||||
peers = [] # dialed: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
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 ["*"]
|
||||
# The only topics replicated at all, whatever the roles say: a filter for
|
||||
# edge nodes. Without it, no filter; [] replicates nothing.
|
||||
# replicated_topics = ["logs", "alerts.*"]
|
||||
retry_delay = "10s"
|
||||
sync_interval = "5s"
|
||||
batch_size = 100 # messages per packet, 1-10000
|
||||
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
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//!
|
||||
//! - [`Server`]: where it listens, its files, its topics, its database.
|
||||
//! - [`Retention`]: how long each topic's messages are kept.
|
||||
//! - [`Replication`]: the peers it dials, what it replicates, how often.
|
||||
//! - [`Replication`]: the servers it sends to and takes from, what it
|
||||
//! replicates, how often.
|
||||
//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what
|
||||
//! a certificate's roles allow together.
|
||||
//!
|
||||
@@ -200,20 +201,26 @@ impl Retention {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Replication {
|
||||
/// The peers it dials (`host:port`); peers dialing in come by
|
||||
/// themselves. What's replicated with each is its roles'.
|
||||
/// The servers it dials and sends to (`host:port`). What's sent to
|
||||
/// each is its roles' `send_*`.
|
||||
#[serde(deserialize_with = "values::peers")]
|
||||
pub peers: Vec<String>,
|
||||
pub push_to: Vec<String>,
|
||||
/// The servers it takes replicated messages from: IP addresses or
|
||||
/// hostnames, `*` for all; none by default. What's taken is their
|
||||
/// roles' `accept_*`.
|
||||
#[serde(deserialize_with = "values::hosts")]
|
||||
pub accept_from: Vec<String>,
|
||||
/// The only topics replicated at all, whatever the roles say (an edge
|
||||
/// node's filter); none: no filter.
|
||||
pub replicated_topics: Option<NameList>,
|
||||
/// How long to wait before dialing a peer again; 10s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub retry_delay: Duration,
|
||||
/// How often a linked peer is sent what it misses; 5s by default.
|
||||
/// How long a link waits, once nothing was left to send, before it
|
||||
/// looks again; 5s by default.
|
||||
#[serde(deserialize_with = "values::duration")]
|
||||
pub sync_interval: Duration,
|
||||
/// The most messages sent to a peer per packet; 100 by default.
|
||||
/// The most messages sent to a peer per packet; 1000 by default.
|
||||
#[serde(deserialize_with = "values::batch_size")]
|
||||
pub batch_size: u32,
|
||||
}
|
||||
@@ -221,11 +228,12 @@ pub struct Replication {
|
||||
impl Default for Replication {
|
||||
fn default() -> Self {
|
||||
Replication {
|
||||
peers: Vec::new(),
|
||||
push_to: Vec::new(),
|
||||
accept_from: Vec::new(),
|
||||
replicated_topics: None,
|
||||
retry_delay: Duration::from_secs(10),
|
||||
sync_interval: Duration::from_secs(5),
|
||||
batch_size: 100,
|
||||
batch_size: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,30 @@ impl Permissions {
|
||||
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
|
||||
}
|
||||
|
||||
/// The topics and the nodes taken from it, as `SyncState` lists them:
|
||||
/// its roles' `accept_*` (of those that accept topics), none twice.
|
||||
/// What's taken is still [`Permissions::accepts`]'.
|
||||
pub fn accepted(&self) -> (Vec<String>, Vec<String>) {
|
||||
let (mut topics, mut nodes) = (Vec::<String>::new(), Vec::<String>::new());
|
||||
for role in self
|
||||
.roles
|
||||
.iter()
|
||||
.filter(|role| !role.accept_topics.is_empty())
|
||||
{
|
||||
for (list, entries) in [
|
||||
(&mut topics, role.accept_topics.entries()),
|
||||
(&mut nodes, role.accept_nodes.entries()),
|
||||
] {
|
||||
for entry in entries {
|
||||
if !list.iter().any(|known| names_equal(known, entry)) {
|
||||
list.push(entry.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(topics, nodes)
|
||||
}
|
||||
|
||||
/// Whether it replicates at all: a peer.
|
||||
pub fn replicates(&self) -> bool {
|
||||
self.roles
|
||||
|
||||
@@ -91,15 +91,18 @@ pub(crate) fn is_peer_address(text: &str) -> bool {
|
||||
let port = port.parse::<u16>().is_ok_and(|port| port != 0);
|
||||
let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
|
||||
Some(v6) => v6.parse::<Ipv6Addr>().is_ok(),
|
||||
None => {
|
||||
None => is_hostname(host),
|
||||
};
|
||||
port && host
|
||||
}
|
||||
|
||||
/// A hostname or an IPv4 address: letters, digits, dots and dashes.
|
||||
fn is_hostname(host: &str) -> bool {
|
||||
!host.is_empty()
|
||||
&& host
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
|
||||
}
|
||||
};
|
||||
port && host
|
||||
}
|
||||
|
||||
// As serde reads them (`deserialize_with`): a value that's wrong fails
|
||||
// there, and toml says on which line.
|
||||
@@ -149,6 +152,27 @@ pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>,
|
||||
Ok(peers)
|
||||
}
|
||||
|
||||
/// Hosts without a port: IP addresses or hostnames, or `*` for all; none
|
||||
/// twice.
|
||||
pub(crate) fn hosts<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
|
||||
let hosts = Vec::<String>::deserialize(reader)?;
|
||||
for (at, host) in hosts.iter().enumerate() {
|
||||
if host != "*" && !is_hostname(host) && host.parse::<Ipv6Addr>().is_err() {
|
||||
return Err(D::Error::custom(format!(
|
||||
"'{host}' isn't an IP address or a hostname (without a port), like \
|
||||
\"10.0.0.2\" or \"server-2.lan\", or \"*\" for all"
|
||||
)));
|
||||
}
|
||||
if hosts[..at]
|
||||
.iter()
|
||||
.any(|before| before.eq_ignore_ascii_case(host))
|
||||
{
|
||||
return Err(D::Error::custom(format!("'{host}' is given twice")));
|
||||
}
|
||||
}
|
||||
Ok(hosts)
|
||||
}
|
||||
|
||||
/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`.
|
||||
pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D::Error> {
|
||||
let size = u32::deserialize(reader)?;
|
||||
|
||||
@@ -42,7 +42,8 @@ fn the_example() {
|
||||
assert!(!server.has_topic("sensors"));
|
||||
assert_eq!(server.synchronous, Synchronous::Full);
|
||||
assert_eq!(server.max_attachment_size, 1 << 30);
|
||||
assert_eq!(config.replication.peers, Vec::<String>::new());
|
||||
assert_eq!(config.replication.push_to, Vec::<String>::new());
|
||||
assert_eq!(config.replication.accept_from, Vec::<String>::new());
|
||||
assert_eq!(config.retention.age("logs"), days(30));
|
||||
assert_eq!(
|
||||
config.retention.age("sensors.kitchen"),
|
||||
@@ -65,7 +66,7 @@ fn defaults() {
|
||||
assert_eq!(config.retention.age("logs"), None);
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
|
||||
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
|
||||
assert_eq!(config.replication.batch_size, 100);
|
||||
assert_eq!(config.replication.batch_size, 1000);
|
||||
assert_eq!(config.replication.replicated_topics, None);
|
||||
assert!(config.roles.is_empty());
|
||||
assert!(config.permissions(&["anything"]).is_none());
|
||||
@@ -81,7 +82,8 @@ max_attachment_size = 0
|
||||
retention_interval = "1h30m"
|
||||
|
||||
[replication]
|
||||
peers = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
|
||||
accept_from = ["10.0.0.2", "server-3.lan", "fd00::4"]
|
||||
retry_delay = "1m"
|
||||
sync_interval = "2s"
|
||||
batch_size = 10000
|
||||
@@ -93,7 +95,8 @@ replicated_topics = ["logs"]
|
||||
assert_eq!(config.server.synchronous, Synchronous::Normal);
|
||||
assert_eq!(config.server.max_attachment_size, 0);
|
||||
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
|
||||
assert_eq!(config.replication.peers.len(), 3);
|
||||
assert_eq!(config.replication.push_to.len(), 3);
|
||||
assert_eq!(config.replication.accept_from[2], "fd00::4");
|
||||
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
|
||||
assert_eq!(config.replication.batch_size, 10_000);
|
||||
}
|
||||
@@ -181,6 +184,10 @@ accept_nodes = ["garage"]
|
||||
// A role without the topics replicates nothing, whatever its nodes.
|
||||
let only_peer = config.permissions(&["peer"]).unwrap();
|
||||
assert!(!only_peer.accepts("logs", "kitchen-1"));
|
||||
// What SyncState lists: the accepting roles' lists only.
|
||||
let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(peer.accepted(), (strings(&["*"]), strings(&["garage"])));
|
||||
assert_eq!(only_peer.accepted(), (vec![], vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -324,13 +331,25 @@ fn refusals() {
|
||||
),
|
||||
// [replication]
|
||||
(
|
||||
&with("[replication]\npeers = [\"10.0.0.2\"]\n"),
|
||||
&with("[replication]\npush_to = [\"10.0.0.2\"]\n"),
|
||||
"isn't a host and a port",
|
||||
),
|
||||
(
|
||||
&with("[replication]\npeers = [\"a:1\", \"a:1\"]\n"),
|
||||
&with("[replication]\npush_to = [\"a:1\", \"a:1\"]\n"),
|
||||
"'a:1' is given twice",
|
||||
),
|
||||
(
|
||||
&with("[replication]\naccept_from = [\"10.0.0.2:7000\"]\n"),
|
||||
"without a port",
|
||||
),
|
||||
(
|
||||
&with("[replication]\naccept_from = [\"a.lan\", \"A.lan\"]\n"),
|
||||
"'A.lan' is given twice",
|
||||
),
|
||||
(
|
||||
&with("[replication]\npeers = []\n"),
|
||||
"unknown field `peers`",
|
||||
),
|
||||
(
|
||||
&with("[replication]\nbatch_size = 0\n"),
|
||||
"batch size must be 1 to 10000",
|
||||
|
||||
@@ -29,3 +29,5 @@ workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
bakashrot-client = { path = "../bakashrot-client" }
|
||||
# To damage a stored attachment from a test (the storage's own version).
|
||||
rusqlite = { version = "0.42.0", features = ["bundled"] }
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Replication's receiving end: a server that dialed in sends what this
|
||||
//! one lacks (`push_to.rs` is the other end). Taken only from addresses in
|
||||
//! `[replication] accept_from`, and only what its roles' `accept_*` allow.
|
||||
|
||||
use crate::connection::{Frames, Peer, receive_parts, refused, send};
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, now};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Whether `address` is in `accept_from`: `*`, an address as written, or
|
||||
/// a hostname resolving to it (looked up now).
|
||||
async fn is_accepted(shared: &Shared, address: IpAddr) -> bool {
|
||||
let address = address.to_canonical();
|
||||
for host in &shared.config.replication.accept_from {
|
||||
if host == "*" {
|
||||
return true;
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
if ip.to_canonical() == address {
|
||||
return true;
|
||||
}
|
||||
} else if let Ok(found) = tokio::net::lookup_host((host.as_str(), 0)).await
|
||||
&& found
|
||||
.into_iter()
|
||||
.any(|at| at.ip().to_canonical() == address)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` (looked up at
|
||||
/// its first replication request).
|
||||
async fn check_address(shared: &Shared, peer: &mut Peer) -> Result<(), Packet> {
|
||||
let accepted = match peer.accepted {
|
||||
Some(accepted) => accepted,
|
||||
None => *peer
|
||||
.accepted
|
||||
.insert(is_accepted(shared, peer.address).await),
|
||||
};
|
||||
match accepted {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!(
|
||||
"this server doesn't take replication from {} ({}): not in its accept_from",
|
||||
peer.node, peer.address
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` and its roles
|
||||
/// accept `node`'s messages in `topic`.
|
||||
async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Result<(), Packet> {
|
||||
check_address(shared, peer).await?;
|
||||
match peer.permissions.accepts(topic, node) {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("this server doesn't take {topic}:{node} from {}", peer.node),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What it takes from this peer, how far it is in those, and the
|
||||
/// attachments it lacks among them.
|
||||
pub(crate) async fn sync_state(shared: &Arc<Shared>, peer: &mut Peer) -> Packet {
|
||||
if let Err(refusal) = check_address(shared, peer).await {
|
||||
return refusal;
|
||||
}
|
||||
let (topics, nodes) = peer.permissions.accepted();
|
||||
let found = shared
|
||||
.read(|reader| {
|
||||
Ok((
|
||||
reader.heads()?,
|
||||
reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?,
|
||||
))
|
||||
})
|
||||
.await;
|
||||
let (mut heads, mut missing) = match found {
|
||||
Ok(found) => found,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
heads.retain(|head| peer.permissions.accepts(&head.topic, &head.node));
|
||||
missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
|
||||
SyncState {
|
||||
topics,
|
||||
nodes,
|
||||
heads,
|
||||
missing,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A batch of a topic and node's messages: stored (those past their age
|
||||
/// here only counted), answered with its last id.
|
||||
pub(crate) async fn replicate_messages(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
batch: ReplicateMessages,
|
||||
) -> Packet {
|
||||
if let Err(refusal) = check(shared, peer, &batch.topic, &batch.node).await {
|
||||
return refusal;
|
||||
}
|
||||
if let Some(big) = batch
|
||||
.messages
|
||||
.iter()
|
||||
.find(|m| m.data.len() > MAX_MESSAGE_SIZE)
|
||||
{
|
||||
return refused(
|
||||
ErrorCode::TooBig,
|
||||
format!("message #{}: {MAX_MESSAGE_SIZE} bytes at most", big.id),
|
||||
);
|
||||
}
|
||||
let skip_before = shared
|
||||
.config
|
||||
.retention
|
||||
.age(&batch.topic)
|
||||
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64));
|
||||
let write = Write::Replicate {
|
||||
topic: batch.topic,
|
||||
node: batch.node,
|
||||
messages: batch.messages,
|
||||
max_attachment_size: shared.config.server.max_attachment_size,
|
||||
skip_before,
|
||||
};
|
||||
match shared.pushes.send(write).await {
|
||||
Ok(message_id) => MessagePushed { message_id }.into(),
|
||||
Err(refusal) => refusal.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment this server lacks: `Continue`, its parts from where it
|
||||
/// stopped, checked with its SHA-256 (the parts it had read back for it).
|
||||
/// An error closes the connection.
|
||||
pub(crate) async fn replicate_attachment(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
frames: &mut Frames,
|
||||
request: ReplicateAttachment,
|
||||
) -> Result<Packet, String> {
|
||||
if let Err(refusal) = check(shared, peer, &request.topic, &request.node).await {
|
||||
return Ok(refusal);
|
||||
}
|
||||
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id);
|
||||
let ReplicateAttachment {
|
||||
topic,
|
||||
node,
|
||||
message_id,
|
||||
from_part,
|
||||
} = request;
|
||||
let stored = match shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, message_id))
|
||||
.await
|
||||
{
|
||||
Ok(Some(stored)) if stored.state == AttachmentState::Replicating => stored,
|
||||
Ok(_) => {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotFound,
|
||||
format!("{message}: no attachment missing here"),
|
||||
));
|
||||
}
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let next = stored.received / ATTACHMENT_PART_SIZE;
|
||||
if from_part != next || stored.received == stored.size {
|
||||
return Ok(refused(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{message}: part {next} is the next one here, not {from_part}"),
|
||||
));
|
||||
}
|
||||
|
||||
// The parts it has, read back for the SHA-256.
|
||||
let sha256 = match shared.hash_parts(stored.id, 0..from_part).await {
|
||||
Ok(sha256) => sha256,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment_id = stored.id as u64;
|
||||
send(frames, Continue {}.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let refusal = receive_parts(
|
||||
shared,
|
||||
frames,
|
||||
attachment_id,
|
||||
&attachment,
|
||||
from_part,
|
||||
sha256,
|
||||
)
|
||||
.await?;
|
||||
if let Some(refusal) = &refusal
|
||||
&& refusal.code != ErrorCode::DataMismatch.code()
|
||||
{
|
||||
// A part not written: it goes on from there next time.
|
||||
return Ok(refusal.clone().into());
|
||||
}
|
||||
let finish = Write::FinishReplicated {
|
||||
attachment: attachment_id,
|
||||
matches: refusal.is_none(),
|
||||
};
|
||||
Ok(match (shared.pushes.send(finish).await, refusal) {
|
||||
(Err(refusal), _) | (Ok(_), Some(refusal)) => refusal.into(),
|
||||
(Ok(_), None) => MessagePushed { message_id }.into(),
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! a time (`Source/docs/protocol.md`).
|
||||
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, now};
|
||||
use crate::{Shared, accept_from, now};
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::Identity;
|
||||
@@ -12,11 +12,11 @@ use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, PacketType, frame};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::VecDeque;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -39,27 +39,30 @@ const PART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// next ones wait (the client with them, through TCP).
|
||||
const PARTS_IN_FLIGHT: usize = 4;
|
||||
|
||||
type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
|
||||
pub(crate) type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
|
||||
|
||||
/// Serves one connection until it ends, logging why.
|
||||
pub(crate) async fn handle(shared: Arc<Shared>, tcp: TcpStream, peer: SocketAddr) {
|
||||
match serve(&shared, tcp).await {
|
||||
match serve(&shared, tcp, peer.ip()).await {
|
||||
Ok(node) => debug!("{peer} ({node}): closed"),
|
||||
Err(why) => info!("{peer}: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Who it is once checked: its node, its certificate's serial (for later
|
||||
/// revocations), what it may do.
|
||||
struct Peer {
|
||||
node: String,
|
||||
/// revocations), what it may do, where it connects from.
|
||||
pub(crate) struct Peer {
|
||||
pub(crate) node: String,
|
||||
serial: Vec<u8>,
|
||||
permissions: Permissions,
|
||||
pub(crate) permissions: Permissions,
|
||||
pub(crate) address: IpAddr,
|
||||
/// Whether `accept_from` has it, once a replication request asked.
|
||||
pub(crate) accepted: Option<bool>,
|
||||
}
|
||||
|
||||
async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<String, String> {
|
||||
tcp.set_nodelay(true).map_err(|error| error.to_string())?;
|
||||
let (mut frames, peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp))
|
||||
let (mut frames, mut peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())??;
|
||||
debug!("{} connected", peer.node);
|
||||
@@ -95,11 +98,15 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
|
||||
Packet::ListNames(list) => list_names(shared, &peer, list).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, query).await,
|
||||
other if is_request(other.packet_type()) => RequestRefused::new(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{} isn't answered yet", other.packet_type().name()),
|
||||
)
|
||||
.into(),
|
||||
Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await,
|
||||
Packet::ReplicateMessages(batch) => {
|
||||
accept_from::replicate_messages(shared, &mut peer, batch).await
|
||||
}
|
||||
Packet::ReplicateAttachment(request) => {
|
||||
accept_from::replicate_attachment(shared, &mut peer, &mut frames, request)
|
||||
.await
|
||||
.map_err(|why| format!("{}: {why}", peer.node))?
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"{}: sent {}, not a request",
|
||||
@@ -115,7 +122,11 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
|
||||
}
|
||||
|
||||
/// TLS, the versions, the identity, the welcome (or the refusal).
|
||||
async fn open(shared: &Arc<Shared>, tcp: TcpStream) -> Result<(Frames, Peer), String> {
|
||||
async fn open(
|
||||
shared: &Arc<Shared>,
|
||||
tcp: TcpStream,
|
||||
address: IpAddr,
|
||||
) -> Result<(Frames, Peer), String> {
|
||||
let mut stream = shared
|
||||
.acceptor
|
||||
.accept(tcp)
|
||||
@@ -172,6 +183,8 @@ async fn open(shared: &Arc<Shared>, tcp: TcpStream) -> Result<(Frames, Peer), St
|
||||
node: identity.name,
|
||||
serial,
|
||||
permissions,
|
||||
address,
|
||||
accepted: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -238,8 +251,9 @@ async fn push(
|
||||
Ok(upload) => upload,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let sha256 = digest::Context::new(&digest::SHA256);
|
||||
let received = match send(frames, Continue {}.into()).await {
|
||||
Ok(()) => receive_parts(shared, frames, upload, &attachment).await,
|
||||
Ok(()) => receive_parts(shared, frames, upload, &attachment, 0, sha256).await,
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
let refusal = match received {
|
||||
@@ -264,19 +278,22 @@ async fn push(
|
||||
refusal.map(Packet::from)
|
||||
}
|
||||
|
||||
/// Reads every part of an upload, has the writer store them while the next
|
||||
/// ones come, checks the SHA-256: the refusal if one is due (the parts all
|
||||
/// read even then), an error if the connection must close.
|
||||
async fn receive_parts(
|
||||
/// Reads an attachment's parts from `from_part` on (an upload's, or a
|
||||
/// replicated one's), has the writer store them while the next ones come,
|
||||
/// checks the SHA-256 (`sha256` has the parts before): the refusal if one
|
||||
/// is due (the parts all read even then; `DataMismatch` for the SHA-256),
|
||||
/// an error if the connection must close.
|
||||
pub(crate) async fn receive_parts(
|
||||
shared: &Arc<Shared>,
|
||||
frames: &mut Frames,
|
||||
upload: u64,
|
||||
attachment: &Attachment,
|
||||
from_part: u64,
|
||||
mut sha256: digest::Context,
|
||||
) -> Result<Option<RequestRefused>, String> {
|
||||
let mut sha256 = digest::Context::new(&digest::SHA256);
|
||||
let mut writing = VecDeque::new();
|
||||
let mut refusal = None;
|
||||
for part in 0..attachment.part_count() {
|
||||
for part in from_part..attachment.part_count() {
|
||||
let bytes = match timeout(PART_TIMEOUT, frames.next()).await {
|
||||
Err(_) => return Err(format!("part {part} of an attachment: too slow")),
|
||||
Ok(None) => return Err(format!("closed at part {part} of an attachment")),
|
||||
@@ -495,25 +512,10 @@ async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(code: ErrorCode, reason: String) -> Packet {
|
||||
pub(crate) fn refused(code: ErrorCode, reason: String) -> Packet {
|
||||
RequestRefused::new(code, reason).into()
|
||||
}
|
||||
|
||||
/// The packets a client or a peer sends: the others are answers.
|
||||
fn is_request(kind: PacketType) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
PacketType::PushMessage
|
||||
| PacketType::GetMessages
|
||||
| PacketType::GetAttachment
|
||||
| PacketType::ListNames
|
||||
| PacketType::Query
|
||||
| PacketType::SyncStateRequest
|
||||
| PacketType::ReplicateMessages
|
||||
| PacketType::ReplicateAttachment
|
||||
)
|
||||
}
|
||||
|
||||
async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
|
||||
pub(crate) async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
|
||||
frames.send(bytes::Bytes::from(packet.encode())).await
|
||||
}
|
||||
|
||||
@@ -11,12 +11,15 @@
|
||||
//! a revoked certificate's connection is dropped at its next request.
|
||||
//! - [`Server::apply_retention`]: deletes messages past their topic's age
|
||||
//! (`retention.rs`).
|
||||
//!
|
||||
//! What it answers so far: pushes and their attachments, messages,
|
||||
//! attachments, names and queries. Replication comes with step 11
|
||||
//! (`../../revamp.md`, "Plan").
|
||||
//! - [`Server::replicate`]: sends what the servers of `push_to` lack
|
||||
//! (`push_to.rs`); those dialing in, if in `accept_from`, are answered
|
||||
//! by `accept_from.rs`.
|
||||
//! - [`Server::stop`]: commits what was queued for the writer, refuses
|
||||
//! the rest.
|
||||
|
||||
mod accept_from;
|
||||
mod connection;
|
||||
mod push_to;
|
||||
mod retention;
|
||||
mod writer;
|
||||
|
||||
@@ -30,7 +33,7 @@ use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
||||
use tracing::{info, warn};
|
||||
use writer::Pushes;
|
||||
|
||||
@@ -52,6 +55,8 @@ struct Shared {
|
||||
/// The server's own name: its certificate's.
|
||||
name: String,
|
||||
acceptor: TlsAcceptor,
|
||||
/// To dial the servers of `push_to`.
|
||||
connector: TlsConnector,
|
||||
revocations: SharedRevocations,
|
||||
/// The CA's certificate, to check CRLs with.
|
||||
ca: String,
|
||||
@@ -84,6 +89,8 @@ impl Server {
|
||||
let revocations = load_revocations(server.crl.as_deref(), &ca)?.shared();
|
||||
let tls = tls::server_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the server's TLS: {error}"))?;
|
||||
let dialing = tls::client_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the TLS to peers: {error}"))?;
|
||||
let database = Database::open(&server.database, server.synchronous)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
|
||||
@@ -93,6 +100,7 @@ impl Server {
|
||||
shared: Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
@@ -151,6 +159,20 @@ impl Server {
|
||||
retention::run(&self.shared).await
|
||||
}
|
||||
|
||||
/// Keeps a link to each server of `[replication] push_to`, sending
|
||||
/// each what it lacks (again at once after sending, after `sync_interval`
|
||||
/// when there was nothing). Never returns.
|
||||
pub async fn replicate(&self) {
|
||||
push_to::run(self.shared.clone()).await
|
||||
}
|
||||
|
||||
/// Stops writing: every write queued before is committed (and so
|
||||
/// answered), the ones after are refused (`ServerError`, the server
|
||||
/// stopping). Then the server can be dropped, its runtime stopped.
|
||||
pub async fn stop(&self) {
|
||||
self.shared.pushes.stop().await;
|
||||
}
|
||||
|
||||
/// Reloads the CRL file now: how many certificates it revokes.
|
||||
pub fn reload_revocations(&self) -> Result<usize, String> {
|
||||
let shared = &self.shared;
|
||||
@@ -175,6 +197,23 @@ impl Shared {
|
||||
.await
|
||||
}
|
||||
|
||||
/// The SHA-256 of an attachment's stored `parts`, read back one at a
|
||||
/// time (to go on with more, or to compare).
|
||||
async fn hash_parts(
|
||||
self: &Arc<Self>,
|
||||
attachment_id: i64,
|
||||
parts: std::ops::Range<u64>,
|
||||
) -> Result<aws_lc_rs::digest::Context, RequestRefused> {
|
||||
let mut sha256 = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256);
|
||||
for part in parts {
|
||||
let data = self
|
||||
.read(move |reader| reader.read_part(attachment_id, part))
|
||||
.await?;
|
||||
sha256.update(&data);
|
||||
}
|
||||
Ok(sha256)
|
||||
}
|
||||
|
||||
/// Runs a client's SQL on a query connection, off the async threads.
|
||||
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
|
||||
self.pooled(
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
//! `bakashrot-server <config.toml>`: runs a server until Ctrl+C.
|
||||
//! `bakashrot-server <config.toml>`: runs a server until it's told to stop
|
||||
//! (SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its console closed
|
||||
//! on Windows), then stops cleanly: what was queued for the database is
|
||||
//! committed first.
|
||||
//!
|
||||
//! Logs go to the console (stdout), `BAKASHROT_LOG` sets their level
|
||||
//! (`error`, `warn`, `info` by default, `debug`, `trace`).
|
||||
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_server::Server;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::{error, info};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
tracing_subscriber::fmt().with_target(false).init();
|
||||
let level = std::env::var("BAKASHROT_LOG").ok();
|
||||
let filter = level.as_deref().map_or(Ok(LevelFilter::INFO), str::parse);
|
||||
tracing_subscriber::fmt()
|
||||
.with_target(false)
|
||||
.with_max_level(*filter.as_ref().unwrap_or(&LevelFilter::INFO))
|
||||
// No colour codes in a file or a journal.
|
||||
.with_ansi(std::io::stdout().is_terminal())
|
||||
.init();
|
||||
if filter.is_err() {
|
||||
error!("BAKASHROT_LOG: not a level (error, warn, info, debug, trace), logging info");
|
||||
}
|
||||
let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else {
|
||||
eprintln!("usage: bakashrot-server <config.toml>");
|
||||
return ExitCode::from(2);
|
||||
@@ -30,11 +48,48 @@ async fn run(path: &std::path::Path) -> Result<(), String> {
|
||||
.await
|
||||
.map_err(|error| format!("listening on {}: {error}", server.listen()))?;
|
||||
info!("{} listening on {}", server.name(), server.listen());
|
||||
tokio::select! {
|
||||
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}"))?,
|
||||
_ = server.watch_revocations() => {}
|
||||
_ = server.apply_retention() => {}
|
||||
_ = tokio::signal::ctrl_c() => info!("stopping"),
|
||||
}
|
||||
let outcome = tokio::select! {
|
||||
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}")),
|
||||
_ = server.watch_revocations() => Ok(()),
|
||||
_ = server.apply_retention() => Ok(()),
|
||||
_ = server.replicate() => Ok(()),
|
||||
signal = stop_signal() => {
|
||||
info!("{}, stopping", signal?);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
server.stop().await;
|
||||
info!("stopped");
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The first stop signal: its name.
|
||||
#[cfg(unix)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let listen = |kind| signal(kind).map_err(|error| format!("listening for signals: {error}"));
|
||||
let (mut terminate, mut interrupt) = (
|
||||
listen(SignalKind::terminate())?,
|
||||
listen(SignalKind::interrupt())?,
|
||||
);
|
||||
Ok(tokio::select! {
|
||||
_ = terminate.recv() => "SIGTERM",
|
||||
_ = interrupt.recv() => "SIGINT",
|
||||
})
|
||||
}
|
||||
|
||||
/// The first stop signal: its name. Closing the console leaves a few
|
||||
/// seconds before Windows ends the process, enough to commit.
|
||||
#[cfg(windows)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::windows;
|
||||
let failed = |error: std::io::Error| format!("listening for Ctrl+C: {error}");
|
||||
let mut c = windows::ctrl_c().map_err(failed)?;
|
||||
let mut r#break = windows::ctrl_break().map_err(failed)?;
|
||||
let mut close = windows::ctrl_close().map_err(failed)?;
|
||||
Ok(tokio::select! {
|
||||
_ = c.recv() => "Ctrl+C",
|
||||
_ = r#break.recv() => "Ctrl+Break",
|
||||
_ = close.recv() => "the console closed",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Replication's sending end: a link to each server of
|
||||
//! `[replication] push_to`, kept up (dialed again after `retry_delay`).
|
||||
//! It checks in: asks what the other server takes and has (`SyncState`),
|
||||
//! sends the messages it lacks, by topic and node name, then the
|
||||
//! attachments it lacks; again at once if it sent any (it keeps up under
|
||||
//! load), after `sync_interval` otherwise. Only what the other server's roles'
|
||||
//! `send_*` allow. `accept_from.rs` is the other end.
|
||||
|
||||
use crate::Shared;
|
||||
use crate::writer::Write;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::tls;
|
||||
use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::{names_equal, pattern_matches};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::{sleep, timeout};
|
||||
use tokio_rustls::client::TlsStream;
|
||||
use tokio_util::codec::{Framed, LengthDelimitedCodec};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// How long connecting may take: TCP, TLS, the versions, the welcome.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long an answer may take.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Keeps a link to each server of `push_to`. Never returns.
|
||||
pub(crate) async fn run(shared: Arc<Shared>) {
|
||||
let mut links = JoinSet::new();
|
||||
for address in &shared.config.replication.push_to {
|
||||
links.spawn(keep_linked(shared.clone(), address.clone()));
|
||||
}
|
||||
while links.join_next().await.is_some() {}
|
||||
std::future::pending().await
|
||||
}
|
||||
|
||||
/// Links to `address`, checks in until the link fails, then again after
|
||||
/// `retry_delay`. A failure is logged once until it changes.
|
||||
async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||
let replication = &shared.config.replication;
|
||||
let mut last_failure = String::new();
|
||||
loop {
|
||||
let failure = match Link::open(&shared, &address).await {
|
||||
Ok(mut link) => {
|
||||
info!("{address}: linked to {}", link.name);
|
||||
last_failure.clear();
|
||||
loop {
|
||||
match link.check_in(&shared).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => sleep(replication.sync_interval).await,
|
||||
Err(why) => break format!("{} ({address}): {why}", link.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(why) => format!("{address}: {why}"),
|
||||
};
|
||||
if failure != last_failure {
|
||||
warn!("{failure}");
|
||||
last_failure = failure;
|
||||
}
|
||||
sleep(replication.retry_delay).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A link to a server: what it is, what it may be sent.
|
||||
struct Link {
|
||||
frames: Framed<TlsStream<TcpStream>, LengthDelimitedCodec>,
|
||||
name: String,
|
||||
permissions: Permissions,
|
||||
/// Whether this check-in sent something it took.
|
||||
sent: bool,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
async fn open(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
timeout(CONNECT_TIMEOUT, Link::connect(shared, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())?
|
||||
}
|
||||
|
||||
/// TCP, TLS, the versions, its roles here, the welcome.
|
||||
async fn connect(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
let text = |error: std::io::Error| error.to_string();
|
||||
let tcp = TcpStream::connect(address).await.map_err(text)?;
|
||||
tcp.set_nodelay(true).map_err(text)?;
|
||||
let mut stream = shared
|
||||
.connector
|
||||
.connect(tls::server_name(), tcp)
|
||||
.await
|
||||
.map_err(|error| format!("TLS: {error}"))?;
|
||||
if stream.get_ref().1.alpn_protocol() != Some(ALPN) {
|
||||
return Err("not a BakaShrot server".into());
|
||||
}
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
.await
|
||||
.map_err(text)?;
|
||||
stream.flush().await.map_err(text)?;
|
||||
let mut theirs = [0; frame::VERSION_SIZE];
|
||||
stream.read_exact(&mut theirs).await.map_err(text)?;
|
||||
frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?;
|
||||
|
||||
let identity = tls::peer_identity(stream.get_ref().1.peer_certificates())
|
||||
.map_err(|error| error.to_string())?;
|
||||
let permissions = shared.config.permissions(&identity.roles).ok_or_else(|| {
|
||||
format!(
|
||||
"{}: none of its roles ({}) is in this server's config",
|
||||
identity.name,
|
||||
identity.roles.join(", ")
|
||||
)
|
||||
})?;
|
||||
let mut link = Link {
|
||||
frames: Framed::new(stream, frame::codec(MAX_PACKET_SIZE)),
|
||||
name: identity.name,
|
||||
permissions,
|
||||
sent: false,
|
||||
};
|
||||
match link.receive().await? {
|
||||
Packet::Welcome(_) => Ok(link),
|
||||
Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One check-in: what it lacks, the messages then the attachments.
|
||||
/// Whether it sent something it took.
|
||||
async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> {
|
||||
self.sent = false;
|
||||
let state = match self.ask(SyncStateRequest {}.into()).await? {
|
||||
Packet::SyncState(state) => state,
|
||||
Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)),
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let heads = shared
|
||||
.read(|reader| reader.heads())
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let theirs: HashMap<(String, String), u64> = state
|
||||
.heads
|
||||
.iter()
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id))
|
||||
.collect();
|
||||
for head in heads {
|
||||
let (topic, node) = (head.topic, head.node);
|
||||
if !self.sends(&state, &topic, &node) {
|
||||
continue;
|
||||
}
|
||||
let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0);
|
||||
if after < head.last_id {
|
||||
self.send_messages(shared, topic, node, after).await?;
|
||||
}
|
||||
}
|
||||
for missing in state.missing {
|
||||
if self.permissions.sends(&missing.topic, &missing.node) {
|
||||
self.send_attachment(shared, missing).await?;
|
||||
}
|
||||
}
|
||||
Ok(self.sent)
|
||||
}
|
||||
|
||||
/// Whether it takes `node`'s messages in `topic` (its `SyncState`) and
|
||||
/// may be sent them (its roles here).
|
||||
fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool {
|
||||
let listed = |list: &[String], name: &str| {
|
||||
list.iter()
|
||||
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
|
||||
};
|
||||
listed(&state.topics, topic)
|
||||
&& listed(&state.nodes, node)
|
||||
&& self.permissions.sends(topic, node)
|
||||
}
|
||||
|
||||
/// A topic and node's messages after `after`, in batches. A refusal
|
||||
/// leaves them for the next check-in.
|
||||
async fn send_messages(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
topic: String,
|
||||
node: String,
|
||||
mut after: u64,
|
||||
) -> Result<(), String> {
|
||||
let limit = shared.config.replication.batch_size;
|
||||
loop {
|
||||
let (t, n) = (topic.clone(), node.clone());
|
||||
let messages = shared
|
||||
.read(move |reader| reader.to_replicate(&t, &n, after, limit))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(last) = messages.last().map(|message| message.id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let batch = ReplicateMessages {
|
||||
topic: topic.clone(),
|
||||
node: node.clone(),
|
||||
messages,
|
||||
};
|
||||
match self.ask(batch.into()).await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
after = last;
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!("{}: {topic}:{node} refused: {}", self.name, refused.reason);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment it lacks, from the part it needs, if this server has
|
||||
/// it. One it says doesn't match its SHA-256 is checked here: a
|
||||
/// damaged copy is asked for again from this server's own peers.
|
||||
async fn send_attachment(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
missing: MissingAttachment,
|
||||
) -> Result<(), String> {
|
||||
let message = format!("{}:{}#{}", missing.topic, missing.node, missing.message_id);
|
||||
let (topic, node, id) = (
|
||||
missing.topic.clone(),
|
||||
missing.node.clone(),
|
||||
missing.message_id,
|
||||
);
|
||||
let stored = shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, id))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(stored) = stored.filter(|stored| stored.state == AttachmentState::Ready) else {
|
||||
return Ok(());
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let from_part = missing.next_part;
|
||||
if from_part >= attachment.part_count() {
|
||||
return Ok(());
|
||||
}
|
||||
let request = ReplicateAttachment {
|
||||
topic: missing.topic,
|
||||
node: missing.node,
|
||||
message_id: missing.message_id,
|
||||
from_part,
|
||||
};
|
||||
match self.ask(request.into()).await? {
|
||||
Packet::Continue(_) => {}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
for part in from_part..attachment.part_count() {
|
||||
// A part that can't be read: the link closes, it asks again.
|
||||
let data = shared
|
||||
.read(move |reader| reader.read_part(stored.id, part))
|
||||
.await
|
||||
.map_err(|refused| format!("part {part} of {message}: {}", refused.reason))?;
|
||||
self.send(AttachmentPart { data }.into()).await?;
|
||||
}
|
||||
match self.receive().await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
debug!("{}: sent {message}'s attachment", self.name);
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) if refused.code == ErrorCode::DataMismatch.code() => {
|
||||
check_own_copy(shared, stored.id, &attachment, &message).await
|
||||
}
|
||||
Packet::RequestRefused(refused) => debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
),
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
self.send(packet).await?;
|
||||
self.receive().await
|
||||
}
|
||||
|
||||
async fn send(&mut self, packet: Packet) -> Result<(), String> {
|
||||
self.frames
|
||||
.send(bytes::Bytes::from(packet.encode()))
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
async fn receive(&mut self) -> Result<Packet, String> {
|
||||
match timeout(ANSWER_TIMEOUT, self.frames.next()).await {
|
||||
Err(_) => Err("no answer in time".into()),
|
||||
Ok(None) => Err("closed the link".into()),
|
||||
Ok(Some(bytes)) => {
|
||||
let bytes = bytes.map_err(|error| error.to_string())?;
|
||||
Packet::decode(&bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The other server said this server's copy doesn't match its SHA-256:
|
||||
/// read it back; damaged, it's asked for again from this server's peers
|
||||
/// (and not served meanwhile), instead of sent again and again.
|
||||
async fn check_own_copy(
|
||||
shared: &Arc<Shared>,
|
||||
attachment_id: i64,
|
||||
attachment: &Attachment,
|
||||
message: &str,
|
||||
) {
|
||||
let read = shared.hash_parts(attachment_id, 0..attachment.part_count());
|
||||
if let Ok(sha256) = read.await
|
||||
&& sha256.finish().as_ref() == attachment.sha256
|
||||
{
|
||||
return;
|
||||
}
|
||||
let damaged = Write::Damaged {
|
||||
attachment: attachment_id as u64,
|
||||
};
|
||||
match shared.pushes.send(damaged).await {
|
||||
Ok(_) => {
|
||||
warn!("{message}: this server's copy of its attachment is damaged, asked for again")
|
||||
}
|
||||
Err(refused) => warn!("{message}: a damaged attachment: {}", refused.reason),
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node, to compare without case.
|
||||
fn key(topic: &str, node: &str) -> (String, String) {
|
||||
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn unexpected(packet: &Packet) -> String {
|
||||
format!("answered {}", packet.packet_type().name())
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! The writer's thread: every write goes through one queue, and the thread
|
||||
//! writes whatever is queued in one transaction (a group commit): the
|
||||
//! busier, the bigger the groups.
|
||||
//! busier, the bigger the groups. [`Pushes::stop`] ends it once what was
|
||||
//! queued before is committed.
|
||||
|
||||
use crate::refusal;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_proto::packets::{ReplicatedMessage, RequestRefused};
|
||||
use bakashrot_storage::{Batch, Writer};
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -52,6 +53,19 @@ pub(crate) enum Write {
|
||||
/// Deletes deleted messages' attachment parts, `max_parts` at most:
|
||||
/// how many.
|
||||
PurgeAttachments { max_parts: usize },
|
||||
/// A peer's messages: the topic and node's last id.
|
||||
Replicate {
|
||||
topic: String,
|
||||
node: String,
|
||||
messages: Vec<ReplicatedMessage>,
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
},
|
||||
/// A replicated attachment all of whose parts came: ready if it
|
||||
/// `matches` its SHA-256, started over otherwise. 0.
|
||||
FinishReplicated { attachment: u64, matches: bool },
|
||||
/// This server's own copy found damaged: asked for again. 0.
|
||||
Damaged { attachment: u64 },
|
||||
}
|
||||
|
||||
impl Write {
|
||||
@@ -88,13 +102,32 @@ impl Write {
|
||||
Write::PurgeAttachments { max_parts } => batch
|
||||
.purge_attachments(*max_parts)
|
||||
.map(|count| count as u64),
|
||||
Write::Replicate {
|
||||
topic,
|
||||
node,
|
||||
messages,
|
||||
max_attachment_size,
|
||||
skip_before,
|
||||
} => batch.replicate(topic, node, messages, *max_attachment_size, *skip_before),
|
||||
Write::FinishReplicated {
|
||||
attachment,
|
||||
matches,
|
||||
} => batch
|
||||
.finish_replicated(*attachment as i64, *matches)
|
||||
.map(|()| 0),
|
||||
Write::Damaged { attachment } => batch.damaged(*attachment as i64).map(|()| 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Job {
|
||||
/// What the writer's thread is sent.
|
||||
enum Job {
|
||||
Write {
|
||||
write: Write,
|
||||
done: oneshot::Sender<Outcome>,
|
||||
},
|
||||
/// Stop once the writes queued before are committed, then say so.
|
||||
Stop(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
/// The queue to the writer's thread.
|
||||
@@ -103,30 +136,51 @@ pub(crate) struct Pushes {
|
||||
}
|
||||
|
||||
impl Pushes {
|
||||
/// Starts the writer's thread on `writer`. It ends with the queue.
|
||||
/// Starts the writer's thread on `writer`. It ends with the queue, or
|
||||
/// at [`Pushes::stop`].
|
||||
pub(crate) fn start(mut writer: Writer) -> std::io::Result<Pushes> {
|
||||
let (queue, pending) = mpsc::channel::<Job>();
|
||||
std::thread::Builder::new()
|
||||
.name("writer".into())
|
||||
.spawn(move || {
|
||||
while let Ok(first) = pending.recv() {
|
||||
let mut group = vec![first];
|
||||
while group.len() < MAX_GROUP {
|
||||
let Ok(next) = pending.try_recv() else { break };
|
||||
group.push(next);
|
||||
let (mut group, mut stopped) = (Vec::new(), None);
|
||||
for job in std::iter::once(first).chain(pending.try_iter()) {
|
||||
match job {
|
||||
Job::Write { write, done } => group.push((write, done)),
|
||||
Job::Stop(done) => stopped = Some(done),
|
||||
}
|
||||
if stopped.is_some() || group.len() == MAX_GROUP {
|
||||
break;
|
||||
}
|
||||
}
|
||||
write(&mut writer, group);
|
||||
if let Some(done) = stopped {
|
||||
// Writes queued after are dropped with the queue,
|
||||
// refused as the server stopping.
|
||||
let _ = done.send(());
|
||||
return;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Pushes { queue })
|
||||
}
|
||||
|
||||
/// Stops the writer's thread once every write queued before is
|
||||
/// committed; the ones after are refused, the server stopping.
|
||||
pub(crate) async fn stop(&self) {
|
||||
let (done, stopped) = oneshot::channel();
|
||||
if self.queue.send(Job::Stop(done)).is_ok() {
|
||||
let _ = stopped.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues a write now (writes are done in the order queued), its
|
||||
/// outcome once its group is committed. Dropping the future doesn't
|
||||
/// take the write back.
|
||||
pub(crate) fn send(&self, write: Write) -> impl Future<Output = Outcome> + use<> {
|
||||
let (done, outcome) = oneshot::channel();
|
||||
let queued = self.queue.send(Job { write, done });
|
||||
let queued = self.queue.send(Job::Write { write, done });
|
||||
async move {
|
||||
queued.map_err(|_| stopped())?;
|
||||
outcome.await.unwrap_or_else(|_| Err(stopped()))
|
||||
@@ -135,11 +189,14 @@ impl Pushes {
|
||||
}
|
||||
|
||||
/// Writes a group in one transaction, then answers each write.
|
||||
fn write(writer: &mut Writer, group: Vec<Job>) {
|
||||
fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
|
||||
if group.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(group.len());
|
||||
let committed = writer.batch(|batch| {
|
||||
for job in &group {
|
||||
outcomes.push(job.write.run(batch).map_err(refusal));
|
||||
for (write, _) in &group {
|
||||
outcomes.push(write.run(batch).map_err(refusal));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
@@ -147,9 +204,9 @@ fn write(writer: &mut Writer, group: Vec<Job>) {
|
||||
let refused = refusal(error);
|
||||
outcomes = group.iter().map(|_| Err(refused.clone())).collect();
|
||||
}
|
||||
for (job, outcome) in group.into_iter().zip(outcomes) {
|
||||
for ((_, done), outcome) in group.into_iter().zip(outcomes) {
|
||||
// Its connection may be gone: nothing to answer then.
|
||||
let _ = job.done.send(outcome);
|
||||
let _ = done.send(outcome);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
//! A server on a free port, clients over TLS: pushes and reads, runs of
|
||||
//! messages, big ones, names, queries, attachments, retention, refusals,
|
||||
//! certificates refused, revoked ones dropped, pushes at once.
|
||||
//! messages, big ones, names, queries, attachments, retention, replication
|
||||
//! between servers, refusals, certificates refused, revoked ones dropped,
|
||||
//! pushes at once.
|
||||
|
||||
use bakashrot_client::{Client, Settings};
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, Messages, NameKind, PushMessage, StoredAttachment,
|
||||
Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage,
|
||||
ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState,
|
||||
SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_server::Server;
|
||||
@@ -38,17 +41,22 @@ read_topics = ["logs"]
|
||||
|
||||
[roles.analyst]
|
||||
query = true
|
||||
|
||||
[roles.peer]
|
||||
send_topics = ["*"]
|
||||
accept_topics = ["*"]
|
||||
"#;
|
||||
|
||||
/// A server running on a free port, its CA and folder.
|
||||
struct Running {
|
||||
folder: PathBuf,
|
||||
ca: Ca,
|
||||
ca_issued: Issued,
|
||||
ca_certificate: String,
|
||||
server: Server,
|
||||
address: String,
|
||||
// Kept for the server's tasks to run.
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
@@ -68,19 +76,30 @@ impl Running {
|
||||
Running::start_with(name, "")
|
||||
}
|
||||
|
||||
/// With more `[server]` settings.
|
||||
/// With more `[server]` settings (and sections after them).
|
||||
fn start_with(name: &str, settings: &str) -> Running {
|
||||
let folder = folder(name);
|
||||
let issued = Ca::create("Test CA", 10).unwrap();
|
||||
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
|
||||
let ca = Ca::create("Test CA", 10).unwrap();
|
||||
Running::start_in(folder(name), ca, "server-1", settings, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
/// Another server with the same CA, named `server`.
|
||||
fn peer(&self, name: &str, server: &str, settings: &str) -> Running {
|
||||
let ca = self.ca_issued.clone();
|
||||
Running::start_in(folder(name), ca, server, settings, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
fn start_in(
|
||||
folder: PathBuf,
|
||||
ca_issued: Issued,
|
||||
name: &str,
|
||||
settings: &str,
|
||||
bind: &str,
|
||||
) -> Running {
|
||||
let ca = Ca::load(&ca_issued.certificate, &ca_issued.key).unwrap();
|
||||
let server = ca
|
||||
.issue(
|
||||
&Identity::new("server-1", &["peer"]).unwrap(),
|
||||
Usage::Server,
|
||||
10,
|
||||
)
|
||||
.issue(&Identity::new(name, &["peer"]).unwrap(), Usage::Server, 10)
|
||||
.unwrap();
|
||||
std::fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
|
||||
std::fs::write(folder.join("ca.crt"), &ca_issued.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.crt"), &server.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.key"), &server.key).unwrap();
|
||||
let config = CONFIG.replace(
|
||||
@@ -91,25 +110,50 @@ impl Running {
|
||||
),
|
||||
);
|
||||
std::fs::write(folder.join("server.toml"), config).unwrap();
|
||||
Running::run(folder, ca, ca_issued, bind)
|
||||
}
|
||||
|
||||
/// Stopped as `bakashrot-server` stops, `meanwhile` run, then started
|
||||
/// again on the same database and address.
|
||||
fn restart_after(self, meanwhile: impl FnOnce()) -> Running {
|
||||
let Running {
|
||||
folder,
|
||||
ca,
|
||||
ca_issued,
|
||||
server,
|
||||
address,
|
||||
runtime,
|
||||
..
|
||||
} = self;
|
||||
runtime.block_on(server.stop());
|
||||
runtime.shutdown_background();
|
||||
meanwhile();
|
||||
Running::run(folder, ca, ca_issued, &address)
|
||||
}
|
||||
|
||||
/// Its `server.toml` served on `bind`, retention and replication going.
|
||||
fn run(folder: PathBuf, ca: Ca, ca_issued: Issued, bind: &str) -> Running {
|
||||
let config = Config::load(&folder.join("server.toml")).unwrap();
|
||||
let server = Server::start(config).unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let listener = runtime
|
||||
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
|
||||
.block_on(tokio::net::TcpListener::bind(bind))
|
||||
.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let serving = server.clone();
|
||||
runtime.spawn(async move { serving.serve(listener).await });
|
||||
let retaining = server.clone();
|
||||
runtime.spawn(async move { retaining.apply_retention().await });
|
||||
let replicating = server.clone();
|
||||
runtime.spawn(async move { replicating.replicate().await });
|
||||
Running {
|
||||
folder,
|
||||
ca,
|
||||
ca_certificate: issued.certificate,
|
||||
ca_certificate: ca_issued.certificate.clone(),
|
||||
ca_issued,
|
||||
server,
|
||||
address,
|
||||
_runtime: runtime,
|
||||
runtime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -997,6 +1041,44 @@ fn attachment_edges() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_cleanly() {
|
||||
// 8 nodes pushing flat out, the server stopped under them: every push
|
||||
// answered is stored, the ones after refused as the server stopping.
|
||||
let running = Running::start("stop");
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|n| {
|
||||
let mut client = running
|
||||
.connect(&running.issue(&format!("n{n}"), &["sensor"]))
|
||||
.unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let mut answered = 0;
|
||||
loop {
|
||||
match client.push("logs", "{}") {
|
||||
Ok(id) => answered = id,
|
||||
Err(error) => return (answered, error.code()),
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
running.runtime.block_on(running.server.stop());
|
||||
let stopped: Vec<(u64, u32)> = threads.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
|
||||
let running = running.restart_after(|| {});
|
||||
let mut reader = running
|
||||
.connect(&running.issue("reader", &["reader"]))
|
||||
.unwrap();
|
||||
for (n, (answered, code)) in stopped.into_iter().enumerate() {
|
||||
assert_eq!(code, ErrorCode::ServerError.code(), "n{n}");
|
||||
assert!(answered > 0, "n{n} pushed nothing");
|
||||
let latest = reader.get_messages("logs", &format!("n{n}"), None, 1);
|
||||
// The last push may have been committed after its answer was lost.
|
||||
assert!(latest.unwrap().messages[0].id >= answered, "n{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retention() {
|
||||
// logs kept 2 s, sensors forever; looked at every second.
|
||||
@@ -1050,3 +1132,393 @@ fn retention() {
|
||||
let latest = kitchen.get_messages("logs", "kitchen", None, 1).unwrap();
|
||||
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
|
||||
/// 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
|
||||
/// with `cargo test --release -p bakashrot-server --test end_to_end
|
||||
/// replication_rate -- --ignored --nocapture` (`SYNC`: `full`, the
|
||||
/// default, or `normal`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn replication_rate() {
|
||||
let env =
|
||||
|name: &str, default: u64| std::env::var(name).map_or(default, |v| v.parse().unwrap());
|
||||
let (nodes, seconds) = (env("NODES", 10), env("SECONDS", 30));
|
||||
let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into());
|
||||
let batch = env("BATCH", 1000);
|
||||
// Free ports first: every server's push_to names the others.
|
||||
let addresses: Vec<String> = (0..4)
|
||||
.map(|_| {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap().to_string()
|
||||
})
|
||||
.collect();
|
||||
let ca = Ca::create("Bench CA", 10).unwrap();
|
||||
let servers: Vec<Running> = (0..4)
|
||||
.map(|n| {
|
||||
let push_to = match n {
|
||||
0 => addresses[1..].join("\", \""),
|
||||
_ => addresses[0].clone(),
|
||||
};
|
||||
let settings = format!(
|
||||
"synchronous = \"{sync}\"\n\n[replication]\npush_to = [\"{push_to}\"]\n\
|
||||
accept_from = [\"127.0.0.1\"]\nbatch_size = {batch}\n"
|
||||
);
|
||||
let name = format!("server-{n}");
|
||||
Running::start_in(folder(&name), ca.clone(), &name, &settings, &addresses[n])
|
||||
})
|
||||
.collect();
|
||||
let json = format!(
|
||||
r#"{{"kind":"temp","value":21.37,"pad":"{}"}}"#,
|
||||
"x".repeat(160)
|
||||
);
|
||||
let clients: Vec<Client> = servers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(s, server)| {
|
||||
(0..nodes).map(move |n| {
|
||||
server
|
||||
.connect(&server.issue(&format!("s{s}n{n}"), &["sensor"]))
|
||||
.unwrap()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut analysts: Vec<Client> = servers
|
||||
.iter()
|
||||
.map(|server| {
|
||||
server
|
||||
.connect(&server.issue("analyst", &["analyst"]))
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let mut counts = || -> Vec<u64> {
|
||||
analysts
|
||||
.iter_mut()
|
||||
.map(|analyst| {
|
||||
let result = analyst.query("SELECT COUNT(*) AS n FROM data").unwrap();
|
||||
result[r#"{"columns":["n"],"rows":[[""#.len()..result.len() - 4]
|
||||
.parse()
|
||||
.unwrap()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let start = Instant::now();
|
||||
let until = start + Duration::from_secs(seconds);
|
||||
let threads: Vec<_> = clients
|
||||
.into_iter()
|
||||
.map(|mut client| {
|
||||
let json = json.clone();
|
||||
std::thread::spawn(move || {
|
||||
let (mut pushed, mut slowest) = (0u64, Duration::ZERO);
|
||||
while Instant::now() < until {
|
||||
let push = Instant::now();
|
||||
client.push("logs", &json).unwrap();
|
||||
slowest = slowest.max(push.elapsed());
|
||||
pushed += 1;
|
||||
}
|
||||
(pushed, slowest)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<(u64, Duration)> = threads.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
let pushing = start.elapsed().as_secs_f64();
|
||||
let total: u64 = results.iter().map(|(pushed, _)| pushed).sum();
|
||||
let slowest = results.iter().map(|(_, slowest)| *slowest).max().unwrap();
|
||||
let at_end = counts();
|
||||
let drain = Instant::now();
|
||||
while counts().iter().any(|&count| count < total) {
|
||||
assert!(drain.elapsed() < Duration::from_secs(300), "not drained");
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
let drained = drain.elapsed().as_secs_f64();
|
||||
let behind: Vec<String> = at_end
|
||||
.iter()
|
||||
.map(|&count| format!("{:.1} s", (total - count) as f64 / (total as f64 / pushing)))
|
||||
.collect();
|
||||
println!(
|
||||
"{sync}, 4 servers x {nodes} nodes, {seconds} s: {total} pushes, {:.0}/s, slowest {} ms; \
|
||||
behind at the end (s of pushes; hub, leaves): {}; all everywhere {drained:.1} s later",
|
||||
total as f64 / pushing,
|
||||
slowest.as_millis(),
|
||||
behind.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
/// Waits up to 15 s for `done`, every 100 ms.
|
||||
fn wait_for(what: &str, mut done: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while !done() {
|
||||
assert!(Instant::now() < deadline, "{what}: not in time");
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication() {
|
||||
// a pushes to b (and c); b takes from 127.0.0.1, c from elsewhere only.
|
||||
let b = Running::start_with(
|
||||
"replication-b",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n",
|
||||
);
|
||||
let c = b.peer(
|
||||
"replication-c",
|
||||
"server-c",
|
||||
"\n[replication]\naccept_from = [\"10.9.9.9\"]\n",
|
||||
);
|
||||
let a = b.peer(
|
||||
"replication-a",
|
||||
"server-a",
|
||||
&format!(
|
||||
"\n[replication]\npush_to = [\"{}\", \"{}\"]\nsync_interval = \"1s\"\n\
|
||||
retry_delay = \"1s\"\n",
|
||||
b.address, c.address
|
||||
),
|
||||
);
|
||||
let kitchen = a.issue("kitchen", &["sensor", "reader"]);
|
||||
let mut on_a = a.connect(&kitchen).unwrap();
|
||||
let file = bytes(2 * MIB + 5, 9);
|
||||
on_a.push_with_attachment("logs", "{\"n\":1}", &mut Cursor::new(&file))
|
||||
.unwrap();
|
||||
on_a.push("logs", "{\"n\":2}").unwrap();
|
||||
on_a.push("logs", "not json").unwrap();
|
||||
on_a.push("sensors", "{}").unwrap();
|
||||
|
||||
// b gets them all, by name, with their ids, times and attachment.
|
||||
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||
let read = |client: &mut Client, topic: &str| {
|
||||
client
|
||||
.get_messages(topic, "kitchen", Some(0), 100)
|
||||
.map(|answer| answer.messages)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
wait_for("the messages on b", || {
|
||||
read(&mut on_b, "logs").len() == 3 && read(&mut on_b, "sensors").len() == 1
|
||||
});
|
||||
let (sent, got) = (read(&mut on_a, "logs"), read(&mut on_b, "logs"));
|
||||
let fields = |m: &bakashrot_proto::packets::MessageEntry| (m.id, m.pushed_at, m.data.clone());
|
||||
assert_eq!(
|
||||
sent.iter().map(fields).collect::<Vec<_>>(),
|
||||
got.iter().map(fields).collect::<Vec<_>>()
|
||||
);
|
||||
wait_for("the attachment on b", || {
|
||||
let mut out = Vec::new();
|
||||
on_b.get_attachment("logs", "kitchen", 1, &mut out).is_ok() && out == file
|
||||
});
|
||||
|
||||
// c doesn't take from a: not in its accept_from.
|
||||
let mut analyst = c.connect(&c.issue("analyst", &["analyst"])).unwrap();
|
||||
assert_eq!(
|
||||
analyst.query("SELECT COUNT(*) AS n FROM messages").unwrap(),
|
||||
r#"{"columns":["n"],"rows":[["0"]]}"#
|
||||
);
|
||||
|
||||
// One way: b's own pushes don't go to a (b has no push_to).
|
||||
let mut garage = b.connect(&b.issue("garage", &["sensor"])).unwrap();
|
||||
garage.push("logs", "{}").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2500));
|
||||
assert_eq!(
|
||||
code(
|
||||
on_a.get_messages("logs", "garage", Some(0), 10)
|
||||
.unwrap_err()
|
||||
),
|
||||
ErrorCode::UnknownName.code()
|
||||
);
|
||||
|
||||
// b stopped: a links again once it's back, sends what came meanwhile,
|
||||
// ids go on. Meanwhile a's copy of #6's attachment got damaged.
|
||||
drop((on_b, garage));
|
||||
let b = b.restart_after(|| {
|
||||
assert_eq!(on_a.push("logs", "{\"n\":4}").unwrap(), 4);
|
||||
assert_eq!(on_a.push("logs", "{\"n\":5}").unwrap(), 5);
|
||||
let other = bytes(MIB + 1, 3);
|
||||
let id = on_a
|
||||
.push_with_attachment("logs", "{\"n\":6}", &mut Cursor::new(&other))
|
||||
.unwrap();
|
||||
assert_eq!(id, 6);
|
||||
let raw = rusqlite::Connection::open(a.folder.join("bakashrot.sqlite")).unwrap();
|
||||
raw.execute(
|
||||
"UPDATE attachment_parts SET part_data = zeroblob(length(part_data)) \
|
||||
WHERE key = (SELECT max(key) FROM attachment_parts)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap();
|
||||
wait_for("the messages on b, restarted", || {
|
||||
read(&mut on_b, "logs")
|
||||
.iter()
|
||||
.map(|m| m.id)
|
||||
.collect::<Vec<_>>()
|
||||
== [1, 2, 3, 4, 5, 6]
|
||||
});
|
||||
|
||||
// b refuses the damaged copy; a finds its own damaged and asks for it
|
||||
// again, instead of sending it again and again.
|
||||
wait_for("a's damaged copy noticed", || {
|
||||
on_a.get_attachment("logs", "kitchen", 6, &mut Vec::new())
|
||||
.is_err_and(|error| error.code() == ErrorCode::NotReady.code())
|
||||
});
|
||||
assert_eq!(
|
||||
code(
|
||||
on_b.get_attachment("logs", "kitchen", 6, &mut Vec::new())
|
||||
.unwrap_err()
|
||||
),
|
||||
ErrorCode::NotReady.code()
|
||||
);
|
||||
}
|
||||
|
||||
/// A server's `SyncState`, asked over `raw`.
|
||||
fn sync_state(raw: &mut Raw) -> SyncState {
|
||||
raw.send(SyncStateRequest {});
|
||||
match raw.receive() {
|
||||
Some(Packet::SyncState(state)) => state,
|
||||
other => panic!("expected a SyncState, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication_edges() {
|
||||
// The test plays the peer, over a raw connection.
|
||||
let running = Running::start_with(
|
||||
"replication-edges",
|
||||
"\n[replication]\naccept_from = [\"127.0.0.1\"]\n\n[retention]\nold = \"1h\"\n",
|
||||
);
|
||||
let peer = running.issue("server-x", &["peer"]);
|
||||
let mut raw = Raw::connect(&running, &peer);
|
||||
let state = sync_state(&mut raw);
|
||||
assert_eq!(
|
||||
(state.topics, state.nodes),
|
||||
(vec!["*".into()], vec!["*".into()])
|
||||
);
|
||||
assert!(state.heads.is_empty() && state.missing.is_empty());
|
||||
|
||||
let file = bytes(2 * MIB + 1, 5);
|
||||
let message = |id, pushed_at, attachment| ReplicatedMessage {
|
||||
id,
|
||||
pushed_at,
|
||||
data: format!("m{id}"),
|
||||
attachment,
|
||||
};
|
||||
let now = 1_800_000_000_000;
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![
|
||||
message(
|
||||
3,
|
||||
now,
|
||||
Some(Attachment {
|
||||
size: file.len() as u64,
|
||||
sha256: sha256(&file),
|
||||
}),
|
||||
),
|
||||
message(7, now, None),
|
||||
],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 7 }.into()));
|
||||
// Past its age here: not stored, but counted as received.
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "old".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(1, 1000, None)],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 1 }.into()));
|
||||
let mut analyst = running
|
||||
.connect(&running.issue("analyst", &["analyst"]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
analyst
|
||||
.query("SELECT group_concat(topic || '#' || message_id) AS n FROM messages")
|
||||
.unwrap(),
|
||||
r#"{"columns":["n"],"rows":[["logs#3,logs#7"]]}"#
|
||||
);
|
||||
let state = sync_state(&mut raw);
|
||||
let heads: Vec<_> = state
|
||||
.heads
|
||||
.iter()
|
||||
.map(|head| (head.topic.as_str(), head.last_id))
|
||||
.collect();
|
||||
assert_eq!(heads, [("logs", 7), ("old", 1)]);
|
||||
let missing: Vec<_> = state
|
||||
.missing
|
||||
.iter()
|
||||
.map(|missing| (missing.message_id, missing.next_part))
|
||||
.collect();
|
||||
assert_eq!(missing, [(3, 0)]);
|
||||
|
||||
// From the part it needs only.
|
||||
let ask = |raw: &mut Raw, message_id, from_part| {
|
||||
raw.send(ReplicateAttachment {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
message_id,
|
||||
from_part,
|
||||
})
|
||||
};
|
||||
ask(&mut raw, 3, 1);
|
||||
raw.refused(ErrorCode::InvalidRequest);
|
||||
ask(&mut raw, 7, 0);
|
||||
raw.refused(ErrorCode::NotFound);
|
||||
|
||||
// Cut after its first part: it goes on from the second.
|
||||
ask(&mut raw, 3, 0);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
raw.send(AttachmentPart {
|
||||
data: file[..MIB].to_vec(),
|
||||
});
|
||||
drop(raw);
|
||||
let mut raw = Raw::connect(&running, &peer);
|
||||
wait_for("the first part kept", || {
|
||||
sync_state(&mut raw).missing[0].next_part == 1
|
||||
});
|
||||
ask(&mut raw, 3, 1);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
for part in file[MIB..].chunks(MIB) {
|
||||
raw.send(AttachmentPart {
|
||||
data: part.to_vec(),
|
||||
});
|
||||
}
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 3 }.into()));
|
||||
let mut reader = running
|
||||
.connect(&running.issue("watcher", &["reader"]))
|
||||
.unwrap();
|
||||
let mut out = Vec::new();
|
||||
reader.get_attachment("logs", "far", 3, &mut out).unwrap();
|
||||
assert!(out == file);
|
||||
assert!(sync_state(&mut raw).missing.is_empty());
|
||||
|
||||
// Not matching its SHA-256: refused, asked for again from the start.
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(
|
||||
8,
|
||||
now,
|
||||
Some(Attachment {
|
||||
size: 10,
|
||||
sha256: [0; 32],
|
||||
}),
|
||||
)],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 8 }.into()));
|
||||
ask(&mut raw, 8, 0);
|
||||
assert!(matches!(raw.receive(), Some(Packet::Continue(_))));
|
||||
raw.send(AttachmentPart { data: vec![1; 10] });
|
||||
raw.refused(ErrorCode::DataMismatch);
|
||||
assert_eq!(sync_state(&mut raw).missing[0].next_part, 0);
|
||||
|
||||
// A certificate whose roles take nothing: refused.
|
||||
let mut other = Raw::connect(&running, &running.issue("nosy", &["reader"]));
|
||||
let state = sync_state(&mut other);
|
||||
assert!(state.topics.is_empty() && state.heads.is_empty());
|
||||
other.send(ReplicateMessages {
|
||||
topic: "logs".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(9, now, None)],
|
||||
});
|
||||
other.refused(ErrorCode::NotAllowed);
|
||||
}
|
||||
|
||||
@@ -156,14 +156,16 @@ impl Batch<'_> {
|
||||
/// Stores messages a peer sent for `topic` and `node`, with their own
|
||||
/// ids, in order; ones already here are kept as they are. Their
|
||||
/// attachments are noted, to be asked for (`replicating`), or never if
|
||||
/// bigger than `max_attachment_size` (`too_big`). Returns the topic and
|
||||
/// node's last id.
|
||||
/// bigger than `max_attachment_size` (`too_big`). Ones pushed before
|
||||
/// `skip_before` (ms, past their age here) aren't stored, but count as
|
||||
/// received. Returns the topic and node's last id.
|
||||
pub fn replicate(
|
||||
&mut self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
messages: &[ReplicatedMessage],
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
) -> Result<u64> {
|
||||
self.atomic(|db| {
|
||||
let (stream, mut last_id) = stream(db, topic, node)?;
|
||||
@@ -177,6 +179,11 @@ impl Batch<'_> {
|
||||
if !(1..=MAX_MESSAGE_ID).contains(&message.id) {
|
||||
return Err(Error::Invalid(format!("message id {}", message.id)));
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
if message.pushed_at < skip_before {
|
||||
continue;
|
||||
}
|
||||
let key = message_key(stream, message.id);
|
||||
let stored = insert.execute((key, message.pushed_at, &message.data))? == 1;
|
||||
if let (true, Some(attachment)) = (stored, &message.attachment) {
|
||||
@@ -187,9 +194,10 @@ impl Batch<'_> {
|
||||
};
|
||||
attach.execute((key, attachment.size, &attachment.sha256, state))?;
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
}
|
||||
// The skipped ones move it too.
|
||||
db.prepare_cached("UPDATE streams SET last_id = ?2 WHERE stream_id = ?1")?
|
||||
.execute((stream, last_id))?;
|
||||
Ok(last_id)
|
||||
})
|
||||
}
|
||||
@@ -214,6 +222,26 @@ impl Batch<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A ready attachment found not to match its SHA-256 (a damaged
|
||||
/// disk, a bug): its parts go, it's asked for again from its peers
|
||||
/// (`replicating`), and not served meanwhile.
|
||||
pub fn damaged(&mut self, attachment_id: i64) -> Result<()> {
|
||||
self.atomic(|db| {
|
||||
if attachment(db, attachment_id)?.0 != AttachmentState::Ready {
|
||||
return Err(Error::Invalid(format!(
|
||||
"attachment {attachment_id} isn't a ready one"
|
||||
)));
|
||||
}
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
db.prepare_cached(
|
||||
"UPDATE attachments SET state = 'replicating', received = 0 \
|
||||
WHERE attachment_id = ?1",
|
||||
)?
|
||||
.execute([attachment_id])?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Retention: deletes `topic`'s messages pushed before `cutoff` (ms),
|
||||
/// `limit` at most (call again while it returns `limit`). Each stream
|
||||
/// is read from its oldest message and stops at the first one it keeps:
|
||||
@@ -381,8 +409,21 @@ fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes every upload: at start, none of them can be pushed any more.
|
||||
pub(crate) fn delete_uploads(db: &Connection) -> Result<()> {
|
||||
/// At start: deletes every upload (none of them can be pushed any more),
|
||||
/// and starts over the replicated attachments all of whose parts came but
|
||||
/// weren't checked (stopped in between).
|
||||
pub(crate) fn clean_up(db: &Connection) -> Result<()> {
|
||||
let unchecked: Vec<i64> = db
|
||||
.prepare(
|
||||
"SELECT attachment_id FROM attachments \
|
||||
WHERE state = 'replicating' AND received = size",
|
||||
)?
|
||||
.query_map([], |row| row.get(0))?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
for attachment_id in unchecked {
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
set_attachment(db, attachment_id, "received = ?2", 0)?;
|
||||
}
|
||||
let uploads: Vec<i64> = db
|
||||
.prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")?
|
||||
.query_map([], |row| row.get(0))?
|
||||
|
||||
@@ -98,7 +98,7 @@ impl Database {
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
crate::batch::delete_uploads(&transaction)?;
|
||||
crate::batch::clean_up(&transaction)?;
|
||||
transaction.commit()?;
|
||||
Ok(database)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,10 @@ use crate::{
|
||||
AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys,
|
||||
};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{Head, MessageEntry, Messages, MissingAttachment, StoredAttachment};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row};
|
||||
|
||||
/// About how many bytes of messages one answer carries: past it, the rest
|
||||
@@ -23,6 +26,11 @@ const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3";
|
||||
|
||||
/// A stream's messages after a key, as replication sends them.
|
||||
const TO_REPLICATE: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.sha256 \
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3";
|
||||
|
||||
/// A connection that reads.
|
||||
#[derive(Debug)]
|
||||
pub struct Reader {
|
||||
@@ -97,6 +105,48 @@ impl Reader {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A topic and node's messages after an id, as replication sends them:
|
||||
/// `limit` at most, about [`MESSAGES_BYTES`] at most (a bigger one
|
||||
/// alone). None once there are no more.
|
||||
pub fn to_replicate(
|
||||
&self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
after: u64,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ReplicatedMessage>> {
|
||||
let mut messages = Vec::new();
|
||||
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
|
||||
return Ok(messages);
|
||||
};
|
||||
let (_, last) = stream_keys(stream);
|
||||
let mut statement = self.connection.prepare_cached(TO_REPLICATE)?;
|
||||
let from = message_key(stream, after.min(MAX_MESSAGE_ID));
|
||||
let mut rows = statement.query((from, last, i64::from(limit)))?;
|
||||
let mut bytes = 0;
|
||||
while let Some(row) = rows.next()? {
|
||||
let data: String = row.get(2)?;
|
||||
if !messages.is_empty() && bytes + data.len() > MESSAGES_BYTES {
|
||||
break;
|
||||
}
|
||||
bytes += data.len();
|
||||
let attachment = match row.get::<_, Option<u64>>(3)? {
|
||||
Some(size) => Some(Sent {
|
||||
size,
|
||||
sha256: row.get(4)?,
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
messages.push(ReplicatedMessage {
|
||||
id: message_id(row.get(0)?),
|
||||
pushed_at: row.get(1)?,
|
||||
data,
|
||||
attachment,
|
||||
});
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Every topic with messages (or that had some), in order.
|
||||
pub fn topics(&self) -> Result<Vec<String>> {
|
||||
self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic")
|
||||
|
||||
@@ -316,6 +316,7 @@ fn replication() {
|
||||
replicated(12, 300, Some((50, sha))),
|
||||
],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -331,6 +332,7 @@ fn replication() {
|
||||
..replicated(5, 1, None)
|
||||
}],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -407,6 +409,7 @@ fn replication() {
|
||||
"garage",
|
||||
&[replicated(1, 1, Some((2 * PART as u64, sha)))],
|
||||
u64::MAX,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -420,9 +423,78 @@ fn replication() {
|
||||
("garage", 1)
|
||||
);
|
||||
|
||||
// What's sent on: after an id, with its attachments' SHA-256s.
|
||||
let sent = reader.to_replicate("logs", "kitchen", 5, 10).unwrap();
|
||||
let sent_ids: Vec<u64> = sent.iter().map(|m| m.id).collect();
|
||||
assert_eq!(sent_ids, [9, 12, 13]);
|
||||
assert_eq!(
|
||||
sent[0].attachment,
|
||||
Some(Sent {
|
||||
size: PART as u64 + 1,
|
||||
sha256: sha
|
||||
})
|
||||
);
|
||||
assert_eq!(sent[2].attachment, None);
|
||||
assert_eq!(
|
||||
reader.to_replicate("logs", "kitchen", 9, 1).unwrap()[0].id,
|
||||
12
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "kitchen", 13, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "nobody", 0, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// A damaged ready copy: its parts go, asked for again.
|
||||
writer.batch(|b| b.damaged(small.id)).unwrap();
|
||||
let again = reader.attachment("logs", "kitchen", 12).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(again.state, again.received),
|
||||
(AttachmentState::Replicating, 0)
|
||||
);
|
||||
assert!(reader.read_part(small.id, 0).is_err());
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.damaged(small.id)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
|
||||
// Past their age here: not stored, but counted.
|
||||
let last = writer
|
||||
.batch(|b| {
|
||||
b.replicate(
|
||||
"logs",
|
||||
"attic",
|
||||
&[
|
||||
replicated(1, 100, Some((50, sha))),
|
||||
replicated(2, 200, None),
|
||||
replicated(3, 300, None),
|
||||
],
|
||||
1000,
|
||||
201,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(last, 3);
|
||||
assert_eq!(
|
||||
ids(&reader.messages("logs", "attic", Some(0), 10).unwrap()),
|
||||
[3]
|
||||
);
|
||||
assert_eq!(reader.last_id("logs", "attic").unwrap(), 3);
|
||||
let skipped = writer
|
||||
.batch(|b| b.replicate("logs", "cellar", &[replicated(7, 100, None)], 1000, 201))
|
||||
.unwrap();
|
||||
assert_eq!((skipped, reader.last_id("logs", "cellar").unwrap()), (7, 7));
|
||||
|
||||
// Ids out of range.
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0)),
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0, 0)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
}
|
||||
|
||||
@@ -110,8 +110,9 @@ attachment=None)` (the topic required; the attachment bytes or a path),
|
||||
`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`.
|
||||
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
|
||||
refused, either way, or no role allowed), `BakaShrotError`. The DLL is
|
||||
looked for next to the module, or `BAKASHROT_DLL`. The wheel comes with the
|
||||
release (step 12).
|
||||
looked for next to the module, or `BAKASHROT_DLL`. The release has a
|
||||
wheel with the library in it (`pip install bakashrot-*.whl`, nothing else:
|
||||
`bindings/python/make_wheel.py`, `../README.md`, "Releases").
|
||||
|
||||
## PureBasic
|
||||
|
||||
|
||||
+16
-7
@@ -12,7 +12,7 @@ Decided in `../../revamp.md`, "Decided".
|
||||
|---|---|
|
||||
| `[server]` | where it listens, the certificate files, the database, its topics, how pushes are flushed, attachments, retention's pace |
|
||||
| `[retention]` | how long each topic's messages are kept |
|
||||
| `[replication]` | the peers it dials, the topics replicated at all, retry and sync pace, batch size |
|
||||
| `[replication]` | the servers it sends to and takes from, the topics replicated at all, retry and sync pace, batch size |
|
||||
| `[roles.<name>]` | what certificates with that role may do |
|
||||
|
||||
Unknown keys are refused, so a typo or a key of the old ini is caught.
|
||||
@@ -47,11 +47,20 @@ default topic: a push always names its topic (protocol 7 has none).
|
||||
|
||||
## Peers
|
||||
|
||||
Peers are roles too: a server whose certificate has a role with
|
||||
`send_topics` or `accept_topics` replicates, whichever end dialed. The
|
||||
config only lists where to dial (`[replication] peers`, `host:port`): a
|
||||
certificate can't say where a server is. Each side applies its own roles
|
||||
to the other, as before each side had its own peer section.
|
||||
Who replicates with whom is each server's config, by address (not the
|
||||
certificates: that would mean reissuing them):
|
||||
|
||||
- **`[replication] push_to`:** the servers it dials and sends to,
|
||||
`host:port`.
|
||||
- **`[replication] accept_from`:** the servers it takes replicated
|
||||
messages from, IP addresses or hostnames without a port, `"*"` for
|
||||
all; none by default. Clients aren't concerned: they push wherever
|
||||
their roles allow.
|
||||
|
||||
A link carries messages one way: the server that dials sends, the one
|
||||
dialed takes them. What's sent and taken is still the roles': the other
|
||||
server's certificate's roles here, their `send_*` for what's sent to it,
|
||||
their `accept_*` for what's taken from it.
|
||||
|
||||
`[replication] replicated_topics`, optional, filters every peer's
|
||||
replication whatever its roles say: an edge node that keeps some topics to
|
||||
@@ -85,7 +94,7 @@ server; each server has its own.
|
||||
|---|---|
|
||||
| `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] peers` (addresses), the lists in the peer's roles |
|
||||
| `[BakaShrot.Peer.*]`: `Host`, `Port`, `Node`, `PublicKey`, topic and node lists | `[replication] push_to` and `accept_from` (addresses), the lists in the peer's roles |
|
||||
| `ReplicatingTopics` | each peer role's `send_topics` / `accept_topics`; `replicated_topics` filters them all |
|
||||
| topic and node ids, pins, ranges, `[BakaShrot.Nodes]` | names only: ids are the database's |
|
||||
| `DefaultTopic` | dropped: a push always names its topic |
|
||||
|
||||
@@ -135,7 +135,7 @@ Replicating P: SyncStateRequest S: SyncState
|
||||
client asks again `from_part` the next one it needs.
|
||||
- **Replication:** `SyncState` is all a check-in needs. The peer compares
|
||||
it with what it has, by name, sends the messages the server lacks in
|
||||
batches of up to `PeerBatchSize` (about 64 KiB, a bigger
|
||||
batches of up to `batch_size` messages and about 1 MiB (a bigger
|
||||
message alone), then the attachments it listed.
|
||||
|
||||
## Rules
|
||||
|
||||
+135
-11
@@ -5,10 +5,9 @@ and `crates/bakashrot-client` (the blocking client library the C DLL will
|
||||
wrap). Decided in `../../revamp.md`, "Decided" (2026-11-13). What goes over
|
||||
the wire: `protocol.md`.
|
||||
|
||||
**Status:** steps 5, 6, 9 and 10: connecting, pushes and their
|
||||
attachments, messages, attachments, names, queries, retention.
|
||||
Replication (step 11) is refused
|
||||
(`InvalidRequest`, "isn't answered yet") until its step.
|
||||
**Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their
|
||||
attachments, messages, attachments, names, queries, retention,
|
||||
replication, stopping cleanly. Every request of protocol 7 is answered.
|
||||
|
||||
## Running
|
||||
|
||||
@@ -17,20 +16,47 @@ bakashrot-server server.toml
|
||||
```
|
||||
|
||||
The config (`config.md`) gives where to listen, the certificates, the CRL,
|
||||
the database, the topics and the roles. Logs go to the console
|
||||
(`tracing`); Ctrl+C stops it. Running as a service, console commands:
|
||||
step 12.
|
||||
the database, the topics and the roles. Decided 2026-11-14
|
||||
(`../../revamp.md`, "Operations"):
|
||||
|
||||
- **Stopping:** SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its
|
||||
console closed on Windows. It stops taking connections and writes
|
||||
what was queued for the database (`Server::stop`): every push
|
||||
answered is stored, the ones after are refused (`ServerError`, "the
|
||||
server is stopping"), then it exits with 0. Nothing else to wait for:
|
||||
a client whose push wasn't answered pushes it again (at least once).
|
||||
- **No console commands** (the old `quit`, `restart`, `vacuum`, `names`,
|
||||
`help`): it needs no console, a service manager runs it as is. `names`
|
||||
is `bakashrot list`, `restart` a stop and a start. Maybe an admin
|
||||
channel later.
|
||||
- **Logs go to the console** (stdout, `tracing`), without colours when
|
||||
it isn't a terminal: redirect them, or let systemd or Docker keep
|
||||
them. `BAKASHROT_LOG` sets the level: `error`, `warn`, `info` (the
|
||||
default), `debug`, `trace`.
|
||||
- **No Windows service mode:** a tool like NSSM runs it as one, stopping
|
||||
it with Ctrl+C.
|
||||
|
||||
A systemd unit, for example:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
ExecStart=/opt/bakashrot/bakashrot-server /etc/bakashrot/server.toml
|
||||
User=bakashrot
|
||||
Restart=on-failure
|
||||
# SIGTERM, then 90 s at most: far more than a stop takes.
|
||||
```
|
||||
|
||||
## Inside the server
|
||||
|
||||
| What | Where | How |
|
||||
|---|---|---|
|
||||
| Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time |
|
||||
| Writes | one writer thread | a queue of every write (pushes, uploads and their parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups |
|
||||
| Writes | one writer thread | a queue of every write (pushes, uploads and their parts, replicated messages and parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups |
|
||||
| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused |
|
||||
| WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) |
|
||||
| The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays |
|
||||
| Retention | a task, at start then every `retention_interval` (1 min) | below |
|
||||
| Replication | a task per server of `push_to` | below: links kept up, a check-in every `sync_interval` (5 s) |
|
||||
|
||||
## Retention
|
||||
|
||||
@@ -45,7 +71,56 @@ Each topic's count is logged ("deleted 3 messages of topic 'logs'").
|
||||
than the one before it (a clock set back) waits for that one.
|
||||
- **Ids go on:** a stream's last id stays, the next push takes the next.
|
||||
- **"May be" deleted past its age:** up to `retention_interval` later.
|
||||
- **Each server its own:** a peer's ages are its own (step 11).
|
||||
- **Each server its own:** a peer's ages are its own. What a peer sends
|
||||
already past this server's age isn't stored, but counts as received:
|
||||
it isn't sent again.
|
||||
|
||||
## Replication
|
||||
|
||||
Decided in `../../revamp.md` ("Replication by address", 2026-11-14).
|
||||
Each server's config says who it replicates with, by address
|
||||
(`config.md`, "Peers"): `push_to`, the servers it dials and sends to;
|
||||
`accept_from`, the servers whose messages it takes (`"*"` for all). A link
|
||||
carries messages one way, from the server that dials to the one dialed;
|
||||
the other way is the other server's own `push_to`.
|
||||
|
||||
**Sending** (`push_to.rs`): a link to each server of `push_to`, as a
|
||||
client with this server's certificate; a failed or dropped one is dialed
|
||||
again after `retry_delay` (10 s), its failure logged once until it
|
||||
changes. It checks in from the start, then again at once if it sent
|
||||
something (so it keeps up under load), after `sync_interval` (5 s)
|
||||
otherwise:
|
||||
|
||||
1. `SyncStateRequest`: the other server answers what it takes from this
|
||||
one (topics and nodes, patterns included), its last id in each topic
|
||||
and node, and the attachments it lacks (256 at most).
|
||||
2. **The messages:** for each topic and node here that it takes and that
|
||||
its roles here may be sent (`send_topics`, `send_nodes`,
|
||||
`replicated_topics`), and where it's behind, the messages after its
|
||||
last id, `batch_size` (1000) at a time and about 1 MiB at most (a
|
||||
bigger one alone), each batch answered before the next. A refusal
|
||||
leaves that topic and node for the next check-in.
|
||||
3. **The attachments it lacks:** those this server has ready, from the
|
||||
part it needs. One it says doesn't match its SHA-256 is read back
|
||||
here: damaged (a disk, a bug), this server's copy is dropped and asked
|
||||
for again from its own peers (`replicating`, not served meanwhile),
|
||||
instead of sent again at every check-in (the old open item 3).
|
||||
|
||||
**Receiving** (`accept_from.rs`): replication requests are answered only
|
||||
if the connection comes from `accept_from` (a hostname looked up at its
|
||||
first request, `NotAllowed` otherwise), and only for what its roles'
|
||||
`accept_topics` / `accept_nodes` allow (`NotAllowed`). Messages keep
|
||||
their ids and `pushed_at`; ones already here are kept as they are; one
|
||||
past this server's age is only counted. An attachment comes after its
|
||||
message (`replicating`, `NotReady` to readers), from the part this server
|
||||
needs, the parts it had read back for the SHA-256; matching, it's ready,
|
||||
otherwise started over (`DataMismatch`). A stop between its last part
|
||||
and the check: started over at the next start.
|
||||
|
||||
**One server per node** stays the config's rule, as in the old version
|
||||
(`OldSource/Design/ReplicationIssues.md` #1): a node pushing to two
|
||||
servers that replicate makes the same ids with different messages,
|
||||
undetected.
|
||||
|
||||
## A connection
|
||||
|
||||
@@ -150,6 +225,10 @@ each, 200-byte JSON, 20,000 pushes per client.
|
||||
here): 10 clients make groups of about 10. More clients, bigger groups.
|
||||
- **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and
|
||||
down in 0.5 s, the tool's start and the client's hashing included.
|
||||
- **Built for size** (`opt-level = "s"`, 2026-11-14; the numbers here
|
||||
were measured before, at 3): `normal` about 5% lower (36,900-38,100/s
|
||||
against 39,800-40,400), `full` the same (the disk's), attachments and
|
||||
tool commands the same. The programs and the DLL 25-31% smaller.
|
||||
|
||||
### Against the old server (2026-11-14)
|
||||
|
||||
@@ -176,6 +255,32 @@ JSON; the rest through the tools.
|
||||
off (`certificates.md`, "TLS").
|
||||
- **The old tool's read** printed a line at a time to the console API.
|
||||
|
||||
### Replication, against the old server (2026-11-14)
|
||||
|
||||
`replication_rate` (`tests/end_to_end.rs`, ignored by default) against
|
||||
the old `Tests/Bench/Bench-Replication.ps1 -Parts Ramp -Ramp 10x0`: 4
|
||||
servers in a Y (a hub sending to 3 leaves, each sending to the hub), 10
|
||||
nodes pushing to each as fast as they're answered for 30 s, 200-byte
|
||||
JSON, the same machine. The old one's pushers are its PureBasic bench
|
||||
client, the new one's `bakashrot-client` threads in the test's process.
|
||||
|
||||
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` |
|
||||
|---|---|---|---|---|
|
||||
| Pushes, all 4 servers | 16,638/s | 16,000-16,300/s | 33,895/s | 35,300-37,500/s |
|
||||
| Slowest push | 134 ms | 50-57 ms | 854 ms | 420-510 ms |
|
||||
| Behind when the pushes stop (most of a server) | 9.0 s of pushes | 0 | 11.4 s | 0.3-0.9 s |
|
||||
| Until every server has everything | 8.8 s | 0.3 s | 14.8 s | 5.3-5.6 s |
|
||||
|
||||
- **Keeping up:** a link checks in again at once after sending; before
|
||||
it waited `sync_interval` after every check-in, as the old one did, and
|
||||
pushes went faster (19,300/s `full`, 40,200/s `normal`) while the
|
||||
leaves fell 7-9 s behind and took 10-20 s to catch up.
|
||||
- **`batch_size` 1000** (was 100, the old `PeerBatchSize`): `normal` went
|
||||
from 27,500-31,500/s to 35,300-37,500/s, and from 2-2.5 s to under 1 s
|
||||
behind. Batches stay about 1 MiB at most.
|
||||
- **The last few seconds** with `normal` are a link's `sync_interval`:
|
||||
idle once caught up, it looks again 5 s later.
|
||||
|
||||
## Tests
|
||||
|
||||
`crates/bakashrot-server/tests/end_to_end.rs`, a server on a free port
|
||||
@@ -210,9 +315,28 @@ each:
|
||||
new one refused, others going on, a bad CRL refused);
|
||||
- six connections pushing at once (one id stream per node, none lost or
|
||||
doubled);
|
||||
- stopping cleanly: eight nodes pushing flat out, the server stopped
|
||||
under them: every push answered is there after a restart, the ones
|
||||
after refused as `ServerError`;
|
||||
- retention (`Retention-Test.ps1`'s local part): a topic's messages and
|
||||
their attachment deleted past its age, another topic kept forever, ids
|
||||
going on, a younger message kept through a pass.
|
||||
going on, a younger message kept through a pass;
|
||||
- replication (`Names-Test.ps1`'s replication, `Restart-Test.ps1`,
|
||||
`AttachmentEdges-Test.ps1`'s corruption): three servers of one CA, a
|
||||
pushing to b and c. b gets every message by name with its id, time
|
||||
and data, and the attachment; c, whose `accept_from` hasn't a, gets
|
||||
nothing; b's own pushes don't go to a. b stopped, a pushes meanwhile
|
||||
and its copy of an attachment gets damaged; b started again on its
|
||||
database and address: a links again, sends what b lacks, ids go on;
|
||||
b refuses the damaged copy, a finds it damaged and asks for it again;
|
||||
- replication edges (the test as the peer, a raw connection): what
|
||||
`SyncState` says, ids and last ids kept, a message past its age only
|
||||
counted, an attachment from the wrong part refused, one cut after its
|
||||
first part going on from the second (the first read back for the
|
||||
SHA-256), one not matching refused and asked for from the start, a
|
||||
certificate whose roles take nothing refused;
|
||||
- `replication_rate`, ignored by default: the benchmark above (`SYNC`,
|
||||
`NODES`, `SECONDS`, `BATCH`).
|
||||
|
||||
The old tests' tool parts (`--follow`, the output) are the tools' tests
|
||||
(`client.md`), their replication parts come with step 11.
|
||||
(`client.md`).
|
||||
|
||||
@@ -80,8 +80,9 @@ together, one disk flush for all.
|
||||
|---|---|
|
||||
| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new |
|
||||
| `start_upload(size, sha256)`, `write_part(id, part, data)`, `push_with_attachment(id, ...)`, `cancel_upload(id)` | a push with an attachment: its parts first, then the message with it |
|
||||
| `replicate(topic, node, messages, max_attachment_size)` | a peer's messages, with their ids; ones already here are kept |
|
||||
| `replicate(topic, node, messages, max_attachment_size, skip_before)` | a peer's messages, with their ids; ones already here are kept; ones pushed before `skip_before` (past their age here) only counted in `last_id` |
|
||||
| `write_part`, `finish_replicated(id, matches)` | a replicated attachment's parts, then ready (or started over) |
|
||||
| `damaged(id)` | a ready attachment found not matching its SHA-256: its parts dropped, asked for again (`replicating`) |
|
||||
| `delete_before(topic, cutoff, limit)` | retention |
|
||||
| `purge_attachments(max_parts)` | deleted messages' attachments |
|
||||
| `Writer::vacuum()` (outside a batch) | the file shrunk to what it holds: the old server's `vacuum` command |
|
||||
@@ -102,6 +103,7 @@ read while the writer writes. Answers are the protocol's own types:
|
||||
| `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys |
|
||||
| `topics()`, `nodes()` | the names with messages | `streams` |
|
||||
| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` |
|
||||
| `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys |
|
||||
| `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) |
|
||||
| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key |
|
||||
|
||||
@@ -116,7 +118,7 @@ One table, a state each:
|
||||
| State | Meaning | Next |
|
||||
|---|---|---|
|
||||
| `uploading` | a push's attachment, parts coming, no message yet (`message_key` NULL) | all parts and the SHA-256 match: the message is stored and the attachment `ready`, one transaction. Cut short: deleted with its parts (and every one left at start) |
|
||||
| `replicating` | its message came from a peer with its size and SHA-256; parts come after | asked from part `received / 1 MiB` on; all came and match: `ready`, else started over |
|
||||
| `replicating` | its message came from a peer with its size and SHA-256; parts come after | asked from part `received / 1 MiB` on; all came and match: `ready`, else started over (also at start, all came but not checked) |
|
||||
| `ready` | all here, checked | readable |
|
||||
| `too_big` | bigger than this server's `max_attachment_size` | never asked for; its message is kept |
|
||||
| `deleting` | its message was deleted (a trigger) | parts deleted in batches, then the row |
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
"""Builds a BakaShrot release for this machine's platform (Windows x64 or
|
||||
Linux x86-64), checks it works, and archives it:
|
||||
|
||||
python release.py [--skip-test]
|
||||
|
||||
Into target/dist/:
|
||||
bakashrot-<version>-<platform>/ the release:
|
||||
bakashrot-server, bakashrot, bakashrot-cert the programs
|
||||
bakashrot.dll / libbakashrot.so the client library (C)
|
||||
include/bakashrot.h its C header
|
||||
purebasic/*.pbi its PureBasic prototypes
|
||||
python/bakashrot.py the Python client, over it
|
||||
python/bakashrot-<version>-*.whl the same with the library in it
|
||||
server.example.toml, client.example.toml the configs, documented
|
||||
docs/ Source/docs/
|
||||
README.txt what's where, how to start
|
||||
LICENSE.txt, THIRD-PARTY.txt BakaShrot's (CC0), its dependencies'
|
||||
bakashrot-<version>-<platform>.zip (Windows) or .tar.gz (Linux)
|
||||
|
||||
No keys or certificates in it: bakashrot-cert makes them.
|
||||
|
||||
The check (unless --skip-test), in the release folder's _test/ (exes run
|
||||
from temp folders get blocked by antivirus here), deleted after unless
|
||||
it failed: a CA and certificates by bakashrot-cert, the
|
||||
server started on a free port with a throwaway database, then the tool
|
||||
pushing (and an attachment of 3 MB), reading back, listing, querying;
|
||||
Python through the library, then the wheel installed by pip and used with
|
||||
no path given; then the server stopped as a service manager would
|
||||
(SIGTERM, or Ctrl+Break on Windows), which must end cleanly.
|
||||
|
||||
The version is the workspace's (Cargo.toml), which bakashrot.py's
|
||||
__version__ must match. Needs Python 3.11+ (tomllib) and cargo (rustup).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import tomllib
|
||||
from datetime import datetime, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
WINDOWS = sys.platform == "win32"
|
||||
EXE = ".exe" if WINDOWS else ""
|
||||
LIBRARY = "bakashrot.dll" if WINDOWS else "libbakashrot.so"
|
||||
PROGRAMS = ["bakashrot-server", "bakashrot", "bakashrot-cert"]
|
||||
CRATES = ["bakashrot-server", "bakashrot-tools", "bakashrot-capi"]
|
||||
|
||||
CLIENT_EXAMPLE = """\
|
||||
# What the bakashrot tool and Python's Client.from_file() read, to connect
|
||||
# to a server. Paths are relative to this file's folder. See
|
||||
# docs/client.md.
|
||||
server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port
|
||||
ca = "ca.crt" # the CA's certificate (bakashrot-cert ca)
|
||||
certificate = "kitchen.crt" # this node's (bakashrot-cert issue --name kitchen ...)
|
||||
key = "kitchen.key"
|
||||
# crl = "ca.crl" # optional: certificates the CA revoked
|
||||
"""
|
||||
|
||||
|
||||
def fail(why):
|
||||
sys.exit(f"release.py: {why}")
|
||||
|
||||
|
||||
def run(command, cwd=HERE, **kwargs):
|
||||
"""Runs a command, its standard output; fails with its output if it does."""
|
||||
done = subprocess.run(command, cwd=cwd, capture_output=True, encoding="utf-8", errors="replace", **kwargs)
|
||||
if done.returncode != 0:
|
||||
fail(f"{' '.join(map(str, command))} failed ({done.returncode}):\n{done.stdout}{done.stderr}")
|
||||
return done.stdout
|
||||
|
||||
|
||||
def version():
|
||||
with open(os.path.join(HERE, "Cargo.toml"), "rb") as file:
|
||||
version = tomllib.load(file)["workspace"]["package"]["version"]
|
||||
with open(os.path.join(HERE, "bindings", "python", "bakashrot.py"), encoding="utf-8") as file:
|
||||
python = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE)
|
||||
if not python or python.group(1) != version:
|
||||
fail(f"bakashrot.py's __version__ isn't the workspace's {version}")
|
||||
return version
|
||||
|
||||
|
||||
def platform_name():
|
||||
machine = platform.machine().lower()
|
||||
if WINDOWS and machine in ("amd64", "x86_64"):
|
||||
return "windows-x64"
|
||||
if sys.platform.startswith("linux") and machine == "x86_64":
|
||||
return "linux-x64"
|
||||
fail(f"no release for {sys.platform} {machine}")
|
||||
|
||||
|
||||
def commit():
|
||||
try:
|
||||
sha = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=HERE,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
dirty = subprocess.run(["git", "status", "--porcelain", "."], cwd=HERE,
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
except OSError:
|
||||
return "unknown"
|
||||
return (sha or "unknown") + (" (with uncommitted changes)" if dirty else "")
|
||||
|
||||
|
||||
def third_party():
|
||||
"""Every crate built into the programs and the library (normal
|
||||
dependencies, this platform's), with its license files' text."""
|
||||
host = re.search(r"^host: (\S+)", run(["rustc", "-vV"]), re.MULTILINE).group(1)
|
||||
metadata = json.loads(run(["cargo", "metadata", "--format-version", "1", "--filter-platform", host]))
|
||||
packages = {package["id"]: package for package in metadata["packages"]}
|
||||
nodes = {node["id"]: node for node in metadata["resolve"]["nodes"]}
|
||||
roots = [id for id, package in packages.items() if package["name"] in CRATES]
|
||||
seen, stack = set(), list(roots)
|
||||
while stack:
|
||||
id = stack.pop()
|
||||
if id in seen:
|
||||
continue
|
||||
seen.add(id)
|
||||
for dep in nodes[id]["deps"]:
|
||||
if any(kind["kind"] is None for kind in dep["dep_kinds"]):
|
||||
stack.append(dep["pkg"])
|
||||
workspace = set(metadata["workspace_members"])
|
||||
used = sorted((packages[id] for id in seen - workspace), key=lambda p: (p["name"], p["version"]))
|
||||
lines = [
|
||||
"BakaShrot's programs and client library are built with these crates",
|
||||
"(their code is in them). Each one's license, then their license files,",
|
||||
"each text once with the crates it comes from.",
|
||||
"SQLite (in libsqlite3-sys) is in the public domain.",
|
||||
"",
|
||||
]
|
||||
lines += [f"{p['name']} {p['version']}: {p['license'] or 'see its files'}" for p in used]
|
||||
texts = {} # a license file's text: the crates' files it is
|
||||
for package in used:
|
||||
folder = os.path.dirname(package["manifest_path"])
|
||||
names = sorted(name for name in os.listdir(folder)
|
||||
if re.match(r"(LICEN[CS]E|COPYING|COPYRIGHT|NOTICE)", name, re.IGNORECASE)
|
||||
and os.path.isfile(os.path.join(folder, name)))
|
||||
for name in names:
|
||||
with open(os.path.join(folder, name), encoding="utf-8", errors="replace") as file:
|
||||
text = file.read().strip()
|
||||
texts.setdefault(text, []).append(f"{package['name']} {package['version']} ({name})")
|
||||
for text, sources in texts.items():
|
||||
lines += ["", "=" * 76, *sources, "=" * 76, "", text]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def readme(version, name):
|
||||
built = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
|
||||
rustc = run(["rustc", "--version"]).strip()
|
||||
return f"""\
|
||||
BakaShrot {version} ({name})
|
||||
|
||||
Built {built}, commit {commit()}, {rustc}.
|
||||
Licenses: BakaShrot is CC0 (LICENSE.txt); the crates built into it are
|
||||
listed in THIRD-PARTY.txt with their licenses.
|
||||
|
||||
A message store with replication: servers take messages per topic and node
|
||||
from clients with certificates of your own CA, store them in SQLite, and
|
||||
replicate them between servers. docs/ has the details (config.md,
|
||||
certificates.md, server.md, client.md, protocol.md).
|
||||
|
||||
Certificates (bakashrot-cert{EXE}; docs/certificates.md):
|
||||
bakashrot-cert ca --name "Home CA" ca.crt, ca.key (keep ca.key safe)
|
||||
bakashrot-cert issue --name server-1 --server a server's
|
||||
bakashrot-cert issue --name kitchen --role sensor a client's: its node, its roles
|
||||
bakashrot-cert revoke kitchen.crt ca.crl
|
||||
|
||||
The server (bakashrot-server{EXE} server.toml; docs/config.md, server.md):
|
||||
server.example.toml has every setting. It logs to the console
|
||||
(BAKASHROT_LOG=debug for more) and stops cleanly on SIGTERM or SIGINT
|
||||
(Linux), Ctrl+C, Ctrl+Break or its console closed (Windows): what was
|
||||
being written is committed first. No console commands: run it from a
|
||||
service manager (systemd, NSSM...) or a terminal.
|
||||
|
||||
The tool (bakashrot{EXE}, with a client.toml: client.example.toml;
|
||||
docs/client.md), --help on each command:
|
||||
bakashrot push logs '{{"t":21}}' bakashrot push logs @file.json -a photo.jpg
|
||||
bakashrot latest logs kitchen bakashrot messages logs kitchen [-f]
|
||||
bakashrot attachment logs kitchen 43 copy.jpg
|
||||
bakashrot list bakashrot query "SELECT * FROM messages"
|
||||
|
||||
The client library ({LIBRARY}): the BakaShrot_* exports, include/bakashrot.h
|
||||
for C, purebasic/ for PureBasic, python/bakashrot.py for Python (no
|
||||
dependencies; it looks for the library next to itself or in BAKASHROT_DLL).
|
||||
Or: pip install python/bakashrot-*.whl, the library inside.
|
||||
|
||||
Compatibility: protocol 7. Servers and clients must come from the same
|
||||
release: another version's connection is refused. Nothing from the old
|
||||
(PureBasic) BakaShrot is read: not its configs, keys or databases.
|
||||
"""
|
||||
|
||||
|
||||
def build():
|
||||
print("Building")
|
||||
command = ["cargo", "build", "--release", "--locked"]
|
||||
for crate in CRATES:
|
||||
command += ["-p", crate]
|
||||
run(command)
|
||||
return os.path.join(HERE, "target", "release")
|
||||
|
||||
|
||||
def package(built, version, name, out):
|
||||
print(f"Packaging {out}")
|
||||
for program in PROGRAMS:
|
||||
shutil.copy2(os.path.join(built, program + EXE), out)
|
||||
shutil.copy2(os.path.join(built, LIBRARY), out)
|
||||
bindings = os.path.join(HERE, "bindings")
|
||||
os.makedirs(os.path.join(out, "include"))
|
||||
shutil.copy2(os.path.join(bindings, "c", "bakashrot.h"), os.path.join(out, "include"))
|
||||
shutil.copytree(os.path.join(bindings, "purebasic"), os.path.join(out, "purebasic"))
|
||||
os.makedirs(os.path.join(out, "python"))
|
||||
shutil.copy2(os.path.join(bindings, "python", "bakashrot.py"), os.path.join(out, "python"))
|
||||
shutil.copytree(os.path.join(HERE, "docs"), os.path.join(out, "docs"))
|
||||
shutil.copy2(os.path.join(HERE, "crates", "bakashrot-config", "example.toml"),
|
||||
os.path.join(out, "server.example.toml"))
|
||||
write(os.path.join(out, "client.example.toml"), CLIENT_EXAMPLE)
|
||||
shutil.copy2(os.path.join(HERE, "..", "LICENSE"), os.path.join(out, "LICENSE.txt"))
|
||||
write(os.path.join(out, "THIRD-PARTY.txt"), third_party())
|
||||
write(os.path.join(out, "README.txt"), readme(version, name))
|
||||
wheel = run([sys.executable, "-B", os.path.join(bindings, "python", "make_wheel.py"),
|
||||
os.path.join(out, LIBRARY), os.path.join(out, "python"),
|
||||
os.path.join(out, "LICENSE.txt"), os.path.join(out, "THIRD-PARTY.txt")]).strip()
|
||||
print(f"Wheel: {os.path.basename(wheel)}")
|
||||
return wheel
|
||||
|
||||
|
||||
def write(path, text):
|
||||
"""A text file, with the platform's line endings."""
|
||||
with open(path, "w", encoding="utf-8") as file:
|
||||
file.write(text)
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def smoke_test(out, wheel):
|
||||
print("Testing the release")
|
||||
test = os.path.join(out, "_test")
|
||||
os.makedirs(test)
|
||||
tool = lambda program, *args: run([os.path.join(out, program + EXE), *args], cwd=test)
|
||||
|
||||
def expect(what, got, pattern):
|
||||
if not re.search(pattern, got, re.MULTILINE):
|
||||
fail(f"{what}: unexpected output:\n{got}")
|
||||
|
||||
tool("bakashrot-cert", "ca", "--name", "Release test CA")
|
||||
tool("bakashrot-cert", "issue", "--name", "server-1", "--server")
|
||||
tool("bakashrot-cert", "issue", "--name", "tester", "--role", "tester")
|
||||
port = free_port()
|
||||
write(os.path.join(test, "server.toml"), f"""\
|
||||
[server]
|
||||
listen = "127.0.0.1:{port}"
|
||||
ca = "ca.crt"
|
||||
certificate = "server-1.crt"
|
||||
key = "server-1.key"
|
||||
database = "test.sqlite"
|
||||
topics = ["releasetest"]
|
||||
|
||||
[roles.tester]
|
||||
push_topics = ["releasetest"]
|
||||
read_topics = ["*"]
|
||||
query = true
|
||||
""")
|
||||
write(os.path.join(test, "client.toml"), f"""\
|
||||
server = "127.0.0.1:{port}"
|
||||
ca = "ca.crt"
|
||||
certificate = "tester.crt"
|
||||
key = "tester.key"
|
||||
""")
|
||||
write(os.path.join(test, "message.json"), '{"release":"test","value":42}')
|
||||
attachment = os.urandom(3 * 1024 * 1024)
|
||||
with open(os.path.join(test, "attachment.bin"), "wb") as file:
|
||||
file.write(attachment)
|
||||
|
||||
log = open(os.path.join(test, "server.log"), "w")
|
||||
# Its own process group on Windows, to be sent Ctrl+Break alone.
|
||||
flags = subprocess.CREATE_NEW_PROCESS_GROUP if WINDOWS else 0
|
||||
server = subprocess.Popen([os.path.join(out, "bakashrot-server" + EXE), "server.toml"], cwd=test,
|
||||
stdout=log, stderr=subprocess.STDOUT, creationflags=flags)
|
||||
try:
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
if server.poll() is not None:
|
||||
fail(f"the server exited ({server.returncode}):\n{read_log(test)}")
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
|
||||
break
|
||||
except OSError:
|
||||
if time.monotonic() > deadline:
|
||||
fail(f"the server isn't listening on {port}:\n{read_log(test)}")
|
||||
time.sleep(0.1)
|
||||
|
||||
expect("push", tool("bakashrot", "push", "releasetest", "@message.json"), r"message #1\b")
|
||||
expect("push -a", tool("bakashrot", "push", "releasetest", '{"with":"file"}', "-a", "attachment.bin"),
|
||||
r"message #2, with an attachment of 3145728 bytes")
|
||||
latest = tool("bakashrot", "latest", "releasetest", "tester")
|
||||
expect("latest", latest, r"releasetest:tester#2")
|
||||
expect("latest", latest, r"Attachment: 3145728 bytes")
|
||||
expect("attachment", tool("bakashrot", "attachment", "releasetest", "tester", "2", "copy.bin"),
|
||||
r"Saved 3145728 bytes")
|
||||
with open(os.path.join(test, "copy.bin"), "rb") as file:
|
||||
if file.read() != attachment:
|
||||
fail("the attachment came back different")
|
||||
messages = tool("bakashrot", "messages", "releasetest", "tester")
|
||||
expect("messages", messages, r'^1\t\{"release":"test","value":42\}$')
|
||||
expect("messages", messages, r'^2\t\{"with":"file"\}$')
|
||||
expect("list", tool("bakashrot", "list", "nodes", "--json"), r'"names":\["tester"\]')
|
||||
expect("query", tool("bakashrot", "query",
|
||||
"SELECT message_data ->> '$.value' AS v FROM messages WHERE topic = 'releasetest' AND message_id = 1"),
|
||||
r'"rows":\[\["42"\]\]')
|
||||
print(" The tools: pushed, an attachment too, read back, listed, queried: OK")
|
||||
|
||||
script = ("import sys; sys.path.insert(0, sys.argv[1]); import bakashrot\n"
|
||||
"with bakashrot.Client.from_file('client.toml', sys.argv[2]) as c:\n"
|
||||
" print(c.latest('releasetest', 'tester').id, c.get_attachment('releasetest', 'tester', 2)"
|
||||
" == open('attachment.bin', 'rb').read(), c.push({'py': 1}, 'releasetest'))\n")
|
||||
got = run([sys.executable, "-B", "-c", script, os.path.join(out, "python"), os.path.join(out, LIBRARY)],
|
||||
cwd=test).strip()
|
||||
if got != "2 True 3":
|
||||
fail(f"Python through the library: unexpected output: {got}")
|
||||
print(" Python, through the library: OK")
|
||||
|
||||
installed = os.path.join(test, "wheel")
|
||||
run([sys.executable, "-m", "pip", "install", "--no-index", "--no-deps", "--disable-pip-version-check",
|
||||
"--quiet", "--target", installed, wheel])
|
||||
script = ("import os, sys; sys.path.insert(0, sys.argv[1]); import bakashrot\n"
|
||||
"with bakashrot.Client.from_file('client.toml') as c:\n"
|
||||
" inside = os.path.dirname(c._dll.path) == os.path.dirname(bakashrot.__file__)\n"
|
||||
" print(inside, c.latest('releasetest', 'tester').json()['py'], c.push({'wheel': 1}, 'releasetest'))\n")
|
||||
environment = {key: value for key, value in os.environ.items() if key != "BAKASHROT_DLL"}
|
||||
got = run([sys.executable, "-B", "-c", script, installed], cwd=test, env=environment).strip()
|
||||
if got != "True 1 4":
|
||||
fail(f"the wheel: unexpected output: {got}")
|
||||
print(" The wheel, installed by pip: OK")
|
||||
|
||||
server.send_signal(signal.CTRL_BREAK_EVENT if WINDOWS else signal.SIGTERM)
|
||||
try:
|
||||
code = server.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
fail(f"the server didn't stop when asked:\n{read_log(test)}")
|
||||
if code != 0 or "stopped" not in read_log(test):
|
||||
fail(f"the server didn't stop cleanly ({code}):\n{read_log(test)}")
|
||||
print(" Stopped cleanly: OK")
|
||||
finally:
|
||||
if server.poll() is None:
|
||||
server.kill()
|
||||
server.wait()
|
||||
log.close()
|
||||
return test
|
||||
|
||||
|
||||
def read_log(test):
|
||||
with open(os.path.join(test, "server.log"), encoding="utf-8", errors="replace") as file:
|
||||
return file.read()
|
||||
|
||||
|
||||
def archive(out):
|
||||
"""The release folder in a .zip (Windows) or .tar.gz (Linux, keeping
|
||||
the programs executable)."""
|
||||
return shutil.make_archive(out, "zip" if WINDOWS else "gztar", *os.path.split(out))
|
||||
|
||||
|
||||
def main():
|
||||
args = set(sys.argv[1:])
|
||||
if args - {"--skip-test"}:
|
||||
sys.exit(__doc__)
|
||||
# rustup's folder isn't on every shell's PATH.
|
||||
os.environ["PATH"] = os.path.join(os.path.expanduser("~"), ".cargo", "bin") + os.pathsep + os.environ["PATH"]
|
||||
if not shutil.which("cargo"):
|
||||
fail("cargo not found (rustup)")
|
||||
release, name = version(), platform_name()
|
||||
dist = os.path.join(HERE, "target", "dist")
|
||||
out = os.path.join(dist, f"bakashrot-{release}-{name}")
|
||||
for old in (out, out + ".zip", out + ".tar.gz"):
|
||||
if os.path.isdir(old):
|
||||
shutil.rmtree(old)
|
||||
elif os.path.exists(old):
|
||||
os.remove(old)
|
||||
os.makedirs(out)
|
||||
print(f"BakaShrot {release} for {name}, into {out}")
|
||||
wheel = package(build(), release, name, out)
|
||||
if "--skip-test" not in args:
|
||||
shutil.rmtree(smoke_test(out, wheel))
|
||||
print(f"Archive: {archive(out)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,12 +1,12 @@
|
||||
# BakaShrot revamp
|
||||
|
||||
Started 2026-11-13: what it should change, what's decided, what's still
|
||||
open, and the plan. Steps 0 to 10 of the plan are done (the workspace,
|
||||
open, and the plan. Steps 0 to 11 of the plan are done (the workspace,
|
||||
`bakashrot-proto`, `bakashrot-pki` and `bakashrot-cert`,
|
||||
`bakashrot-config`, `bakashrot-storage`, `bakashrot-server` and
|
||||
`bakashrot-client` answering every request but replication's,
|
||||
attachments included, the C DLL with its C, PureBasic and Python
|
||||
bindings, the `bakashrot` tool, retention), see "Plan".
|
||||
`bakashrot-client` answering every request, attachments included, the C
|
||||
DLL with its C, PureBasic and Python bindings, the `bakashrot` tool,
|
||||
retention, replication), see "Plan".
|
||||
|
||||
- **Old implementation:** `OldSource/`, PureBasic, protocol 6, schema v8.
|
||||
Frozen as the reference: it still builds and passes its suites from there
|
||||
@@ -150,7 +150,8 @@ 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`);
|
||||
(`[replication] peers`; `push_to` and `accept_from` since 2026-11-14,
|
||||
"Replication by address" below);
|
||||
- **no default topic** (dropped from the protocol too, 2026-11-13): a
|
||||
push always names its topic;
|
||||
- `[replication] replicated_topics`, optional: the only topics
|
||||
@@ -215,6 +216,34 @@ Also decided (2026-11-13):
|
||||
`getrandom`) and RDRAND, as BoringSSL and `ring` do. The jitter seeding
|
||||
took 25 ms in every process at its first connection: a tool command went
|
||||
from 36 ms to 11 ms (the old tools: 8).
|
||||
- **Replication by address** (2026-11-14), `Source/docs/config.md`:
|
||||
- **each server's config says who it replicates with**, by IP or
|
||||
hostname: `[replication] push_to`, the servers it dials and sends to
|
||||
(`host:port`, was `peers`), and `accept_from`, the servers whose
|
||||
replicated messages it takes (`"*"` for all). Not in the certificates:
|
||||
changing who replicates with whom would mean reissuing them;
|
||||
- **a link carries data one way**, from the server that dials to the one
|
||||
dialed (as the old links did); the other way is the other server's
|
||||
own `push_to`. The roles' `send_*` / `accept_*` still say which
|
||||
topics and nodes;
|
||||
- **`accept_from` is for servers only:** clients push wherever their
|
||||
roles allow, as now. A node pushing to one server only stays the
|
||||
config's rule, not checked, as in the old version
|
||||
(`OldSource/Design/ReplicationIssues.md` #1).
|
||||
- **Operations** (2026-11-14), `Source/docs/server.md`, "Running";
|
||||
`Source/README.md`, "Releases":
|
||||
- **signals only:** SIGTERM and SIGINT on Linux; Ctrl+C, Ctrl+Break or
|
||||
the console closed on Windows; each stops it cleanly. No Windows
|
||||
service mode (a tool like NSSM if needed); more only if needed later;
|
||||
- **no console commands:** the old `quit`, `restart`, `vacuum`,
|
||||
`names`, `help` dropped; maybe an admin channel later;
|
||||
- **logs to the console only**, the easiest to redirect;
|
||||
- **Docker at the end** (step 13);
|
||||
- **a release per platform** (Windows x64, Linux x86-64): the
|
||||
programs, the client library and its bindings, the example configs,
|
||||
the docs, the licenses, and a smoke test;
|
||||
- **the Python wheel has the library in it**, for a simple install;
|
||||
- **version 0.2.0.**
|
||||
|
||||
## Proposed, to confirm
|
||||
|
||||
@@ -227,14 +256,8 @@ come back as text either way; only what SQL computes would gain
|
||||
|
||||
## Open questions
|
||||
|
||||
- **"One server per node"** (a node pushes to one server only,
|
||||
`OldSource/Design/ReplicationIssues.md` #1): a CA certificate is valid on
|
||||
every server, so which server takes a node's pushes must come from the
|
||||
server's config (a list of nodes, or a role per server).
|
||||
- **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).
|
||||
- **Running as a service** (old open item 1): designed in from the start,
|
||||
e.g. a Windows service mode, a stop signal, no console needed.
|
||||
- **Tests:** keep the PowerShell suites (ported to certificates and the new
|
||||
config), move them to Rust integration tests, or both; a single runner and
|
||||
CI either way (old open item 7).
|
||||
@@ -272,9 +295,9 @@ Described in `OldSource/Notes.md` and `OldSource/Design/`, tested by
|
||||
- Storage: one writer, WAL, `Synchronous = FULL` by default, `node_heads`
|
||||
so ids never go back, the `messages` and `browse` views
|
||||
(`Design/StorageConcurrency.md`).
|
||||
- The console commands (`quit`, `restart`, `vacuum`, `names`, `help`).
|
||||
- Docker image, release zip, Python wheel (`Design/Release.md`,
|
||||
`OldSource/Docker/`).
|
||||
`OldSource/Docker/`). Not the console commands (dropped 2026-11-14,
|
||||
"Operations").
|
||||
|
||||
## The old open items
|
||||
|
||||
@@ -282,7 +305,7 @@ From `OldSource/Notes.md`, "Open items":
|
||||
|
||||
- **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, if designed in), the list and
|
||||
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
|
||||
@@ -327,9 +350,9 @@ hand in each).
|
||||
| 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 | One server per node | |
|
||||
| 12 | Operations | Console commands, service and signals, logs, Docker, release, wheel | Runs unattended, stops cleanly, the release's smoke test | The service | |
|
||||
| 13 | Finish | One test runner, end-to-end tests in CI, the bench | Push speed against the old ~17,000 msg/s (4 servers) | | |
|
||||
| 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 |
|
||||
| 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, end-to-end tests in CI, the bench, Docker | Push speed against the old ~17,000 msg/s (4 servers) | | |
|
||||
|
||||
Each step ends with its tests passing and its docs updated (the crate's
|
||||
docs, `Source/docs/`, this file's status), then a commit when the owner
|
||||
@@ -617,3 +640,90 @@ asks. Open questions get settled at the step that needs them.
|
||||
- **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)
|
||||
|
||||
`Source/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** (`Source/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)
|
||||
|
||||
`Source/docs/server.md` ("Running"), `Source/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:** `Source/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/source.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 and the CI job haven't run yet (no
|
||||
Linux machine here; the push is waiting). Docker: step 13.
|
||||
|
||||
Reference in New Issue
Block a user